ML--HMM(隱馬爾可夫模型及python的實現2)
阿新 • • 發佈:2019-02-08
1.HMM的應用1,這個程式碼不知道出處了,若有侵權請聯絡本文作者刪除,註釋為本人所加。
2.對基本的HMM需要進一步瞭解的,請戳這裡
3.下面是HMM程式碼的解釋之一
# _*_ coding:utf-8 _*_
# __author__='dragon'
"""
test HMM
"""
from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
from hmmlearn import hmm
##這裡要求先裝好了hmm這個包
states = ["Rainy", "Sunny" ]##隱藏狀態
n_states = len(states)##長度
observations = ["walk", "shop", "clean"]##可觀察的狀態
n_observations = len(observations)##可觀察序列的長度
start_probability = np.array([0.6, 0.4])##開始轉移概率
##轉移矩陣
transition_probability = np.array([
[0.7, 0.3],
[0.4, 0.6]
])
##混淆矩陣
emission_probability = np.array([
[0.1, 0.4, 0.5 ],
[0.6, 0.3, 0.1]
])
#構建了一個MultinomialHMM模型,這模型包括開始的轉移概率,隱含間的轉移矩陣A(transmat),隱含層到可視層的混淆矩陣emissionprob,下面是引數初始化
model = hmm.MultinomialHMM(n_components=n_states)
model._set_startprob(start_probability)
model._set_transmat(transition_probability)
model._set_emissionprob(emission_probability)
# predict a sequence of hidden states based on visible states
bob_says = [2, 2, 1, 1, 2, 2]##預測時的可見序列
logprob, alice_hears = model.decode(bob_says, algorithm="viterbi")
print logprob##該引數反映模型擬合的好壞
##最後輸出結果
print "Bob says:", ", ".join(map(lambda x: observations[x], bob_says))
print "Alice hears:", ", ".join(map(lambda x: states[x], alice_hears))