This is machine translation

Translated by Microsoft
Mouseover text to see original. Click the button below to return to the English version of the page.

Note: This page has been translated by MathWorks. Click here to see
To view all translated materials including this page, select Country from the country navigator on the bottom of this page.

Customize Output During Deep Learning Network Training

This example shows how to define an output function that runs at each iteration during training of deep learning neural networks. If you specify output functions by using the 'OutputFcn' name-value pair argument of trainingOptions, then trainNetwork calls these functions once before the start of training, after each training iteration, and once after training has finished. Each time the output functions are called, trainNetwork passes a structure containing information such as the current iteration number, loss, and accuracy. You can use output functions to display or plot progress information, or to stop training. To stop training early, make your output function return true. If any output function returns true, then training finishes and trainNetwork returns the latest network.

To stop training when the loss on the validation set stops decreasing, simply specify validation data and a validation patience using the 'ValidationData' and the 'ValidationPatience' name-value pair arguments of trainingOptions, respectively. The validation patience is the number of times that the loss on the validation set can be larger than or equal to the previously smallest loss before network training stops. You can add additional stopping criteria using output functions. This example shows how to create an output function that stops training when the classification accuracy on the validation data stops improving. The output function is defined at the end of the script.

Load the training data, which contains 5000 images of digits. Set aside 1000 of the images for network validation.

[XTrain,YTrain] = digitTrain4DArrayData;

idx = randperm(size(XTrain,4),1000);
XValidation = XTrain(:,:,:,idx);
XTrain(:,:,:,idx) = [];
YValidation = YTrain(idx);
YTrain(idx) = [];

Construct a network to classify the digit image data.

layers = [
    imageInputLayer([28 28 1])
    
    convolution2dLayer(3,8,'Padding','same')
    batchNormalizationLayer
    reluLayer   
    
    maxPooling2dLayer(2,'Stride',2)
    
    convolution2dLayer(3,16,'Padding','same')
    batchNormalizationLayer
    reluLayer   
    
    maxPooling2dLayer(2,'Stride',2)
    
    convolution2dLayer(3,32,'Padding','same')
    batchNormalizationLayer
    reluLayer   
    
    fullyConnectedLayer(10)
    softmaxLayer
    classificationLayer];

Specify options for network training. To validate the network at regular intervals during training, specify validation data. Choose the 'ValidationFrequency' value so that the network is validated once per epoch.

To stop training when the classification accuracy on the validation set stops improving, specify stopIfAccuracyNotImproving as an output function. The second input argument of stopIfAccuracyNotImproving is the number of times that the accuracy on the validation set can be smaller than or equal to the previously highest accuracy before network training stops. Choose any large value for the maximum number of epochs to train. Training should not reach the final epoch because training stops automatically.

miniBatchSize = 128;
validationFrequency = floor(numel(YTrain)/miniBatchSize);
options = trainingOptions('sgdm', ...
    'InitialLearnRate',0.01, ...
    'MaxEpochs',100, ...
    'MiniBatchSize',miniBatchSize, ...
    'VerboseFrequency',validationFrequency, ...
    'ValidationData',{XValidation,YValidation}, ...
    'ValidationFrequency',validationFrequency, ...
    'Plots','training-progress', ...
    'OutputFcn',@(info)stopIfAccuracyNotImproving(info,3));

Train the network. Training stops when the validation accuracy stops increasing.

net = trainNetwork(XTrain,YTrain,layers,options);
Training on single CPU.
Initializing input data normalization.
|======================================================================================================================|
|  Epoch  |  Iteration  |  Time Elapsed  |  Mini-batch  |  Validation  |  Mini-batch  |  Validation  |  Base Learning  |
|         |             |   (hh:mm:ss)   |   Accuracy   |   Accuracy   |     Loss     |     Loss     |      Rate       |
|======================================================================================================================|
|       1 |           1 |       00:00:02 |       10.94% |       13.20% |       2.9520 |       2.5400 |          0.0100 |
|       1 |          31 |       00:00:12 |       71.09% |       75.30% |       0.8454 |       0.8358 |          0.0100 |
|       2 |          62 |       00:00:20 |       90.62% |       89.70% |       0.3492 |       0.4296 |          0.0100 |
|       3 |          93 |       00:00:31 |       96.88% |       94.30% |       0.1888 |       0.2550 |          0.0100 |
|       4 |         124 |       00:00:44 |       99.22% |       96.30% |       0.1182 |       0.1918 |          0.0100 |
|       5 |         155 |       00:00:56 |      100.00% |       97.00% |       0.0868 |       0.1568 |          0.0100 |
|       6 |         186 |       00:01:06 |      100.00% |       97.40% |       0.0604 |       0.1227 |          0.0100 |
|       7 |         217 |       00:01:15 |       99.22% |       97.90% |       0.0554 |       0.1014 |          0.0100 |
|       8 |         248 |       00:01:21 |       99.22% |       98.40% |       0.0459 |       0.0861 |          0.0100 |
|       9 |         279 |       00:01:32 |      100.00% |       98.60% |       0.0326 |       0.0740 |          0.0100 |
|      10 |         310 |       00:01:39 |      100.00% |       98.80% |       0.0261 |       0.0642 |          0.0100 |
|      11 |         341 |       00:01:47 |      100.00% |       98.90% |       0.0223 |       0.0564 |          0.0100 |
|      12 |         372 |       00:01:55 |      100.00% |       99.10% |       0.0190 |       0.0500 |          0.0100 |
|      13 |         403 |       00:02:01 |      100.00% |       99.30% |       0.0167 |       0.0450 |          0.0100 |
|      14 |         434 |       00:02:06 |      100.00% |       99.30% |       0.0151 |       0.0413 |          0.0100 |
|      15 |         465 |       00:02:10 |      100.00% |       99.40% |       0.0140 |       0.0388 |          0.0100 |
|      16 |         496 |       00:02:14 |      100.00% |       99.50% |       0.0129 |       0.0368 |          0.0100 |
|      17 |         527 |       00:02:21 |      100.00% |       99.50% |       0.0121 |       0.0353 |          0.0100 |
|      18 |         558 |       00:02:26 |      100.00% |       99.50% |       0.0113 |       0.0341 |          0.0100 |
|      19 |         589 |       00:02:31 |      100.00% |       99.50% |       0.0107 |       0.0331 |          0.0100 |
|======================================================================================================================|

Define Output Function

Define the output function stopIfAccuracyNotImproving(info,N), which stops network training if the best classification accuracy on the validation data does not improve for N network validations in a row. This criterion is similar to the built-in stopping criterion using the validation loss, except that it applies to the classification accuracy instead of the loss.

function stop = stopIfAccuracyNotImproving(info,N)

stop = false;

% Keep track of the best validation accuracy and the number of validations for which
% there has not been an improvement of the accuracy.
persistent bestValAccuracy
persistent valLag

% Clear the variables when training starts.
if info.State == "start"
    bestValAccuracy = 0;
    valLag = 0;
    
elseif ~isempty(info.ValidationLoss)
    
    % Compare the current validation accuracy to the best accuracy so far,
    % and either set the best accuracy to the current accuracy, or increase
    % the number of validations for which there has not been an improvement.
    if info.ValidationAccuracy > bestValAccuracy
        valLag = 0;
        bestValAccuracy = info.ValidationAccuracy;
    else
        valLag = valLag + 1;
    end
    
    % If the validation lag is at least N, that is, the validation accuracy
    % has not improved for at least N validations, then return true and
    % stop training.
    if valLag >= N
        stop = true;
    end
    
end

end

See Also

|

Related Topics