【发布时间】:2015-08-19 18:54:28
【问题描述】:
下面的代码是我在 HMM 模型中使用的 Viterbi 算法的 here 找到的 Python 实现。该链接还提供了一个测试用例。
在__init__,我明白:
-
initialProb是从给定状态开始的概率, -
transProb是在任何给定时间从一种状态移动到另一种状态的概率,但是
我看不懂的参数是obsProb。谁能解释一下?
import numpy as np
'''
N: number of hidden states
'''
class Decoder(object):
def __init__(self, initialProb, transProb, obsProb):
self.N = initialProb.shape[0]
self.initialProb = initialProb
self.transProb = transProb
self.obsProb = obsProb
assert self.initialProb.shape == (self.N, 1)
assert self.transProb.shape == (self.N, self.N)
assert self.obsProb.shape[0] == self.N
def Obs(self, obs):
return self.obsProb[:, obs, None]
def Decode(self, obs):
trellis = np.zeros((self.N, len(obs)))
backpt = np.ones((self.N, len(obs)), 'int32') * -1
# initialization
trellis[:, 0] = np.squeeze(self.initialProb * self.Obs(obs[0]))
for t in xrange(1, len(obs)):
trellis[:, t] = (trellis[:, t-1, None].dot(self.Obs(obs[t]).T) * self.transProb).max(0)
backpt[:, t] = (np.tile(trellis[:, t-1, None], [1, self.N]) * self.transProb).argmax(0)
# termination
tokens = [trellis[:, -1].argmax()]
for i in xrange(len(obs)-1, 0, -1):
tokens.append(backpt[tokens[-1], i])
return tokens[::-1]
【问题讨论】:
-
不知道是不是名字不好。我希望它指的是观察序列。 (我对vetirbi算法没有任何经验,但是有this wikipedia page)
-
另外,test 显示它是一个 numpy 数组。
-
github.com/phvu/misc/blob/master/viterbi/viterbi.py 中的 obsProb 对应于en.wikipedia.org/wiki/Viterbi_algorithm#Example 中的emission_probability (emit_p),表示隐藏状态概率。 obsProb 使用 viterbi.py 第 16-17 行 (github.com/phvu/misc/blob/master/viterbi/viterbi.py#L16) 中的输入数据进行索引,以在第 24 行 (github.com/phvu/misc/blob/master/viterbi/viterbi.py#L24) 初始化格子数组
-
@Tris Nefzger,感谢让我困惑的 emit 部分。