Invalid training data. Predictors and responses must have the same number of observations.
18 views (last 30 days)
Show older comments
I wan to train a LSTM.
But I get Error:
Error using trainNetwork (line 191)
Invalid training data. Predictors and responses must have the same number of observations.
layers = [ ...
sequenceInputLayer(6)
lstmLayer(120,'OutputMode','last')
fullyConnectedLayer(2)
softmaxLayer
classificationLayer];
options = trainingOptions('adam', ...
'MaxEpochs',20, ...
'MiniBatchSize',32, ...
'GradientThreshold',1, ...
'InitialLearnRate',0.005, ...
'Shuffle','every-epoch', ...
'Verbose',0, ...
'Plots','training-progress');
net = trainNetwork(XTrain, YTrain, layers, options);



0 Comments
Accepted Answer
Matt J
on 28 Aug 2025 at 19:41
Edited: Matt J
on 28 Aug 2025 at 19:55
Your XTrain shouldn't be a 100x6 cell. It should be a 100x1 cell where each XTrain{i} is a matrix with 6 rows. Example,
layers = [ ...
sequenceInputLayer(6)
lstmLayer(120,'OutputMode','last')
fullyConnectedLayer(2)
softmaxLayer
classificationLayer];
for i=1:100
XTrain{i,1} = rand(6,randi(20));
end
YTrain = categorical(randi([0,1],100,1));
whos YTrain
XTrain,
options = trainingOptions('adam', ...
'MaxEpochs',20, ...
'MiniBatchSize',32, ...
'GradientThreshold',1, ...
'InitialLearnRate',0.005, ...
'Shuffle','every-epoch', ...
'Verbose',1, ...
'Plots','none');
net = trainNetwork(XTrain, YTrain, layers, options)
3 Comments
Matt J
on 28 Aug 2025 at 21:05
Edited: Matt J
on 28 Aug 2025 at 21:34
The error is complaining that you have not removed the output layer (classificationLayer) from your layers array. Output layers do not belong in the network when training with trainnet, because the loss function is separately specified to trainnet using the lossFcn input parameter.

More Answers (0)
See Also
Categories
Find more on Image Data Workflows 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!