Help on KNN prediction function.

조회 수: 6 (최근 30일)
Jack
Jack 2022년 10월 26일
답변: Shubh Dhyani 2022년 11월 2일
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:

카테고리

Help CenterFile Exchange에서 Statistics and Machine Learning Toolbox에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by