资源描述:
《bayes程序MATLAB》由会员上传分享,免费在线阅读,更多相关内容在教育资源-天天文库。
1、%为了提高实验样本测试的精度,故采用多次模拟求平均值的方法N=input('实验模拟次数N(N最好为奇数)=');Result(1:3,1:3)=0;%判别矩阵的初始化fork=1:N%控制程序模拟次数N%生成二维正态分布的样本2XN维的矩阵X1=mvnrnd([12],[40;06],300)';%2XNX2=mvnrnd([53],[50;01],200)';X3=mvnrnd([47],[20;09],500)';%样本程序%---------------------------------------------------%
2、%测试样本X10=mvnrnd([12],[40;06],100)';%2XNX20=mvnrnd([53],[50;01],100)';X30=mvnrnd([47],[20;09],100)';%先验概率P(1)=length(X1)/(length(X1)+length(X2)+length(X3));P(2)=length(X2)/(length(X1)+length(X2)+length(X3));P(3)=length(X3)/(length(X1)+length(X2)+length(X3));%计算相关量cov(X):
3、协方差矩阵Ave:均值%--------------------------------------------------------%W1=-1/2*inv(cov(X1'));W2=-1/2*inv(cov(X2'));W3=-1/2*inv(cov(X3'));%Ave1=(sum(X1')/length(X1))';Ave2=(sum(X2')/length(X2))';Ave3=(sum(X3')/length(X3))';%计算平均值(2维列向量)w1=inv(cov(X1'))*Ave1;w2=inv(cov(X2')
4、)*Ave2;w3=inv(cov(X3'))*Ave3;%2w10=-1/2*Ave1'*inv(cov(X1'))*Ave1-1/2*log(det(cov(X1')))+log(P(1));w20=-1/2*Ave2'*inv(cov(X2'))*Ave2-1/2*log(det(cov(X2')))+log(P(2));w30=-1/2*Ave3'*inv(cov(X3'))*Ave3-1/2*log(det(cov(X3')))+log(P(3));%-------------------------------------
5、----------------------%fori=1:3forj=1:100ifi==1g1=X10(:,j)'*W1*X10(:,j)+w1'*X10(:,j)+w10;g2=X10(:,j)'*W2*X10(:,j)+w2'*X10(:,j)+w20;g3=X10(:,j)'*W3*X10(:,j)+w3'*X10(:,j)+w30;ifg1>=g2&g1>=g3Result(1,1)=Result(1,1)+1;elseifg2>=g1&g2>=g3Result(1,2)=Result(1,2)+1;%记录误判情况else
6、Result(1,3)=Result(1,3)+1;%记录误判情况endelseifi==2g1=X20(:,j)'*W1*X20(:,j)+w1'*X20(:,j)+w10;g2=X20(:,j)'*W2*X20(:,j)+w2'*X20(:,j)+w20;g3=X20(:,j)'*W3*X20(:,j)+w3'*X20(:,j)+w30;ifg2>=g1&g2>=g3Result(2,2)=Result(2,2)+1;elseifg1>=g2&g1>=g3Result(2,1)=Result(2,1)+1;elseResult(2
7、,3)=Result(2,3)+1;endelseg1=X30(:,j)'*W1*X30(:,j)+w1'*X30(:,j)+w10;g2=X30(:,j)'*W2*X30(:,j)+w2'*X30(:,j)+w20;g3=X30(:,j)'*W3*X30(:,j)+w3'*X30(:,j)+w30;ifg3>=g1&g3>=g2Result(3,3)=Result(3,3)+1;elseifg2>=g1&g2>=g3Result(3,2)=Result(3,2)+1;elseResult(3,1)=Result(3,1)+1;end
8、endendendend%画出各样本的分布情况subplot(2,1,1)plot(X1(1,:),X1(2,:),'r.','LineWidth',2),holdonplot(X2(1,:),X2(2,:),'go',