How do I draw the MSE curve for an LSTM classification code in Matlab?

4 ビュー (過去 30 日間)
Ruaa Anooz
Ruaa Anooz 2022 年 9 月 21 日
回答済み: Manish 2024 年 12 月 24 日
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?

回答 (1 件)

Manish
Manish 2024 年 12 月 24 日
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!

カテゴリ

Help Center および File ExchangeDeep Learning Toolbox についてさらに検索

Community Treasure Hunt

Find the treasures in MATLAB Central and discover how the community can help you!

Start Hunting!

Translated by