10.1题
function HMM
A = [0.5,0.2,0.3;0.3,0.5,0.2;0.2,0.3,0.5];
B = [0.5,0.5;0.4,0.6;0.7,0.3];
pi0 = [0.2,0.4,0.4]';
O = [1,2,1,2];
sizes = length(O);
beita = zeros(3,sizes);
alpha = zeros(3,sizes);
beita(:,sizes) = 1;
alpha(:,1) = pi0.*B(:,O(1));
for i=sizes-1:-1:1
beita(:,i) = A*(beita(:,i+1).*B(:,O(i+1)));
end
for i = 2:sizes
alpha(:,i) = (alpha(:,i-1)'*A)'.*B(O(i));
end
P = pi0'*(beita(:,1).*B(:,O(1)));
结果:
10.2题
MATLAB 代码下
function HMM
A = [0.5,0.2,0.3;0.3,0.5,0.2;0.2,0.3,0.5];
B = [0.5,0.5;0.4,0.6;0.7,0.3];
pi0 = [0.2,0.4,0.4]';
O = [1,2,1,1,2,1,2,2];
sizes = length(O);
beita = zeros(3,sizes);
alpha = zeros(3,sizes);
beita(:,sizes) = 1;
alpha(:,1) = pi0.*B(:,O(1));
for i=sizes-1:-1:1
beita(:,i) = A*(beita(:,i+1).*B(:,O(i+1)));
end
for i = 2:sizes
alpha(:,i) = (alpha(:,i-1)'*A)'.*B(O(i));
end
P = alpha(3,4)*beita(3,4)/(alpha(:,4)'*beita(:,4));
end
结果:
10.3题(先算10.2的情况)
function HMM
A = [0.5,0.2,0.3;0.3,0.5,0.2;0.2,0.3,0.5];
B = [0.5,0.5;0.4,0.6;0.7,0.3];
pi0 = [0.2,0.4,0.4]';
O = [1,2,1,1,2,1,2,2];
sizes = length(O);
I = zeros(1,sizes);
delta = zeros(3,sizes);
fai = zeros(3,sizes-1);
delta(:,1) = pi0.*B(:,O(1));
fai(:,1) = 0;
for i = 2 :sizes
delta(:,i) = (max(repmat(delta(:,i-1),1,3).*A,[],1))'.*B(:,O(i));
[ MMMMM, fai(:,i)] = max(repmat(delta(:,i-1),1,3).*A,[],1);
end
P = max(delta(:,sizes));
[MMMMM,I(sizes)] = max(delta(:,sizes),[],1);
I(1:sizes-1) = fai(I(sizes),2:end);
end
隐状态的序列如上
简单 修改代码为O=[1,2,1,2]就可以得到10.1的隐藏序列答案
自己写代码算的 供参考,如果有错谢谢大家指正,我也是搜不到答案才这样的