How to convert knnclassify to fitcknn

5 visualizaciones (últimos 30 días)
akbar muslim
akbar muslim el 17 de Jul. de 2020
Respondida: Sameer el 16 de Mayo de 2025
i have script from youtube but still using knnclassify
please help me how to change it to fitcknn, because when directly change knnclassify to fitcknn it always error.

Respuestas (1)

Sameer
Sameer el 16 de Mayo de 2025
Hi
Here's how you can convert your code to use "fitcknn":
1. Train the KNN model using "fitcknn"
You only need to train the model once (outside the loop):
x = xlsread('DataTraining.xlsx');
training = x(:,1:4); % Features (assuming columns 1-4 are features)
group = x(:,5); % Labels (assuming column 5 is the class label)
% Train KNN model
Mdl = fitcknn(training, group);
2. Predict using the trained model
Use the "predict" function
for i = 1:20
y = xlsread('DataTesting.xlsx');
sample = y;
test = sample(:,1:4); % Features to test (columns 1-4)
% Predict using the trained model
result = predict(Mdl, test);
end
3. Save results
name = 'Result_KNN.xlsx';
result = [sample(:,1) sample(:,2) sample(:,3) sample(:,4) sample(:,5) result];
xlswrite(name, result);
Hope this helps!

Etiquetas

Community Treasure Hunt

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

Start Hunting!

Translated by