Matlab error when evaluating a neural network

2 次查看(过去 30 天)
Hellow I am having an error when I am trying to evaluate a neural network. The code is as follows:
% Load the sample data
load fisheriris
% Extract the first two features as the predictors and the third feature as the response
X = meas(:,1:2);
y = meas(:,3);
% Split the data into training and test sets
rng(1); % For reproducibility
cv = cvpartition(y,'Holdout',0.3);
XTrain = X(training(cv),:);
YTrain = y(training(cv));
XTest = X(test(cv),:);
YTest = y(test(cv));
% Create a decision tree using entropy as the splitting criterion
tree = fitctree(XTrain,YTrain,'SplitCriterion','gdi');
% Evaluate the decision tree on the test set
YPred = predict(tree,XTest);
treeAccuracy = mean(YPred == YTest);
fprintf('Decision tree accuracy: %.2f%%\n',treeAccuracy*100)
% Create a feedforward neural network
net = patternnet(10);
% Train the neural network
net = train(net,XTrain',YTrain');
% Evaluate the neural network on the test set
YPred = net(XTest')';
YPred = tree.ClassNames(YPred);
nnAccuracy = mean(YPred == YTest);
fprintf('Neural network accuracy: %.2f%%\n',nnAccuracy*100)
Error:
Array indices must be positive integers or logical values.
Error in classreg.learning.internal.DisallowVectorOps/subsref (line 22)
[varargout{1:nargout}] = builtin('subsref',this,s);
Error in TreeVSAnn (line 33)
YPred = tree.ClassNames(YPred);
Any help to fix this would be greatly appreciated.
  1 个评论
Vinayak
Vinayak 2023-1-2
Hi Killian,
I am able to execute this code snippet error-free.
Could you please re-check and confirm.
Thanks.

请先登录,再进行评论。

回答(1 个)

KSSV
KSSV 2023-1-2
These lines:
YPred = net(XTest')';
YPred = tree.ClassNames(YPred);
nnAccuracy = mean(YPred == YTest);
fprintf('Neural network accuracy: %.2f%%\n',nnAccuracy*100)
Should be:
YPred = net(XTest')';
nnAccuracy = mean(YPred == YTest);
fprintf('Neural network accuracy: %.2f%%\n',nnAccuracy*100)
You need not to index tree.ClassNames. You got your prediction already from the line:
YPred = net(XTest')';
But this is not the way to caclulate Accuracy.

类别

Help CenterFile Exchange 中查找有关 Sequence and Numeric Feature Data Workflows 的更多信息

Community Treasure Hunt

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

Start Hunting!

Translated by