Impact-Site-Verification: dbe48ff9-4514-40fe-8cc0-70131430799e

Search This Blog

K-Nearest Neighbors visualization | MATLAB

Problem Statement:
Provide an example of a training set such that the same unknown sample can be classified in different ways if k is set to 1 or 3.


%Code:


clc
clear all
close all
warning off
output=[];
x=[1 3 0 -1 0];
y=[0 0 0 0 2];
c=["CA","CA","CB","CB","CB"];
m=c;
k=input('Enter the k value');
es=input('For how many times you want to run the code:');
xg=[];
yg=[];
for erts=1:es
a=input('Enter the first parameter value of the test:');
b=input('Enter the second parameter value of the test:');
xg=[xg a];
yg=[yg b];
distance=[];
for i=1:length(x)
    e=sqrt((x(i)-a)^2+(y(i)-b)^2);
    distance=[distance e];
end
distance
temp=0;
gemp=0;
for i=1:length(distance)
    for j=1:(length(distance)-i)
        if(distance(j)>distance(j+1))
            temp=distance(j);
            distance(j)=distance(j+1);
            distance(j+1)=temp;
            gemp=c(j);
            c(j)=c(j+1);
            c(j+1)=gemp;
        end
    end
end
classy=[];
for i=1:k
    classy=[classy c(i)];
end
output=[output mode(classy)];
c=m;
end
sty=[];
for i=1:length(c)
if (c(i)=="CA")
    sty=[sty "b+"];
else
    sty=[sty "r*"];
end
end
for i=1:length(c)
    plot(x(i),y(i),sty(i),'linewidth',5);
    hold on;
end
for i=1:length(xg)
    plot(xg(i),yg(i),'ko','linewidth',5);
end


No comments

Popular Posts

Followers