資源描述:
《bayes程序MATLAB》由會(huì)員上傳分享,免費(fèi)在線閱讀,更多相關(guān)內(nèi)容在教育資源-天天文庫(kù)。
1、%為了提高實(shí)驗(yàn)樣本測(cè)試的精度,故采用多次模擬求平均值的方法N=input('實(shí)驗(yàn)?zāi)M次數(shù)N(N最好為奇數(shù))=');Result(1:3,1:3)=0;%判別矩陣的初始化fork=1:N%控制程序模擬次數(shù)N%生成二維正態(tài)分布的樣本2XN維的矩陣X1=mvnrnd([12],[40;06],300)';%2XNX2=mvnrnd([53],[50;01],200)';X3=mvnrnd([47],[20;09],500)';%樣本程序%---------------------------------------------------%
2、%測(cè)試樣本X10=mvnrnd([12],[40;06],100)';%2XNX20=mvnrnd([53],[50;01],100)';X30=mvnrnd([47],[20;09],100)';%先驗(yàn)概率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));%計(jì)算相關(guān)量cov(X):
3、協(xié)方差矩陣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))';%計(jì)算平均值(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',