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!
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 vues (au cours des 30 derniers jours)
Afficher commentaires plus anciens
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))))
Réponses (1)
Walter Roberson
le 13 Sep 2021
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)
0 commentaires
Voir également
Catégories
En savoir plus sur Dimensionality Reduction and Feature Extraction dans Help Center et File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!