import numpy as np
class HiddenMarkovModel:
def __init__(self, states, observations, start_prob, transition_prob, emission_prob):
self.states = states
self.observations = observations
self.start_prob = start_prob
self.transition_prob = transition_prob
self.emission_prob = emission_prob
def forward(self, observations):
T = len(observations)
N = len(self.states)
alpha = np.zeros((T, N))
alpha[0, :] = self.start_prob * self.emission_prob[:, self.observations.index(observations[0])]
for t in range(1, T):
for j in range(N):
alpha[t, j] = np.sum(alpha[t-1, i] * self.transition_prob[i, j] * self.emission_prob[j, self.observations.index(observations[t])] for i in range(N))
return alpha
def backward(self, observations):
T = len(observations)
N = len(self.states)
beta = np.zeros((T, N))
beta[T-1, :] = 1
for t in range(T-2, -1, -1):
for i in range(N):
beta[t, i] = np.sum(self.transition_prob[i, j] * self.emission_prob[j, self.observations.index(observations[t+1])] * beta[t+1, j] for j in range(N))
return beta
def forward_backward(self, observations):
alpha = self.forward(observations)
beta = self.backward(observations)
state_prob = alpha * beta / np.sum(alpha * beta, axis=1, keepdims=True)
return state_prob
states = ['Healthy', 'Fever']
observations = ['normal', 'cold', 'dizzy']
start_prob = np.array([0.6, 0.4])
transition_prob = np.array([[0.7, 0.3], [0.4, 0.6]])
emission_prob = np.array([[0.5, 0.4, 0.1], [0.1, 0.3, 0.6]])
hmm = HiddenMarkovModel(states, observations, start_prob, transition_prob, emission_prob)
observations_sequence = ['normal', 'cold', 'dizzy']
alpha = hmm.forward(observations_sequence)
print("Forward probabilities:")
print(alpha)
beta = hmm.backward(observations_sequence)
print("\nBackward probabilities:")
print(beta)
state_prob = hmm.forward_backward(observations_sequence)
print("\nEstimated state probabilities:")
print(state_prob)