Clear Filters
Clear Filters

Help on KNN prediction function.

1 view (last 30 days)
Jack
Jack on 26 Oct 2022
Answered: Shubh Dhyani on 2 Nov 2022
Im a little unsure on how to complete my prediction function that im writing for my KNN classifier, i have some testing examples that i need to loop over and for each example i need to generate a prediction. What i show below is what is have so far.

Answers (1)

Shubh Dhyani
Shubh Dhyani on 2 Nov 2022
I understand that you are trying to construct a prediction function based on a KNN Classifier and that you would like to loop over the examples and generate the predictions for them.
The following example will illustrate how to achieve the above :
function predictions = predictClass(mdlObj,testSamples, Y)
predictions = {};
for i = 1:length(testSamples)
ind = knnsearch(mdlObj, testSamples(i,:))
% using Y to get the class name name of the closest X data item
predictions(i) = Y(ind);
end
end
Please note that you will have to pass in “Y”(the labels for training set) as well because the “knnsearch” function outputs the index of the closest “X” (training set) data item. So, you will need the corresponding labels to get the class. You can refer to the following documentation for more information on the “knnsearch” function:
Alternatively, you can use the “fitcknn” function to train the model and the “predict” function to predict the classes of the test data, without the need to construct a separate prediction function. Please refer to the following documentation links for more information on the “fitcknn” and the “predict” functions:

Categories

Find more on Statistics and Machine Learning Toolbox 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!