Error in classifying using knn classify

3 views (last 30 days)
I have created a input featurepool of 360 rows(90 samples each of 4 classes) and 22 columns(features). Corresponding classes is 360 row-column vector. I have trained using knnclassifier described as in the link training KNNusing euclidean distance and k = 5. But I when I am trying to classify it displays an error
Error using knnclassify (line 96) The length of GROUP must equal the number of rows in TRAINING.
Error in testknn prediction = knnclassify(testData, knnstruct, testLabel);
I have used 180 rows (50%) for training and other (50%) for testing. how to rectify this ?
Here is my code snippet.
load FeaturePool_3deg
FV = [FeaturePool_3deg_left; FeaturePool_3deg_right; FeaturePool_3deg_up; FeaturePool_3deg_down];
numofsubpools = 4;
sizeofpool = 90;
for i = 1 : numofsubpools
classes(sizeofpool*(i-1)+1:sizeofpool*i) = i;
end
classes = classes';
data = zscore(FV); % normalizing the data
[~,~,labels] = unique(classes);
numInst = size(data,1);
numLabels = max(labels);
idx = randperm(numInst); % select random 50%
numTrain = round(numInst/2); % number of train samples
numTest = numInst - numTrain; % number of test samples
trainData = data(idx(1:numTrain),:); % Separating Train Data
testData = data(idx(numTrain+1:end),:); % Seperating Test Data
trainLabel = labels(idx(1:numTrain)); % Seperating Train Labels
testLabel = labels(idx(numTrain+1:end)); % Seperating Test Labels
% Construct KNN , k = 5, and using euclidean distance
knnstruct = fitcknn(trainData,trainLabel,'NumNeighbors',5,'Distance','euclidean');
prediction = knnclassify(testData, knnstruct, testLabel);

Accepted Answer

Walter Roberson
Walter Roberson on 13 Jun 2016
You use the more modern fitcknn, which is good, but you then pass the resulting model to the older knnclassify as if the model is training data. To classify your test data these days you should be using predict() on the model returned by fitcknn.

More Answers (0)

Community Treasure Hunt

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

Start Hunting!