Main Content

trainSSDObjectDetector

Train an SSD deep learning object detector

Since R2020a

Description

Train a Detector

example

trainedDetector = trainSSDObjectDetector(trainingData,detector,options) trains a single shot multibox detector (SSD) using deep learning. You can train an SSD detector to detect multiple object classes. Use this syntax to train either an untrained or pretrained SSD object detection network. You can also use this syntax to fine-tune a network with additional training data or to perform more training iterations to improve detector accuracy.

This function requires that you have Deep Learning Toolbox™. It is recommended that you also have Parallel Computing Toolbox™ to use with a CUDA®-enabled NVIDIA® GPU. For information about the supported compute capabilities, see GPU Computing Requirements (Parallel Computing Toolbox).

trainedDetector = trainSSDObjectDetector(trainingData,net,options) trains a SSD object detector specified as a LayerGraph (Deep Learning Toolbox) object. This syntax is not recommended and will be removed in a future release.

Resume Training a Detector

trainedDetector = trainSSDObjectDetector(trainingData,checkpoint,options) resumes training from a detector checkpoint.

Additional Properties

trainedDetector = trainSSDObjectDetector(___,Name,Value) uses additional options specified by one or more Name,Value pair arguments and any of the previous inputs.

[___,info] = trainSSDObjectDetector(___) also returns information on the training progress, such as training loss and accuracy, for each iteration.

Examples

collapse all

This example shows how to train a SSD object detector on a vehicle data set and use for detecting vehicles in an image.

Load the training data into the workspace.

data = load("vehicleTrainingData.mat");
trainingData = data.vehicleTrainingData;

Specify the directory in which training samples are stored. Add full path to the file names in training data.

dataDir = fullfile(toolboxdir("vision"),"visiondata");
trainingData.imageFilename = fullfile(dataDir,trainingData.imageFilename);

Create an image datastore using the files from the table.

imds = imageDatastore(trainingData.imageFilename);

Create a box label datastore using the label columns from the table.

blds = boxLabelDatastore(trainingData(:,2:end));

Combine the datastores.

ds = combine(imds,blds);

Specify a base network for creating a SSD object detector.

baseNetwork = layerGraph(resnet50);

Specify the names of the classes to detect.

classNames = {"vehicle"};

Specify the anchor boxes to use for training network.

anchorBoxes = {[30 60; 60 30; 50 50; 100 100], ...
               [40 70; 70 40; 60 60; 120 120]};

Specify the names of the feature extraction layers to connect to the detection subnetwork.

layersToConnect =  ["activation_22_relu" "activation_40_relu"];

Create a SSD object detector by using the ssdObjectDetector function.

detector = ssdObjectDetector(baseNetwork,classNames,anchorBoxes, ...
           DetectionNetworkSource=layersToConnect);

Specify the training options.

options = trainingOptions("sgdm", ...
          InitialLearnRate=0.001, ...
          MiniBatchSize=16, ...
          Verbose=true, ...
          MaxEpochs=30, ...
          Shuffle="never", ...
          VerboseFrequency=10);

Train the SSD object detector.

[detector,info] = trainSSDObjectDetector(ds,detector,options);
*************************************************************************
Training an SSD Object Detector for the following object classes:

* vehicle

Training on single CPU.
Initializing input data normalization.
|=======================================================================================================|
|  Epoch  |  Iteration  |  Time Elapsed  |  Mini-batch  |  Mini-batch  |  Mini-batch  |  Base Learning  |
|         |             |   (hh:mm:ss)   |     Loss     |   Accuracy   |     RMSE     |      Rate       |
|=======================================================================================================|
|       1 |           1 |       00:00:04 |      42.7980 |       39.23% |         2.10 |          0.0010 |
|       1 |          10 |       00:00:38 |       3.1443 |       99.48% |         1.48 |          0.0010 |
|       2 |          20 |       00:01:22 |       2.4110 |       99.45% |         1.16 |          0.0010 |
|       2 |          30 |       00:01:58 |       3.6181 |       99.33% |         1.18 |          0.0010 |
|       3 |          40 |       00:02:40 |       2.0148 |       99.48% |         0.88 |          0.0010 |
|       3 |          50 |       00:03:17 |       3.9796 |       99.42% |         0.75 |          0.0010 |
|       4 |          60 |       00:04:00 |       4.0148 |       99.60% |         0.69 |          0.0010 |
|       4 |          70 |       00:04:36 |       1.6519 |       99.50% |         0.86 |          0.0010 |
|       5 |          80 |       00:05:17 |       1.8625 |       99.63% |         0.84 |          0.0010 |
|       5 |          90 |       00:05:51 |       1.3560 |       99.65% |         0.73 |          0.0010 |
|       6 |         100 |       00:06:32 |       1.2340 |       99.82% |         0.64 |          0.0010 |
|       7 |         110 |       00:07:13 |       1.6821 |       99.59% |         0.71 |          0.0010 |
|       7 |         120 |       00:07:48 |       1.4340 |       99.86% |         0.63 |          0.0010 |
|       8 |         130 |       00:08:31 |       1.1701 |       99.90% |         0.53 |          0.0010 |
|       8 |         140 |       00:09:07 |       1.0795 |       99.86% |         0.58 |          0.0010 |
|       9 |         150 |       00:09:48 |       1.0765 |       99.84% |         0.66 |          0.0010 |
|       9 |         160 |       00:10:22 |       0.9774 |       99.88% |         0.55 |          0.0010 |
|      10 |         170 |       00:11:03 |       0.7405 |       99.87% |         0.51 |          0.0010 |
|      10 |         180 |       00:11:37 |       0.8487 |       99.83% |         0.57 |          0.0010 |
|=======================================================================================================|
Training finished: Max epochs completed.
Detector training complete.
*************************************************************************

Verify the training accuracy by inspecting the training loss for each iteration.

figure
plot(info.TrainingLoss)
grid on
xlabel("Number of Iterations")
ylabel("Training Loss for Each Iteration")
SSD training loss

Read a test image.

img = imread("ssdTestDetect.png");

Detect vehicles in the test image by using the trained SSD object detector.

[bboxes,scores] = detect(detector,img);

Display the detection results.

if(~isempty(bboxes))
    img = insertObjectAnnotation(img,"rectangle",bboxes,scores);
end
figure
imshow(img)
SSD output

Input Arguments

collapse all

Labeled ground truth images, specified as a datastore or a table.

  • If you use a datastore, your data must be set up so that calling the datastore with the read and readall functions returns a cell array or table with two or three columns. When the output contains two columns, the first column must contain bounding boxes, and the second column must contain labels, {boxes,labels}. When the output contains three columns, the second column must contain the bounding boxes, and the third column must contain the labels. In this case, the first column can contain any type of data. For example, the first column can contain images or point cloud data.

    databoxeslabels

    The first column must be images.

    M-by-4 matrices of bounding boxes of the form [x, y, width, height], where [x,y] represent the top-left coordinates of the bounding box.

    The third column must be a cell array that contains M-by-1 categorical vectors containing object class names. All categorical data returned by the datastore must contain the same categories.

    For more information, see Datastores for Deep Learning (Deep Learning Toolbox).

Untrained or pretrained SSD object detector, specified as a ssdObjectDetector object.

Untrained or pretrained SSD network, specified as a LayerGraph object. The layer graph contains the architecture of the SSD multibox network.

Training options, specified as a TrainingOptionsSGDM, TrainingOptionsRMSProp, or TrainingOptionsADAM object returned by the trainingOptions (Deep Learning Toolbox) function. To specify the solver name and other options for network training, use the trainingOptions (Deep Learning Toolbox) function.

Note

The trainSSDObjectDetector function does not support these training options:

  • Datastore inputs are not supported when you set the DispatchInBackground training option to true.

  • Datastore inputs are not supported if the Shuffle training option is set to "never" when the ExecutionEnvironment training option is 'multi-gpu'. For more information about using datastore for parallel training, see Use Datastore for Parallel Training and Background Dispatching (Deep Learning Toolbox).

Saved detector checkpoint, specified as an ssdObjectDetector object. To periodically save a detector checkpoint during training, specify CheckpointPath. To control how frequently check points are saved see the CheckPointFrequency and CheckPointFrequencyUnit training options.

To load a checkpoint for a previously trained detector, load the MAT-file from the checkpoint path. For example, if the CheckpointPath property of the object specified by options is '/checkpath', you can load a checkpoint MAT-file by using this code.

data = load('/checkpath/ssd_checkpoint__216__2018_11_16__13_34_30.mat');
checkpoint = data.detector;

The name of the MAT-file includes the iteration number and timestamp of when the detector checkpoint was saved. The detector is saved in the detector variable of the file. Pass this file back into the trainSSDObjectDetector function:

ssdDetector = trainSSDObjectDetector(trainingData,checkpoint,options);

Name-Value Arguments

Specify optional pairs of arguments as Name1=Value1,...,NameN=ValueN, where Name is the argument name and Value is the corresponding value. Name-value arguments must appear after other arguments, but the order of the pairs does not matter.

Before R2021a, use commas to separate each name and value, and enclose Name in quotes.

Example: 'PositiveOverlapRange',[0.5 1] sets the vertical axis direction to up.

Range of bounding box overlap ratios between 0 and 1, specified as a two-element vector. Anchor boxes that overlap with ground truth bounding boxes within the specified range are used as positive training samples. The function computes the overlap ratio using the intersection-over-union between two bounding boxes.

Range of bounding box overlap ratios between 0 and 1, specified as a two-element vector. Anchor boxes that overlap with ground truth bounding boxes within the specified range are used as negative training samples. The function computes the overlap ratio using the intersection-over-union between two bounding boxes.

Detector training experiment monitoring, specified as an experiments.Monitor (Deep Learning Toolbox) object for use with the Experiment Manager (Deep Learning Toolbox) app. You can use this object to track the progress of training, update information fields in the training results table, record values of the metrics used by the training, and to produce training plots. For an example using this app, see Train Object Detectors in Experiment Manager.

Information monitored during training:

  • Training loss at each iteration.

  • Training accuracy at each iteration.

  • Training root mean square error (RMSE) for the box regression layer.

  • Learning rate at each iteration.

Validation information when the training options input contains validation data:

  • Validation loss at each iteration.

  • Validation accuracy at each iteration.

  • Validation RMSE at each iteration.

Output Arguments

collapse all

Trained SSD object detector, returned as ssdObjectDetector object. You can train a SSD object detector to detect multiple object classes.

Training progress information, returned as a structure array with eight fields. Each field corresponds to a stage of training.

  • TrainingLoss — Training loss at each iteration is calculated as the sum of regression loss and classification loss. To compute the regression loss, the trainSSDObjectDetector function uses smooth L1 loss function. To compute the classification loss the trainSSDObjectDetector function uses the softmax and binary cross-entropy loss function.

  • TrainingAccuracy — Training set accuracy at each iteration.

  • TrainingRMSE — Training root mean squared error (RMSE) is the RMSE calculated from the training loss at each iteration.

  • BaseLearnRate — Learning rate at each iteration.

  • ValidationLoss — Validation loss at each iteration.

  • ValidationAccuracy — Validation accuracy at each iteration.

  • ValidationRMSE — Validation RMSE at each iteration.

  • FinalValidationLoss — Final validation loss at end of the training.

  • FinalValidationRMSE — Final validation RMSE at end of the training.

Each field is a numeric vector with one element per training iteration. Values that have not been calculated at a specific iteration are assigned as NaN. The struct contains ValidationLoss, ValidationAccuracy, ValidationRMSE, FinalValidationLoss, and FinalValidationRMSE fields only when options specifies validation data.

References

[1] W. Liu, E. Anguelov, D. Erhan, C. Szegedy, S. Reed, C.Fu, and A.C. Berg. "SSD: Single Shot MultiBox Detector." European Conference on Computer Vision (ECCV), Springer Verlag, 2016

Version History

Introduced in R2020a

expand all