How to convert knnclassify to fitcknn

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.

Risposte (1)

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!

Richiesto:

il 17 Lug 2020

Risposto:

il 16 Mag 2025

Community Treasure Hunt

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

Start Hunting!

Translated by