trainYOLOv3ObjectDetector - Train YOLO v3 object detector - MATLAB (original) (raw)

Train YOLO v3 object detector

Since R2024a

Syntax

Description

[detector](#mw%5F724cd77b-942b-4675-8a3f-9e896b4ea606) = trainYOLOv3ObjectDetector([trainingData](#mw%5F33a2bca3-1c4b-44a6-97d9-53a7c89a6e45),[detector](#mw%5F724cd77b-942b-4675-8a3f-9e896b4ea606),[options](#mw%5F181c28b1-bd5e-4f9e-a4de-c65712a83b62)) returns an object detector trained using the you only look once version 3 (YOLO v3) network specified by detector. The input detector can be an untrained or pretrained YOLO v3 object detector. The options input specifies training parameters for the detection network.

You can also use this syntax to fine-tune a pretrained YOLO v3 object detector.

example

[detector](#mw%5F724cd77b-942b-4675-8a3f-9e896b4ea606) = trainYOLOv3ObjectDetector([trainingData](#mw%5F33a2bca3-1c4b-44a6-97d9-53a7c89a6e45),[checkpoint](#mw%5Ff1ae70c4-ba2f-4656-bf44-ea622bf8d287),[options](#mw%5F181c28b1-bd5e-4f9e-a4de-c65712a83b62)) resumes training from the saved detector checkpoint.

You can use this syntax to:

[[detector](#mw%5F724cd77b-942b-4675-8a3f-9e896b4ea606),[info](#mw%5F8f326627-f0bd-4570-9d85-99977e789fa1)] = trainYOLOv3ObjectDetector(___) also returns information on training progress, using any combination of input arguments from previous syntaxes, such as the training loss and learning rate for each iteration.

[___] = trainYOLOv3ObjectDetector(___,[Name=Value](#namevaluepairarguments)) specifies options using one or more name-value arguments in addition to any combination of arguments from previous syntaxes. For example, ExperimentMonitor=[] specifies not to track metrics with Experiment Manager.

Note

This functionality requires Deep Learning Toolbox™. To use the pretrained YOLO v3 deep learning networks trained on COCO dataset, you must install the Computer Vision Toolbox™ Model for YOLO v3 Object Detection from Add-On Explorer. For more information about installing add-ons, seeGet and Manage Add-Ons.

example

Examples

collapse all

Train a pretrained YOLO v3 object detector to detect vehicles in an image. The object detector uses a tiny YOLO v3 network, trained on the COCO data set as the base network.

Load a .mat file containing training data, and extract the training data into the workspace. The training data is a table in which the first column contains the training images and the remaining columns contain the corresponding labeled bounding boxes.

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

Specify the directory that contains the training samples. Add the full paths to the filenames in the 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 image and box label datastores.

Specify the anchor boxes to use for training the network. You must assign at least one anchor box to each output layer of the network. Because the tiny YOLO v3 network contains two output layers, specify the anchor boxes as a two-element cell array.

anchorBoxes = {[91 115; 82 106; 58 83];[41 58; 24 32;19 23]};

Specify the names of the classes to detect.

Create a pretrained YOLO v3 deep learning network configured to retrain on the new dataset by using the yolov3ObjectDetector function.

detector = yolov3ObjectDetector("tiny-yolov3-coco",classes,anchorBoxes); detector.Network

ans = dlnetwork with properties:

     Layers: [44×1 nnet.cnn.layer.Layer]
Connections: [45×2 table]
 Learnables: [48×3 table]
      State: [22×3 table]
 InputNames: {'input'}
OutputNames: {'convOut1'  'convOut2'}
Initialized: 1

View summary with summary.

Specify the training options.

options = trainingOptions("adam", ... InitialLearnRate=0.001, ... MiniBatchSize=8, ... MaxEpochs=30, ... BatchNormalizationStatistics="moving", ... ResetInputNormalization=false, ... VerboseFrequency=30);

Retrain the pretrained YOLO v3 network on the new data set by using the trainYOLOv3ObjectDetector function.

trainedDetector = trainYOLOv3ObjectDetector(ds,detector,options);


Training a YOLO v3 Object Detector for the following object classes:


Detector training complete.


Read a test image. Use the trained YOLO v3 object detector to detect vehicles and display the detection results.

I = imread('highway.png'); [bboxes, scores, labels] = detect(trainedDetector,I,Threshold=0.05); results = table(bboxes,labels,scores)

results=2×3 table bboxes labels scores ________________________ _______ _______

131     73    107     83    vehicle    0.15463
 93     84     44     73    vehicle    0.12592

detectedImg = insertObjectAnnotation(I,"Rectangle",bboxes,labels,LineWidth=3,AnnotationColor="cyan"); figure imshow(detectedImg)

Perform transfer learning to fine-tune a pretrained YOLO v3 object detector by freezing its backbone. The detector has been trained for detecting stop signs and the front views and rear views of cars in an image. The detector uses a DarkNet-53 network, trained on the COCO data set, as the base network.

Load a .mat file containing training data, and extract the training data into the workspace. The training data is a table in which the first column contains the training images and the remaining columns contain the corresponding labeled bounding boxes.

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

Specify the directory that contains the training samples. Add the full paths to the filenames in the 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 image and box label datastores.

Specify the input size to use for resizing the training images. You must also resize the bounding boxes based on the specified input size.

Resize and rescale the training images and bounding boxes by using the preprocessData helper function. Convert the preprocessed data to a datastore object by using the transform function.

trainingDataForEstimation = transform(ds,@(data)preprocessData(data,inputSize));

Specify the anchor boxes to use for training the network. You must assign at least one anchor box to each output layer of the network. Because the darknet53-coco YOLO v3 network contains three output layers, specify the anchor boxes as a three-element cell array.

numAnchors = 9; [anchors,meanIoU] = estimateAnchorBoxes(trainingDataForEstimation,numAnchors);

Use larger anchor boxes at lower scale and smaller anchor boxes at higher scale output layers. To do so, sort anchors by area, in descending order, and assign the first three to the first output layer, the next three to the second output layer, and the last three to the third output layer of the network.

area = anchors(:,1).*anchors(:,2); [~,idx] = sort(area,"descend"); anchors = anchors(idx,:); anchorBoxes = {anchors(1:3,:); anchors(4:6,:); anchors(7:9,:)};

Specify the names of the classes to detect.

classes = {'stopSign','carRear','carFront'};

Create a pretrained YOLO v3 deep learning network configured to retrain on the new dataset by using the yolov3ObjectDetector function.

detector = yolov3ObjectDetector("darknet53-coco",classes,anchorBoxes,InputSize=inputSize); detector.Network

ans = dlnetwork with properties:

     Layers: [247×1 nnet.cnn.layer.Layer]
Connections: [273×2 table]
 Learnables: [294×3 table]
      State: [144×3 table]
 InputNames: {'input'}
OutputNames: {'convOut1'  'convOut2'  'convOut3'}
Initialized: 1

View summary with summary.

Specify the training options.

options = trainingOptions("sgdm", ... InitialLearnRate=0.0001, ... MiniBatchSize=4, ... MaxEpochs=30, ... BatchNormalizationStatistics="moving", ... ResetInputNormalization=false, ... VerboseFrequency=30);

Retrain the pretrained YOLO v3 network on the new data set by using the trainYOLOv3ObjectDetector function. To freeze the backbone of the pretrained YOLO v3 network during training, specify the FreezeSubNetwork name-value argument to "backbone". The weights of the frozen backbone layers do not change during training, which increases training speed and reduces GPU memory consumption.

trainedDetector = trainYOLOv3ObjectDetector(ds,detector,options,FreezeSubNetwork="backbone");


Training a YOLO v3 Object Detector for the following object classes:


Detector training complete.


Read a test image. Use the fine-tuned YOLO v3 object detector to detect the stop signs and the front views and rear views of cars, and display the detection results.

I = imread("Test_Image.jpg"); [bboxes,scores,labels] = detect(trainedDetector,I,Threshold=0.2); detectedImg = insertObjectAnnotation(I,"Rectangle",bboxes,labels,LineWidth=3,AnnotationColor="cyan"); results = table(bboxes,labels,scores)

results=3×3 table bboxes labels scores ________________________ ________ _______

 88    388    124     65    carFront    0.39835
430    366    102     87    carRear     0.72145
795    293     65     58    stopSign    0.97976

figure imshow(detectedImg)

Supporting Function

function data = preprocessData(data,targetSize) for num = 1:size(data,1) I = data{num,1}; imgSize = size(I); bboxes = data{num,2}; I = im2single(imresize(I,targetSize(1:2))); scale = targetSize(1:2)./imgSize(1:2); bboxes = bboxresize(bboxes,scale); data(num,1:2) = {I bboxes}; end end

Input Arguments

collapse all

Labeled ground truth images, specified as a datastore. Data must be set up so that calling the datastore with the read and readall functions returns a cell array or table with three columns in the format {data boxes labels}.

The first column, data, must contain the image data, stored as a cell array. The second column, boxes, must contain the bounding boxes, stored as a matrix with dimensions determined by the type of bounding box. The third column, labels, must be a cell array in which each cell contains an M_-by-1 categorical vector of object class names, where_M is the number of bounding boxes. All the categorical data returned by the datastore must use the same categories.

This table describes the format of each element of the bounding boxes column.

Bounding Box Description
Axis-aligned rectangle Defined in spatial coordinates as an _M_-by-4 numeric matrix with rows of the form [x y w _h_], where: M is the number of axis-aligned rectangles.x and y specify the upper-left corner of the rectangle.w specifies the width of the rectangle, which is its length along the _x_-axis.h specifies the height of the rectangle, which is its length along the _y_-axis.
Rotated rectangle Defined in spatial coordinates as an _M_-by-5 numeric matrix with rows of the form [xctr yctr w h _yaw_], where: M is the number of rotated rectangles.xctr and yctr specify the center of the rectangle.w specifies the width of the rectangle, which is its length along the _x_-axis before rotation.h specifies the height of the rectangle, which is its length along the _y_-axis before rotation.yaw specifies the rotation angle in degrees. The rotation is clockwise-positive around the center of the bounding box. Square rectangle rotated by -30 degrees.

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

Note

You can convert a pretrained, axis-aligned network to a rotated rectangle network by providing rotated rectangle training data. When you provide the rotated rectangle training data, the trainYOLOv3ObjectDetector function fine-tunes the network, enabling the rotated rectangle detections.

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 thetrainingOptions function. You must set theBatchNormalizationStatistics property of the object to"moving".

Saved detector checkpoint, specified as a yolov3ObjectDetector object. To periodically save a detector checkpoint during training as a MAT file, specify a location for the file using theCheckpointPath property of the training options objectoptions. To control how frequently the detector saves checkpoints, use the CheckPointFrequency andCheckPointFrequencyUnit properties of the training options object.

To load a checkpoint for a previously trained detector, load the MAT file from the checkpoint path. For example, this code loads the checkpoint MAT file of a detector from the "checkpath" folder in the current working directory to which the detector saves checkpoints during training.

data = load("checkpath/net_checkpoint__6__2023_11_17__16_03_08.mat"); checkpoint = data.net;

The name of each MAT file includes the iteration number and timestamp at which the detector saves the checkpoint. The file stores the detector in thenet variable. To continue training the network, specify the detector extracted from the file to the trainYOLOv3ObjectDetector function:

yoloDetector = trainYOLOv3ObjectDetector(trainingData,checkpoint,options);

Name-Value Arguments

collapse all

Specify optional pairs of arguments asName1=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.

Example: ExperimentMonitor=[] specifies not to track metrics with Experiment Manager.

Subnetworks to freeze during training, specified as one of these values:

The weight of layers in frozen subnetworks does not change during training.

Note

You cannot use the FreezeSubNetwork argument values"backbone" and "backboneAndNeck" with a custom YOLO v3 object detector created using the syntaxyolov3ObjectDetector(net,classes,aboxes).

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.

The app monitors this Information during training:

Output Arguments

collapse all

Trained YOLO v3 object detector, returned as a yolov3ObjectDetector object. You can train a YOLO v3 object detector to detect multiple object classes.

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

Each field is a numeric vector with one element per training iteration. If the function does not calculate a metric at a specific iteration, the corresponding element of that vector has a value of NaN. The structure contains theValidationLoss and FinalValidationLoss fields only when options specifies validation data.

Tips

Extended Capabilities

Version History

Introduced in R2024a

expand all

Support for using MATLAB® Compiler™ will be removed in a future release.

Starting in R2024b, you can use an mAPObjectDetectionMetric object to track the mean average precision (mAP) metric while training the YOLO v3 object detector. To use the metric, specify it to the Metrics (Deep Learning Toolbox) name-value argument of the trainingOptions (Deep Learning Toolbox) function.

See Also

Apps

Functions

Objects

Topics