Help on KNN prediction function.

1 次查看(过去 30 天)
Jack
Jack 2022-10-26
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.

回答(1 个)

Shubh Dhyani
Shubh Dhyani 2022-11-2
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:

Community Treasure Hunt

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

Start Hunting!

Translated by