Oneself according to the algorithm to write two simple MATLAB code, applied to the data in the example to obtain the correct solution, here does not consider the problem of speed optimization, please everyone feel free:
1. Model evaluation
The HMM model is as follows, and the probability of generating the observing symbol sequence O={ABAB} is calculated based on the forward algorithm. State transition probability matrix A = [0.4 0.6 0; 0 0.8 0.2; 0 0 1]; observation matrix: o= [0.7 0.3 0.7 0.3; 0.4 0.6 0.4 0.6; 0.8 0.2 0.8 0.2]; initial probability matrix: pi = [1 0 0]; the calculation steps in the example: 1. When t = 1 o'clock 2. When t = 2 o'clock 3. When t = 3 o'clock 4. When it ends up with: P (o|λ) = A4 (1) + A4 (2) + A4 (3) =0.07176 96matlab Code implementation:
%a Matrix is a state transition matrix a= [0.4 0.6 0; 0 0.8 0.2; 0 0 1];%o matrix is the observation matrix,the observed sequence is abab% and the O matrix is extended according to the observed sequence. o= [0.7 0.3 0.7 0.3; 0.4 0.6 0.4 0.6; 0.8 0.2 0.8 0.2];%pi is the initial state probability matrix Pi= [1 0 0];[n, n] = size (a);[n, T] = size (o);N= Length (pi);Alpha= Zeros (n,t);% initialize T=Alpha matrix of 1 moments fori = 1: NAlpha(i,1) = Pi (i) *o (i,1);End fort = 1: T-1 fori = 1: Nsum= 0; forj = 1: Nsum= sum + alpha (j,t) *a (j,i);EndAlpha(i,t+1) = Sum * O (i,t+1);EndEndP= 0; fori = 1: NP= P + alpha (i,t);EndP
The calculated P-value is 0.0718, which is very close to the results obtained in the example.
2. Optimal path selection problem
The calculation steps in the example are:
1. Initialize:
2. When t = 2 o'clock
3. When t = 3 o'clock
4. When t = 4 o'clock
Recursive results:
Optimal State sequence:
S1,s2,s2,s2.
MATLAB Code implementation:
%a Matrix is a state transition matrix a= [0.4 0.6 0; 0 0.8 0.2; 0 0 1];%o matrix is the observation matrix,the observed sequence is abab% and the O matrix is extended according to the observed sequence. o= [0.7 0.3 0.7 0.3; 0.4 0.6 0.4 0.6; 0.8 0.2 0.8 0.2];%pi is the initial state probability matrix Pi= [1 0 0];[n, n] = size (a);[n, T] = size (o);N= Length (pi);Derta= Zeros (n,t);Pha= Zeros (n,t);Maxer= Zeros (n,n);% initialize T=Alpha matrix of 1 moments fori = 1: NDerta(i,1) = Pi (i) *o (i,1);End fort = 1: T-1 fori = 1: NNu= 0; forj = 1: NMaxer(j,i) = Derta (j,t) *a (j,i);End ifMax (Maxer (:, i)) ==0Pha(i,t+1) = 0;Else[Nu, PHA (i,t+1)] = Max (Maxer (:, i));EndDerta(i,t+1) = Nu * O (i,t+1);EndEndDertaphap= 0;Q= Zeros (1,t);[P Q(T)] = Max (Derta (:, T)); fori = T-1:-1:1Q(i) = PHA (q (i+1), i+1);EndQ
The result of the operation is:
Q =
1 2 2 2
It can be seen that the results are the same as those calculated in the example.
Evaluation of Hidden Markov model model and MATLAB implementation of Optimal path