load data1; right=0; x=zeros(2,1); %假设它们都符合二元高斯分布 u1=zeros(2,1);%值为1的类的均值 v1=zeros(2,2);%值为1的类的方差 u2=zeros(2,1);%值为2的类的均值 v2=zeros(2,2);%值为2的类的方差 sum1=0; sum2=0; pior1=0; posterior1=0; likehood1=0; pior2=0; posterior2=0; likehood2=0; for i=1:1:2500%求先验 if(data(3,i)==1) sum1=sum1+1; else sum2=sum2+1; end end pior1=sum1/(sum1+sum2); pior2=sum2/(sum1+sum2); for m=2501:1:3000 %测试循环 for i=1:1:2500%求均值 if(data(3,i)==1) u1(1,1)=u1(1,1)+data(1,i); u1(2,1)=u1(2,1)+data(2,i); else u2(1,1)=u2(1,1)+data(1,i); u2(2,1)=u2(2,1)+data(2,i); end end u1=u1/2500; u2=u2/2500; for i=1:1:2500%求方差 if(data(3,i)==1) x(1,1)=data(1,i); x(2,1)=data(2,i); v1=v1+(x-u1)*(x-u1)'; else x(1,1)=data(1,i); x(2,1)=data(2,i); v2=v2+(x-u2)*(x-u2)'; end end v1=v1/2500; v2=v2/2500; %求似然 x(1,1)=data(1,m); x(2,1)=data(2,m); likehood1=1/(det(v1)^0.5)*exp(-0.5*(x-u1)'*(v1^-1)*(x-u1));%相同的项不乘了 likehood2=1/(det(v2)^0.5)*exp(-0.5*(x-u2)'*(v2^-1)*(x-u2)); 求后验 posterior1=pior1*likehood1; posterior2=pior2*likehood2; if(((posterior1>posterior2)&&(data(3,m)==1))||((posterior1<posterior2)&&(data(3,m)==-1))) right=right+1; end end
数据下载点击打开链接