I want to use fitcknn but to iterate for multiple k variables ( k = 1:15) and then store the accuracy values in a matrix. What is an easy way to do this? Thanks!

2 ビュー (過去 30 日間)
clear all
data = readtable('some_data.txt');
%%%% Normalize Data %%%%
x = (data.x - mean(data.x))/std(data.x);
data.x = x;
y = (data.y - mean(data.y))/std(data.y);
data.y = y;
k = 15
%%%% Build Classifier %%%%
class_model = fitcknn(data,'c~x+y','NumNeighbors',k,'Distance','euclidean');
%%%% Partition Training/Testing sets %%%%
cv = cvpartition(class_model.NumObservations,'HoldOut',0.2);
cross_val_model = crossval(class_model,'cvpartition',cv);
%%%% Create Predictions %%%%
Predict = predict(cross_val_model.Trained{1},data(test(cv),1:end-1));
%%%% Draw Confusion Matrix %%%%
Result = confusionmat(cross_val_model.Y(test(cv)),Predict);
%%% Accuracy %%%%
accuracy = ((Result(2,2)+Result(1,1))/((Result(2,2)+Result(1,1)+Result(1,2)+Result(2,1))))
  1 件のコメント
Nicholas Boselli
Nicholas Boselli 2021 年 9 月 13 日
I think I just did it but as a beginner my code is still sloppy so if you have a "clean" way of doing this please share! Thanks all!

サインインしてコメントする。

回答 (1 件)

Walter Roberson
Walter Roberson 2021 年 9 月 13 日
clear all
data = readtable('some_data.txt');
%%%% Normalize Data %%%%
x = (data.x - mean(data.x))/std(data.x);
data.x = x;
y = (data.y - mean(data.y))/std(data.y);
data.y = y;
Kvals = 1:15;
%%%% Build Classifier %%%%
class_models = arrayfun(@(k) fitcknn(data,'c~x+y','NumNeighbors',k,'Distance','euclidean'), Kvals, 'uniform', 0);
%%%% Partition Training/Testing sets %%%%
cvs = cellfun(@(CM) cvpartition(CM.NumObservations,'HoldOut',0.2), class_models, 'uniform', 0);
cross_val_models = cellfun(@(CM,CV) crossval(CM,'cvpartition',CV), class_models, cvs, 'uniform', 0);
%%%% Create Predictions %%%%
Predicts = cellfun(@(CVM, CV) predict(CVM.Trained{1},data(test(CV),1:end-1)), cross_val_models, cvs, 'uniform', 0);
%%%% Draw Confusion Matrix %%%%
Results = cellfun(@(CVM, CV, P) confusionmat(CVM.Y(test(CV)),P), cross_val_models, cvs, Predicts, 'uniform', 0);
%%% Accuracy %%%%
accuracys = cellfun(@(Result) ((Result(2,2)+Result(1,1))/((Result(2,2)+Result(1,1)+Result(1,2)+Result(2,1)))), Results);
plot(Kvals, accuracys)

Community Treasure Hunt

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

Start Hunting!

Translated by