%书中例题实现朴素贝叶斯
%特征1的取值集合
A1=[1;2;3];
%特征2的取值集合
A2=[4;5;6];%S M L
AValues={A1;A2};
%Y的取值集合
YValue=[-1;1];
%数据集和
T=[ 1,4,-1;
1,5,-1;
1,5,1;
1,4,1;
1,4,-1;
2,4,-1;
2,5,-1;
2,5,1;
2,6,1;
2,6,1;
3,6,1;
3,5,1;
3,5,1;
3,6,1;
3,6,-1];
%训练带Laplace平滑的朴素贝叶斯模型
ltheta = LaplaceNBtrain(T(:, 1:size(T, 2) - 1), T(:, size(T, 2)), AValues, YValue, 1);
%训练朴素贝叶斯模型
theta = NBtrain(T(:, 1:size(T, 2) - 1), T(:, size(T, 2)), AValues, YValue);
%测试两个数据与书中答案相符
ans = NBtest(theta, [2,4;], AValues, YValue)
lans = NBtest(ltheta, [2,4;], AValues, YValue)
function y = NBtest(theta, X, AValues, YValue)
Xindice=ones(size(X, 1), size(X, 2));
%找到特征在取值集合中的下标,将X矩阵转化为下标矩阵
for j=1:1:size(X, 2)
AXi = AValues{j, 1};
for i=1:1:size(X, 1)
for t=1:1:size(AXi, 1)
if(X(i, j) == AXi(t, 1))
Xindice(i, j) = t;
break
end
end
end
end
%矩阵用于记录所有X在不同Yi下的P(X|Y)P(Y)
Ys = zeros(size(X, 1), size(YValue, 1));
PX_Y = theta{1,1};
PY = theta{2,1};
for i=1:1:size(Ys, 1)
x=Xindice(i, :);
for k=1:1:size(Ys, 2)
ans = PY(k, 1);
for j=1:1:size(x, 2)
ans = ans * PX_Y{k, j}(x(1, j), 1);
end
Ys(i, k) = ans;
end
end
Ys
%后验概率最大化
y=zeros(size(Ys, 1), 1);
for i=1:1:size(Ys, 1)
max = -1;
max_indice = 0;
for j=1:1:size(Ys, 2)
if(Ys(i, j) > max)
max = Ys(i, j);
max_indice = j;
end
end
y(i, 1) = YValue(max_indice, 1);
end
end
function theta=NBtrain(X,Y,AValues,YValue)
%计算先验概率
TY = zeros(size(YValue, 1), 1);
for i=1:1:size(Y, 1)
for j=1:1:size(YValue)
if(Y(i, 1) == YValue(j, 1))
Y(i,1);
TY(j, 1) = TY(j, 1) + 1;
break
end
end
end
PY = TY/size(Y, 1);
%计算条件概率
pX_Y=cell(size(YValue, 1), size(X, 2));
for k=1:1:size(YValue, 1)
%条件y=yk
for i=1:1:size(X, 2)
%i为特征编号
%取得第i个特征的取值集合
XAi = AValues{i, 1};
TXij_Y = zeros(size(XAi, 1), 1);
for j=1:1:size(XAi, 1)
%查找数据中所有Y=yk且特征i的值为Aij的数据个数并累加
for t=1:1:size(X, 1)
if(Y(t, 1)==YValue(k, 1) && X(t, i) == XAi(j, 1))
TXij_Y(j, 1) = TXij_Y(j, 1) + 1;
end
end
end
PX_Y{k, i} = TXij_Y/TY(k, 1);
end
end
theta = cell(2,1);
theta{1,1} = PX_Y;
theta{2,1} = PY;
end
function theta=LaplaceNBtrain(X,Y,AValues,YValue,lambda)
%计算先验概率
TY = zeros(size(YValue, 1), 1);
for i=1:1:size(Y, 1)
for j=1:1:size(YValue)
if(Y(i, 1) == YValue(j, 1))
Y(i,1);
TY(j, 1) = TY(j, 1) + 1;
break
end
end
end
PY = (TY + lambda)/(size(Y, 1) + lambda * size(YValue, 1));
%计算条件概率
pX_Y=cell(size(YValue, 1), size(X, 2));
for k=1:1:size(YValue, 1)
%条件y=yk
for i=1:1:size(X, 2)
%i为特征编号
%取得第i个特征的取值集合
XAi = AValues{i, 1};
TXij_Y = zeros(size(XAi, 1), 1);
for j=1:1:size(XAi, 1)
%查找数据中所有Y=yk且特征i的值为Aij的数据个数并累加
for t=1:1:size(X, 1)
if(Y(t, 1)==YValue(k, 1) && X(t, i) == XAi(j, 1))
TXij_Y(j, 1) = TXij_Y(j, 1) + 1;
end
end
end
PX_Y{k, i} = (TXij_Y + lambda)/(TY(k, 1) + lambda * size(XAi, 1));
end
end
theta = cell(2,1);
theta{1,1} = PX_Y;
theta{2,1} = PY;
end
|
|