Help on KNN prediction function.
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
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.
![](https://www.mathworks.com/matlabcentral/answers/uploaded_files/1170238/image.png)
0 Kommentare
Antworten (1)
Shubh Dhyani
am 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:
0 Kommentare
Siehe auch
Kategorien
Mehr zu Statistics and Machine Learning Toolbox finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!