如何在hmmlearn(Hidden Markov Model)中解码后将隐藏状态映射到相应的类别?

时间:2016-09-28 19:23:37

标签: python hidden-markov-models hmmlearn

我想使用隐马尔可夫模型(解码问题)预测隐藏状态。数据是分类的。隐藏的状态包括饥饿,休息,运动和电影。观察集包括Food,Home,Outdoor&娱乐和艺术&娱乐。我的程序首先根据观察序列(Baum-Welch算法)训练HMM。然后我做解码(维特比算法)来预测隐藏状态序列。

我的问题是我如何将结果(非负整数)映射到相应的类别,如Hungry或Rest。由于训练算法的非确定性属性,对于相同数据的每次训练,参数是不同的。因此,如果我按照以下代码执行映射,则隐藏状态序列每次都不同。

代码如下:

from __future__ import division
import numpy as np
from hmmlearn import hmm

states = ["Hungry", "Rest", "Exercise", "Movie"]
n_states = len(states)

observations = ["Food", "Home", "Outdoor & Recreation", "Arts & Entertainment"]

# The number in this sequence is the index of observation
category_sequence = [1, 0, 1, 2, 1, 3, 1]
Location = np.array([category_sequence]).T
model = hmm.MultinomialHMM(n_components=n_states).fit(Location)

logprob, result = model.decode(Location)
print "Category:", ", ".join(map(lambda x: observations[x], Location.T[0]))
print "Intent:", ", ".join(map(lambda x: states[x], result))

1 个答案:

答案 0 :(得分:3)

这称为标签切换问题。模型的对数似然性在所有状态上求和,因此与特定排序无关。

据我所知,没有处理它的一般方法。您可以尝试的事项包括:

  • 找到部分标记的数据集,在其上运行predict并使用预测将状态索引映射到相应的标签。
  • 为每种状态下的可能参数值提供启发式算法。对于多项式来说这可能很棘手,但是如果你建模,则可以做到这一点。加速度计数据。

更新:一种特殊版本的猜测状态,用于标记贴标签数据的映射。

def guess_labels(hmm, X, labels):
    result = [None] * hmm.n_components
    for label, y_t in zip(labels, hmm.predict(X)):
        assigned = result[y_t]
        if assigned is not None:
            # XXX clearly for any real data there might be
            #     (and there will be) conflicts. Here we just blindly
            #     hope the ``assert`` never fires.
            assert assigned == label
        else:
            result[y_t] = label
    return result