資源描述:
《貝葉斯分類器MATLAB經(jīng)典程序》由會員上傳分享,免費在線閱讀,更多相關內容在教育資源-天天文庫。
1、functionBayes2%為了提高實驗樣本測試的精度,故采用多次模擬求平均值的方法N=input('實驗模擬次數(shù)N(N最好為奇數(shù))=');Result(1:3,1:3)=0;?????%判別矩陣的初始化fork=1:N????????????%控制程序模擬次數(shù)N???%生成二維正態(tài)分布的樣本2XN維的矩陣????X1=mvnrnd([12],[40;06],300)';??%2XN???X2=mvnrnd([53],[50;01],200)';???X3=mvnrnd([47],[20;09],500)';??%樣本程序???%---
2、------------------------------------------------%???%測試樣本???X10=mvnrnd([12],[40;06],100)';??%2XN???X20=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)+leng
3、th(X3));???P(3)=length(X3)/(length(X1)+length(X2)+length(X3));???%計算相關量?cov(X):協(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')/lengt
4、h(X2))';???Ave3=(sum(X3')/length(X3))';%計算平均值(2維列向量)???w1=inv(cov(X1'))*Ave1;w2=inv(cov(X2'))*Ave2;w3=inv(cov(X3'))*Ave3;%2???w10=-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
5、/2*Ave3'*inv(cov(X3'))*Ave3-1/2*log(det(cov(X3')))+log(P(3));???%-----------------------------------------------------------%???fori=1:3????????????????????????????????????????????forj=1:100??????????????????????????????????????????ifi==1???????????????g1=X10(:,j)'*W1*X10
6、(:,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>=g3????????????????????????Result(1,1)=Result(1,1)+1;???????????????elseifg2>=g1&g2>=g3???????????????????
7、Result(1,2)=Result(1,2)+1;%記錄誤判情況???????????????else???????????????????Result(1,3)=Result(1,3)+1;%記錄誤判情況???????????????end???????????elseifi==2???????????????g1=X20(:,j)'*W1*X20(:,j)+w1'*X20(:,j)+w10;???????????????g2=X20(:,j)'*W2*X20(:,j)+w2'*X20(:,j)+w20;???????????????
8、g3=X20(:,j)'*W3*X20(:,j)+w3'*X20(:,j)+w30;???????????????ifg2>=g1&g2>=g3???????????????????Resul