Python(hmmlearn):值错误[无法从形状广播输入数组]

时间:2016-06-10 07:21:19

标签: python-2.7 hmmlearn

我正在运行构建HMM模型的示例代码,但我发现它给了我Value value.Probably它是一个numpy错误。

import hmmlearn.hmm as hmm
transmat = np.array([[0.7, 0.3],
                      [0.3, 0.7]])
emitmat = np.array([[0.9, 0.1],
                    [0.2, 0.8]])
# obs = np.array([0, 0, 1, 0, 0])
startprob = np.array([0.5, 0.5])
h = hmm.MultinomialHMM(n_components=2)
h.startprob_=startprob
h.transmat_=transmat
h.emissionprob_ = emitmat

h.fit([[0, 0, 1, 0, 0]])

h.decode([[0, 0, 1, 0, 0]])
# print h

我将错误视为:

ValueError                                Traceback (most recent call last)
<ipython-input-59-2ea6714302e1> in <module>()
     13 h.fit([[0, 0, 1, 0, 0]])
     14 
---> 15 h.decode([[0, 0, 1, 0, 0]])
     16 # print h

/home/aman/anaconda2/lib/python2.7/site-packages/hmmlearn-0.2.1-py2.7-linux-x86_64.egg/hmmlearn/base.pyc in decode(self, X, lengths, algorithm)
    311             logprobij, state_sequenceij = decoder(X[i:j])
    312             logprob += logprobij
--> 313             state_sequence[i:j] = state_sequenceij
    314 
    315         return logprob, state_sequence

ValueError: could not broadcast input array from shape (5) into shape (1)

我做错了什么?

1 个答案:

答案 0 :(得分:2)

观察它是采取转置后的列向量。

import numpy as np
import hmmlearn.hmm as hmm 
n_components = 2
startprob = np.array([.01,.99])
transmat = np.array([[0.99, 0.01], [0.3, 0.7]])
emissionprob  = np.array([[0.1,0.9], [0.5,0.5]])
model = hmm.MultinomialHMM(n_components=n_components)
model.startprob_=startprob
model.emissionprob_=emissionprob
model.transmat_=transmat
observation=np.array([[0,0,1,0,0]]).T
model.fit(observation)
model.decode(observation,algorithm="viterbi")