how to make a knn classifer using minkowski distance function

3 visualizaciones (últimos 30 días)
Apurva Jariwala
Apurva Jariwala el 17 de Mzo. de 2019
Comentada: Apurva Jariwala el 19 de Mzo. de 2019
Need to make a knn classifer without using fitcknn for K = 3, 5, 7, that uses minkowski distance for the order of 1, 2 and 5
  2 comentarios
Walter Roberson
Walter Roberson el 17 de Mzo. de 2019
Do you mean that you have been given an assignment to write knn classification code yourself?
If so then it would defeat the purpose if we were to give you knn classification code.
Apurva Jariwala
Apurva Jariwala el 19 de Mzo. de 2019
I am trying to make a knn classifier and train and test it using the Iris dataset. The objective is to find accuracy and the confusion matrix. Please read the code below and let me know what changes can I make
IrisD = readtable('irisdata.csv');
classes = categorical(IrisD{:,5});
Icats = categories(classes);
setosa = IrisD(strcmp(IrisD{:,5},Icats(1)),:);
Ttest1 = setosa(1:40,:);
Ttrain1 = setosa(41:50,:);
versicolor = IrisD(strcmp(IrisD{:,5},Icats(2)),:);
Ttest2 = versicolor(1:40,:);
Ttrain2 = versicolor(41:50,:);
virginica = IrisD(strcmp(IrisD{:,5},Icats(3)),:);
Ttest3 = virginica(1:40,:);
Ttrain3 = virginica(41:50,:);
Ttest = [Ttest1; Ttest2; Ttest3];
Ttrain = [Ttrain1; Ttrain2; Ttrain3];
testlabel = Ttest(:,5);
trainlabel = Ttrain(:,5);
C = unique(trainlabel);
testf = Ttest(:,1:4);
trainf = Ttrain(:,1:4);
K = 3;
r = 2;
Lpred = [];
for i = 1:size(testf,1)
Ftest = testf(i,:);
Ns = size(trainf, 1);
dmat = abs(trainf-repmat(Ftest, Ns, 1));
dlist = nthroot(sum(dmat.^r, 2), r);
[dsort, isort] = sort(dlist, 'ascend');
Lknn = trainlabel(isort(1:K));
Ncl = [];
for iC = 1:length(C)
cl = C(iC);
ncl = length(find(Lknn==cl));
Ncl = [Ncl; ncl, cl];
end
[vmax, imax] = max(Ncl(:,1));
Cpred = Ncl(imax, 2);
Lpred = [Lpred; Cpred];
end

Iniciar sesión para comentar.

Respuestas (0)

Productos

Community Treasure Hunt

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

Start Hunting!

Translated by