How do I draw the MSE curve for an LSTM classification code in Matlab?
4 views (last 30 days)
Show older comments
I have a classification code for LSTM in Matlab and I want to draw the curve of MSE for testing data and there is an error appear when I implement the code of MSE=mean(y_test-y_pred)^2.
How can I draw this curve please?
0 Comments
Answers (1)
Manish
on 24 Dec 2024
Hi Ruaa,
I understand that you would like to plot the Mean Squared Error (MSE) curve for the test data. I've used a random sequence dataset and implemented an LSTM model for demonstration purposes.
Refer to the sample code below for better understanding.
numObservations = 100;
sequenceLength = 10;
numFeatures = 5;
numClasses = 3;
%random sequences for training
XTrain = arrayfun(@(x) randn(numFeatures, sequenceLength), 1:numObservations, 'UniformOutput', false);
YTrain = categorical(randi(numClasses, numObservations, 1));
%random sequences for testing
XTest = arrayfun(@(x) randn(numFeatures, sequenceLength), 1:numObservations, 'UniformOutput', false);
YTest = categorical(randi(numClasses, numObservations, 1));
% LSTM network
layers = [
sequenceInputLayer(numFeatures)
lstmLayer(50, 'OutputMode', 'last')
fullyConnectedLayer(numClasses)
softmaxLayer
classificationLayer];
% Training options
maxEpochs = 5;
options = trainingOptions('adam', ...
'MaxEpochs', maxEpochs, ...
'MiniBatchSize', 16, ...
'SequenceLength', 'longest', ...
'Shuffle', 'every-epoch', ...
'Verbose', 0);
% Initialize MSE storage
msePerEpoch = zeros(maxEpochs, 1);
% Train and calculate MSE per epoch
for epoch = 1:maxEpochs
net = trainNetwork(XTrain, YTrain, layers, options);
YPred = classify(net, XTest, 'SequenceLength', 'longest');
% Convert categorical predictions and true labels to numeric
y_pred = double(YPred);
y_test = double(YTest);
% Calculate MSE for this epoch
msePerEpoch(epoch) = mean((y_test - y_pred).^2);
end
% Plot MSE against epochs
figure;
plot(1:maxEpochs, msePerEpoch, '-o');
title('MSE Over Epochs');
xlabel('Epoch');
ylabel('MSE');
grid on;
Refer the below documentation link for better understanding:
Hope it helps!
0 Comments
See Also
Categories
Find more on Deep Learning Toolbox in Help Center and File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!