資源描述:
《西電,模式識別,k近鄰.doc》由會員上傳分享,免費在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫。
1、模式識別大作業(yè)k-近鄰算法學(xué)院:電子工程學(xué)院班級:學(xué)號:姓名:作業(yè)要求一、作業(yè)內(nèi)容編程實現(xiàn)最近鄰算法和k-近鄰算法,在Iris(3類,每類50個樣本,4維特征),wine數(shù)據(jù)集(3類,13維,共178個樣本)上驗證其性能。二、算法描述K近鄰就是在N個樣本中,找出x的K個近鄰。設(shè)這N個樣本中,來自Wc類的樣本有Nc個,若K1,K2,…Kc分別是K個近鄰中屬于W1,W2,…,Wc類的樣本數(shù),則我們可以定義判別函數(shù)為:決策規(guī)則為:若則決策x∈。這就是K近鄰的基本規(guī)則。三、代碼實現(xiàn)Irisfunctionk_jl=k_jl();temp=importdata('iris.txt');sum=ze
2、ros(1,10);fori=1:10data1=temp(1:50,1:4);randnum=randperm(size(data1,1));train1=data1(randnum(1:25),:);test1=data1(randnum(26:50),:);data2=temp(51:100,1:4);randnum=randperm(size(data2,1));train2=data2(randnum(1:25),:);test2=data2(randnum(26:50),:);data3=temp(101:150,1:4);randnum=randperm(size(data
3、3,1));train3=data3(randnum(1:25),:);test3=data3(randnum(26:50),:);train_sample=cat(1,train1,train2,train3);test_sample=cat(1,test1,test2,test3);k=11;kjl=zeros(1,75);forx=1:75fory=1:75result=sqrt((test_sample(x,1)-train_sample(y,1))^2+(test_sample(x,2)-train_sample(y,2))^2+(test_sample(x,3)-train_
4、sample(y,3))^2+(test_sample(x,4)-train_sample(y,4))^2);kjl(1,y)=result;end[B,Ind]=sort(kjl);m1=0;m2=0;m3=0;forn=1:kifInd(1,n)<=20m1=m1+1;elseifInd(1,n)>20&&Ind(1,n)<=40m2=m2+1;elsem3=m3+1;endendif(m1>=m2&&m1>=m3)m=1;elseifm2>=m1&&m2>=m3m=2;elsem=3;endifx<=25disp(sprintf('第%d組數(shù)據(jù)分類后為第%d類',x+25,m));
5、elseifx>25&&x<=50disp(sprintf('第%d組數(shù)據(jù)分類后為第%d類',x+50,m));elseifx>50&&x<=75disp(sprintf('第%d組數(shù)據(jù)分類后為第%d類',x+75,m));endif(x<=25&&m==1)
6、
7、(x>25&&x<=50&&m==2)
8、
9、(x>50&&x<=75&&m==3)sum(1,i)=sum(1,i)+1;endendsum(1,i)=sum(1,i)/75;disp(sprintf('分類正確率為%4.2f',sum(1,i)))endadd=0;forj=1:10disp(sprintf('第%d次分類正確率
10、為%4.2f',j,sum(1,j)))add=sum(1,j)+add;enddisp(sprintf('平均分類正確率為%4.2f',add/10))Winefunctionzx=zx();temp=importdata('wine.txt');sum=zeros(1,10);fori=1:10data_1=temp(1:58,1:4);randnum=randperm(size(data_1,1));train_1=data_1(randnum(1:29),:);test_1=data_1(randnum(30:58),:);data_2=temp(59:116,1:4);rand
11、num=randperm(size(data_2,1));train_2=data_2(randnum(1:29),:);test_2=data_2(randnum(30:58),:);data_3=temp(117:174,1:4);randnum=randperm(size(data_3,1));train_3=data_3(randnum(1:29),:);test_3=data_3(randnum(30:58),:);tra