后向算法给出了不同的答案

时间:2017-02-22 21:28:31

标签: matlab

我试图在Matlab中解决结果可能性问题实现前向和后向算法,但是他们给出了不同的答案。我不知道在我的后向代码中我做错了什么(前进的代码与答案匹配)。任何人都可以帮助我吗?

%Forward Algorithm for HMM Problem
clc;clear;

states=['A','B']; %The N "hidden" states
N=length(states);
emmision_letters=['x','y','z']; % the emission letters.

%Initial Probabilities of states has equalized probablity.
I_prob=repelem(1/N, N)';
% Transition probabilities of states
T_prob=[0.303   0.697; 
       0.831   0.169 ]; 
% Emission prob( Prob of emission letters from given the state)
E_prob=[0.533   0.065   0.402; 
       0.342   0.334   0.324];
input_em='xzyyzzyzyy'; % emission letters
emlist=zeros(1,length(input_em)); %generate the list of the emission letters.

for i =1:length(input_em)
    if input_em(i)=='x'
        emlist(i)=1;
    elseif input_em(i)=='y'
        emlist(i)=2;
    elseif input_em(i)=='z'
        emlist(i)=3;
    end
end

 lem=length(emlist);

 Fq=zeros(N,lem);
 Bq=zeros(N,lem);% the table hold the values

 %Forward 
 for i=1:lem
    if i==1  
        %for i=1, Fq(1)=a_qstart*eq(x1)
        Fq(:,i)=I_prob.*E_prob(:,emlist(i)); 
    else
        % for i=2...n, for each q in Q, Fq(i)=sum(Fq(i-1)*a_qq'*e_q(xi))
        for j=1:N
            %Fq(i)=sum{fq(i-1)*Aqq'*Eq(xi)}
            Fq(j,i)=sum(Fq(:,i-1).*T_prob(:,j)).*E_prob(j,emlist(i)); 
        end
    end
 end
sum(Fq(:,lem)) % the last one represent the whole sequence


% Backward Algorithm for HMM Problem
    for i=lem:-1:1
        if i==lem
            % for i =n, Bq(n)=1
            Bq(:,i)=1;
        else
            % for i=n-1...1, for each q in Q
            for j=1:N
                % instead of calculate transition into A/B in i, 
                % calculate which jump out of A/B in step i+1
                % Bq(i)=sum(Bq(i+1)*a_qq'*e_q(x_i+1))
                Bq(j,i)=sum(Bq(:,i+1).*T_prob(j,:)').* E_prob(j,emlist(i+1));
            end 
        end
    end

    sum(Bq(:,1))

我看不出有什么问题。谢谢大家的帮助!

1 个答案:

答案 0 :(得分:1)

$$ B_q(i)= \ sum_ {q ^ \ prime \ in Q}(a_ {qq ^ \ prime} e_ {q ^ \ prime x_ {i + 1}} B_ {q ^ {\ prime} }(I + 1))$$

在你的for循环中:

Bq(j,i)=sum(Bq(:,i+1).*T_prob(j,:)').* E_prob(:,emlist(i+1));

我认为这会奏效。