Question
When trying to plot the mini batch loss vs iteration while training a CNN, an error occurs. I modified the sample graph given in the training documentation to plot the loss instead of the accuracy. My modification is given below: function plotTrainingLoss(info) persistent plotObj info.State == "start" plotObj = animatedline('Color','r'); xlabel("Iteration") ylabel("Loss") title("Training loss evolution") elseif info.State == "iteration" addpoints(plotObj,info.Iteration,info.TrainingLoss) drawnow limitrate nocallbacks fprintf('%d \n',info.TrainingLoss) end end Given that info.TrainingLoss a possible output argument, this should simply work. I'm also printing the value to the screen which works well. But the graph fails with the following error: Initializing image normalization. |=========================================================================================| | Epoch | Iteration | Time Elapsed | Mini-batch | Mini-batch | Base Learning| | | | (seconds) | Loss | Accuracy | Rate | |=========================================================================================| | 1 | 1 | 0.33 | 2.0795 | 14.84% | 0.0010 | Error using trainNetwork (line 133) Invalid type for argument Y. Type should be double. Error in TrainOwnCNN_Advanced (line 108) CNN = trainNetwork(trainingData,layers,options); I tried debugging, and the TrainingLoss is a single gpuArray object. But trying info.BaseLearnRate prints to screen without issues, but also gives the same error when trying to plot. Switching it to info.TrainingAccuracy magically works like in the help documentation. I'm doing the function call correctly otherwise the rest would fail which is not the case and TrainingAccuracy works. The plot expects a double which info.TrainingAccuracy seems to be, but the rest isn't? Can anyone shed some light on this? Printing to screen while plotting info.TrainingAccuracy looks like below: Initializing image normalization. |=========================================================================================| | Epoch | Iteration | Time Elapsed | Mini-batch | Mini-batch | Base Learning| | | | (seconds) | Loss | Accuracy | Rate | |=========================================================================================| | 1 | 1 | 0.23 | 2.0832 | 7.81% | 0.0010 | 2.083199e+00 2.083350e+00 2.082194e+00 2.081159e+00 2.080728e+00 2.080156e+00 2.079782e+00 2.080018e+00 2.077905e+00 2.078161e+00 2.078137e+00
Expert Answer
Neeta Dsouza
PhD Expert
Answered Sep 12, 2026
To plot training loss for a Convolutional Neural Network (CNN) in MATLAB, set 'Plots', 'training-progress' inside trainingOptions() to view live real-time loss and accuracy curves. To generate custom publication-ready plots after training, capture the training output struct using [net, info] = trainNetwork(...) and plot info.TrainingLoss directly.
Two Primary Plotting Approaches
- Live Interactive Monitor: Adding
'Plots', 'training-progress'launches MATLAB's dedicated Deep Learning Monitor window. It plots mini-batch loss, smoothed loss, mini-batch accuracy, validation metrics, and elapsed training time on the fly. - Post-Training Custom Figure: The
infostructure returned bytrainNetworkstores numerical arrays forTrainingLoss,TrainingAccuracy,ValidationLoss, andValidationAccuracy. This allows full control over fonts, axis limits, line weights, and multi-axis formatting for IEEE or Elsevier papers.
Executable MATLAB Code: Live Monitoring & Custom Loss Curves
% =========================================================================
% Plotting CNN Training Loss and Accuracy in MATLAB
% =========================================================================
% 1. Load sample digit image data
[XTrain, YTrain] = digitTrain4DArrayData;
[XValidation, YValidation] = digitTest4DArrayData;
% 2. Define a simple Convolutional Neural Network architecture
layers = [
imageInputLayer([28 28 1], 'Name', 'input')
convolution2dLayer(3, 16, 'Padding', 'same', 'Name', 'conv1')
batchNormalizationLayer('Name', 'bn1')
reluLayer('Name', 'relu1')
maxPooling2dLayer(2, 'Stride', 2, 'Name', 'pool1')
convolution2dLayer(3, 32, 'Padding', 'same', 'Name', 'conv2')
batchNormalizationLayer('Name', 'bn2')
reluLayer('Name', 'relu2')
fullyConnectedLayer(10, 'Name', 'fc')
softmaxLayer('Name', 'softmax')
classificationLayer('Name', 'output')
];
% 3. Configure training options with both Live Plotting and Validation Tracking
options = trainingOptions('sgdm', ...
'InitialLearnRate', 0.01, ...
'MaxEpochs', 6, ...
'MiniBatchSize', 128, ...
'Shuffle', 'every-epoch', ...
'ValidationData', {XValidation, YValidation}, ...
'ValidationFrequency', 20, ...
'Plots', 'training-progress', ... % Live real-time plot window
'Verbose', false);
% 4. Train the network and capture the 'info' structure
[net, info] = trainNetwork(XTrain, YTrain, layers, options);
% =========================================================================
% 5. Create a Custom Publication-Quality Loss & Accuracy Plot
% =========================================================================
figure('Color', 'w', 'Position', [100, 100, 800, 450]);
% Left Y-Axis: Training and Validation Loss
yyaxis left
plot(info.TrainingLoss, 'LineWidth', 1.2, 'Color', [0.85, 0.32, 0.1]);
hold on;
valIterations = 1:options.ValidationFrequency:length(info.TrainingLoss);
valLoss = info.ValidationLoss(~isnan(info.ValidationLoss));
valIterIndices = linspace(1, length(info.TrainingLoss), length(valLoss));
plot(valIterIndices, valLoss, 'o--', 'LineWidth', 1.5, ...
'MarkerSize', 5, 'Color', [0.63, 0.08, 0.18]);
ylabel('Cross-Entropy Loss', 'FontWeight', 'bold');
ylim([0, max(info.TrainingLoss) * 1.1]);
% Right Y-Axis: Training and Validation Accuracy
yyaxis right
smoothedTrainAcc = movmean(info.TrainingAccuracy, 5); % 5-iteration smoothing
plot(smoothedTrainAcc, 'LineWidth', 1.2, 'Color', [0.0, 0.45, 0.74]);
valAcc = info.ValidationAccuracy(~isnan(info.ValidationAccuracy));
plot(valIterIndices, valAcc, 's--', 'LineWidth', 1.5, ...
'MarkerSize', 5, 'Color', [0.47, 0.67, 0.19]);
ylabel('Accuracy (%)', 'FontWeight', 'bold');
ylim([0, 105]);
grid on;
xlabel('Iteration', 'FontWeight', 'bold');
title('CNN Training Loss and Classification Accuracy Convergence');
legend({'Training Loss', 'Validation Loss', 'Training Acc (Smoothed)', 'Validation Acc'}, ...
'Location', 'east');
% Optional: Export vector graphic for papers
% exportgraphics(gcf, 'cnn_loss_curve.eps', 'Resolution', 300);
Key Details for Technical Optimization
- Smoothing High-Frequency Jitter: Mini-batch loss frequently fluctuates between individual batches. Use
movmean(info.TrainingLoss, 10)to calculate an exponential or moving average baseline that reveals the true underlying learning trajectory. - Handling NaN Values in Validation Vectors: Because validation is evaluated periodically rather than every iteration, the
info.ValidationLossarray containsNaNvalues on non-validation steps. Always filter them using~isnan(info.ValidationLoss)before plotting lines. - Custom Training Loops (dlnetwork): If training with custom loss functions via
dlgradientanddlfevalinstead oftrainNetwork, use MATLAB'sanimatedlineandaddpointsinside the epoch loop to stream loss curves directly to an active figure.
100% Run Guarantee
3-Hour Fast-Track Delivery
Need a Custom Version or Complete Simulation for This Problem?
Our 500+ PhD engineers build, debug, and optimize working MATLAB scripts and Simulink (.slx) models tailored to your exact assignment rubrics with zero plagiarism.
Tested on MATLAB R2024b / R2026a
Turnitin 0% Plagiarism Report
Free 7-Day Revisions Guarantee
Have a different question? Ask here
Related traininfo Questions & Solutions
Browse All →
Explore similar technical troubleshooting questions and verified MATLAB solutions:
Ready-to-Run MATLAB & Simulink Projects
Browse All Projects →