赞
踩
从网站下在鸢尾花数据集http://download.tensorflow.org/data/iris_training.csv并导入matlab中,这里的鸢尾花数据集仅有120条,每种各40条。
将得到的csv文件根据亚种标号进行排序,操作过程及结果如下图:
在matlab中将csv文件信息以矩阵形式导入,命名为iristraining,并绘制四维图像,观察数据特征。
Sepal_Length = iristraining(:,1); % 花萼长度
Sepal_Width = iristraining(:,2); % 花萼宽度
Petal_Length = iristraining(:,3); % 花瓣长度
Petal_Width = iristraining(:,4); % 花瓣宽度
scatter3(Sepal_Length,Sepal_Width,Petal_Length,40,Petal_Width,'filled') % draw the scatter plot
ax = gca;
ax.XDir = 'reverse';
view(-31,14)
xlabel('花萼长度')
ylabel('花萼宽度')
zlabel('花瓣长度')
%
cb = colorbar; % create and label the colorbar
cb.Label.String = '花瓣宽度';
根据图中结果,本次使用先验的结论认为每个的鸢尾花亚种的四个特征服从四维正态分布。
使用matlab进行每个亚种四条特征的协方差矩阵及均值计算
x1 = iristraining(1:40,1:4);
x2 = iristraining(41:80,1:4);
x3 = iristraining(81:120,1:4);
miu1 = mean(x1); %caculate miu and cov
miu2 = mean(x2);
miu3 = mean(x3);
cov1 = cov(x1);
cov2 = cov(x2);
cov3 = cov(x3);
在确定均值与协方差矩阵的基础上,使用mvnpdf函数预测新的坐标处各个亚种分布的概率密度,mvnpdf函数用于计算确定的高斯分布下某处的概率,具体使用方法如图
使用两种先验概率来进行贝叶斯判别,第一种将120条数据重新导入进行判别,先验概率为1:1:1,关键代码如下:
%test1 correct1 = 0; for x = 1:120 data = iristraining(x,1:4); mark = iristraining(x,5); if mark == Bayesian_classifier0(data,miu1,cov1,miu2,cov2,miu3,cov3) correct1 = correct1 + 1; end end accuracy1 = correct1/120 %Bayesian_classifier0 %此处将120条数据重新导入进行贝叶斯判别,先验概率之比为1,仅需判断似然比大小即可 function [category] = Bayesian_classifier0(data,miu1,cov1,miu2,cov2,miu3,cov3) if mvnpdf(data,miu1,cov1) <= mvnpdf(data,miu2,cov2) category = 1; max = mvnpdf(data,miu2,cov2); else category = 0; max = mvnpdf(data,miu1,cov1); end if max <= mvnpdf(data,miu3,cov3) category = 2; end end
第二种以随机数的方式以1:2:3的比例在各个亚种中共取120条数据,在此基础上进行贝叶斯判别,关键代码如下:
%test2 correct2 = 0; for x = 1:120 i = rand; if i <= 1/6 m = floor(i * 6 * 40); elseif i >= 1/2 m = floor(80 + i * 1/2 * 40); else m = floor(40 + i * 1/3 * 40); end if m ==0 m = 1; end data = iristraining(m,1:4); mark = iristraining(m,5); if mark == Bayesian_classifier1(data,miu1,cov1,miu2,cov2,miu3,cov3) correct2 = correct2 + 1; end end accuracy2 = correct2/120 %Bayesian_classifier1 %此处将数据按1:2:3导入进行贝叶斯判别,先验概率之比发生改变,判别阈值发生改变 function [category] = Bayesian_classifier1(data,miu1,cov1,miu2,cov2,miu3,cov3) if mvnpdf(data,miu1,cov1) <= 2*mvnpdf(data,miu2,cov2) category = 1; max = 2*mvnpdf(data,miu2,cov2); else category = 0; max = mvnpdf(data,miu1,cov1); end if max <= 3*mvnpdf(data,miu3,cov3) category = 2; end end
得到结果如下,可以看出,使用该方式进行的贝叶斯判别可以有效的对鸢尾花数据进行较为合理的分类:
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。