📄 ex2.m
字号:
%实验一:贝叶斯分类实验
clear
xx1(:,1) = normrnd(10,4,20,1);%鲈鱼长度
xx1(:,2) = normrnd(12,4,20,1);%鲈鱼亮度
yy1(:,1)=normrnd(12,3,20,1);%鲑鱼长度
yy1(:,2)=normrnd(14,3,20,1);%鲑鱼亮度
%第2题
plot(xx1(:,1),xx1(:,2),'ro');
hold on;
plot(yy1(:,1),yy1(:,2),'gd');
p1=0.4;p2=0.6;
u1=mean(xx1)';
u2=mean(yy1)';
sigma1=cov(xx1);
sigma2=cov(yy1);
%两类协方差相同的情况
if sigma1==sigma2
x0=(u1+u2)/2-log(p1/p2)/((u1-u2)'*inv(sigma1)*(u1-u2))*(u1-u2);
w=inv(sigma1)*(u1-u2);
X=2:0.5:20;
Y=x0(2,1)-w(1,1)*(X-x0(1,1))/w(2,1);
plot(X,Y);
%两类协方差不相同的情况
else
W1=-inv(sigma1)/2;
W2=-inv(sigma2)/2;
W=W1-W2;
w1=inv(sigma1)*u1;
w2=inv(sigma2)*u2;
w=w1-w2;
w10=-u1'*inv(sigma1)*u1/2-log(det(sigma1))/2+log(p1);
w20=-u2'*inv(sigma2)*u2/2-log(det(sigma2))/2+log(p2);
w0=w10-w20;
str=sprintf('%f*x*x+%f*x*y+%f*y*y+%f*x+%f*y+%f',W(1,1),W(1,2)+W(2,1),W(2,2),w(1,1),w(2,1),w0);
ezplot(str,[u1(1,1)-10,u2(1,1)+10,u1(2,1)-10,u2(2,1)+10]);
xlabel('长度');
ylabel('亮度');
legend('鲈鱼','鲑鱼','分类边界');
hold off;
end
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -