Search code examples
python-2.7hmmlearn

Python(hmmlearn):Value Error[could not broadcast input array from shape]


I am running sample code for building HMM model, but i see it gives me Value error.Probably its a numpy error.

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

I see the error as :

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)

what i am doing wrong?


Solution

  • Observation it takes is the column vector after taking the transpose.

    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")