维特比算法的python的简单实现
維特比算法的python簡(jiǎn)單實(shí)現(xiàn)
簡(jiǎn)單介紹
實(shí)現(xiàn)了李航書(shū)籍p210的例子,例子非常經(jīng)典。我有三個(gè)盒子,每個(gè)盒子都有紅球和白球,我觀測(cè)到了三次結(jié)果:紅、白和紅,現(xiàn)在需要求出盒子的可能序列是什么。
通過(guò)這個(gè)例子更加深刻理解“求解HMM的隱變量(這里是盒子的序列)”,也就是HMM的預(yù)測(cè)問(wèn)題。
兩個(gè)矩陣pathtracingMatrix(追溯矩陣)和statedSavedMatrix(狀態(tài)存儲(chǔ)矩陣)
pathtracingMatrix[i][j]存儲(chǔ)的是第i時(shí)刻,第j狀態(tài)的前t-1最有可能的狀態(tài)
statedSavedMatrix[i][j] 存儲(chǔ)的是第i時(shí)刻,第j狀態(tài),最大值是多少,保存的目的方便下一時(shí)刻計(jì)算。
維特比算法最大優(yōu)勢(shì)在于利用動(dòng)態(tài)規(guī)劃算法,將復(fù)雜度從N^T降低到了T*N^2,將計(jì)算量降低了很多。
我寫(xiě)的算法比較小白,如果你有更好建議,歡迎留言討論,謝謝反饋。
python代碼
import numpy as np#給定參數(shù)、觀測(cè)序列的情況下,求出 #parameterspai = np.array([0.2,0.4,0.4]) #initial probability A = np.array([[0.5,0.2,0.3],[0.3,0.5,0.2],[0.2,0.3,0.5]]) #transmission probability B = np.array([[0.5,0.5],[0.4,0.6],[0.7,0.3]]) # observer probabilityprint("pai:",pai.shape) print("A:",A.shape) print("B:",B.shape)#狀態(tài)值 statesN = 3 stateDict = dict() stateDict[0] = "box_1" stateDict[1] = "box_2" stateDict[2] = "box_3"#觀測(cè)值 observedN = 2 observedDict = dict() observedDict[0] = 'red ball' observedDict[1] = 'white ball' observedSequence = np.array([0,1,0])#時(shí)間長(zhǎng)度(HMM的長(zhǎng)度) T = 3#check assert(pai.shape == (statesN,)) assert(A.shape == (statesN,statesN)) assert(B.shape == (statesN,observedN))#viterbi#追溯矩陣 pathtracingMatrix = np.zeros((T,statesN))-1 #狀態(tài)存儲(chǔ)矩陣 statedSavedMatrix = np.zeros((T,statesN))for t in range(T):if t == 0:for i in range(statesN):statedSavedMatrix[t][i] = pai[i]*B[i][observedSequence[t]]continuefor i in range(statesN):#time :tt_state_index = icurrentMaxWeight = 0currentMaxLastStateI = 0for j in range(statesN):#time :t-1weight = statedSavedMatrix[t-1][j]*A[j][i]if weight > currentMaxWeight:currentMaxWeight = weightcurrentMaxLastStateI = jpathtracingMatrix[t][i] = currentMaxLastStateIstatedSavedMatrix[t][i] = currentMaxWeight*B[i][observedSequence[t]]print("pathtracingMatrix:",pathtracingMatrix) print("statedSavedMatrix:",statedSavedMatrix)#tracing 進(jìn)行回溯 lastMaxWeightStateIndex = np.argmax(pathtracingMatrix[T-1])results = np.array([lastMaxWeightStateIndex])for i in range(T-1,0,-1):lastIndex = pathtracingMatrix[i][int(lastMaxWeightStateIndex)]results = np.append(results,lastIndex)lastMaxWeightStateIndex = lastIndex#注意輸出結(jié)果應(yīng)該反轉(zhuǎn)輸出 print("vitebi輸出狀態(tài)index為:",results[::-1])#可讀性輸出print("即:在觀測(cè)值為:",[observedDict[i] for i in observedSequence])print("最有可能盒子序列(隱狀態(tài))為:",[stateDict[i] for i in results[::-1]]) print("算法的復(fù)雜度為:T*N^2(N為隱狀態(tài)的數(shù)量)")運(yùn)行結(jié)果
運(yùn)行結(jié)果為;
vitebi輸出狀態(tài)index為: [2. 2. 2.]
即:在觀測(cè)值為: [‘red ball’, ‘white ball’, ‘red ball’]
最有可能盒子序列(隱狀態(tài))為: [‘box_3’, ‘box_3’, ‘box_3’]
算法的復(fù)雜度為:T*N^2(N為隱狀態(tài)的數(shù)量)
與書(shū)上的結(jié)果一致
總結(jié)
以上是生活随笔為你收集整理的维特比算法的python的简单实现的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: linux 下载百度网盘资源 cent
- 下一篇: python怎么加逗号_Python 逗