필터 지우기
필터 지우기

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)

카테고리

Help CenterFile Exchange에서 Dimensionality Reduction and Feature Extraction에 대해 자세히 알아보기

Community Treasure Hunt

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

Start Hunting!

Translated by