Filter löschen
Filter löschen

Error using confusionmat command

8 Ansichten (letzte 30 Tage)
Charlotte
Charlotte am 24 Okt. 2023
Beantwortet: the cyclist am 24 Okt. 2023
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 Kommentar
the cyclist
the cyclist am 24 Okt. 2023
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.

Melden Sie sich an, um zu kommentieren.

Antworten (1)

the cyclist
the cyclist am 24 Okt. 2023
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.

Community Treasure Hunt

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

Start Hunting!

Translated by