필터 지우기
필터 지우기

Error using confusionmat command

조회 수: 8 (최근 30일)
Charlotte
Charlotte 2023년 10월 24일
답변: the cyclist 2023년 10월 24일
Hi! I am trying to do this question:
a). Use fitcknn() with default options to create a k-nearest neighbour classifier for the data. Use the classifier to predict the classes for the test set in sat.tst and compare the predictions to the actual classes. Finally, draw a confusion plot of the test set results.
b). Use patternnet() to create and train a pattern recognition neural network using the training data. Compare the test set confusion plot to part a).
I have managed to ge the code working for part a but when I try to do part b i get this error "Error using confusionmat
G and GHAT need to have same number of rows
Error in exercise3 (line 32)
C_nn = confusionmat(Y_test, Y_pred_nn);"
This is the code i have
trainData = load('sat.trn');
X_train = trainData(:, 1:36);
Y_train = trainData(:, 37);
% Load test data
testData = load('sat.tst');
X_test = testData(:, 1:36);
Y_test = testData(:, 37);
% Train a k-NN classifier
knnModel = fitcknn(X_train, Y_train);
Y_pred = predict(knnModel, X_test);
C = confusionmat(Y_test, Y_pred);
confusionchart(C, unique(Y_test));
%% Exercise 3b
net = patternnet(10); % Adjust the number of output neurons to match the number of classes (7 in your case)
% Train the network
net = train(net, X_train', Y_train');
% Use the trained network to make predictions on the test data
Y_pred_nn = net(X_test');
% Convert the network's output to class labels
[~, Y_pred_nn] = max(Y_pred_nn);
% Calculate the confusion matrix using confusionmat
C_nn = confusionmat(Y_test, Y_pred_nn);
% Plot the confusion matrix
confusionchart(C_nn, unique(Y_test));
does anyone know what the error means and how do i fix it? I can't seem to find it online.
  댓글 수: 1
the cyclist
the cyclist 2023년 10월 24일
Can you upload the data, so that we can run your code? You can use the paper clip icon in the INSERT section of the toolbar.

댓글을 달려면 로그인하십시오.

답변 (1개)

the cyclist
the cyclist 2023년 10월 24일
I'd like to see the data, but in this line
C_nn = confusionmat(Y_test, Y_pred_nn);
isn't Y_test a Nx1 vector (where N is the number of observations in the test set), and Y_pred_nn is just a scalar (the index to the max), because you redefined Y_pred_nn in the line
[~, Y_pred_nn] = max(Y_pred_nn);
I think maybe you re-used a variable to mean something else, in a way you did not intend.

카테고리

Help CenterFile Exchange에서 Get Started with Statistics and Machine Learning Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by