Python 将数据拟合到hmm。多项式hmm
我试图使用hmmlearn库预测给定一些数据的最佳序列,但我得到了一个错误。我的代码是:Python 将数据拟合到hmm。多项式hmm,python,python-2.7,hmmlearn,Python,Python 2.7,Hmmlearn,我试图使用hmmlearn库预测给定一些数据的最佳序列,但我得到了一个错误。我的代码是: from hmmlearn import hmm trans_mat = np.array([[0.2,0.6,0.2],[0.4,0.0,0.6],[0.1,0.2,0.7]]) emm_mat = np.array([[0.2,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1],[0.1,0.1,0.1,0.1,0.2,0.1,0.1,0.1,0.1],[0.1,0.1,0.1,0.1,0
from hmmlearn import hmm
trans_mat = np.array([[0.2,0.6,0.2],[0.4,0.0,0.6],[0.1,0.2,0.7]])
emm_mat = np.array([[0.2,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1],[0.1,0.1,0.1,0.1,0.2,0.1,0.1,0.1,0.1],[0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.1,0.2]])
start_prob = np.array([0.3,0.4,0.3])
X = [3,4,5,6,7]
model = GaussianHMM(n_components = 3, n_iter = 1000)
X = np.array(X)
model.startprob_ = start_prob
model.transmat_ = trans_mat
model.emissionprob_ = emm_mat
# Predict the optimal sequence of internal hidden state
x = model.fit([X])
print(model.decode([X]))
但我得到一个错误,说:
Traceback (most recent call last):
File "hmm_loyalty.py", line 55, in <module>
x = model.fit([X])
File "build/bdist.macosx-10.6-x86_64/egg/hmmlearn/base.py", line 421, in fit
File "build/bdist.macosx-10.6-x86_64/egg/hmmlearn/hmm.py", line 183, in _init
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sklearn/cluster/k_means_.py", line 785, in fit
X = self._check_fit_data(X)
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/sklearn/cluster/k_means_.py", line 758, in _check_fit_data
X.shape[0], self.n_clusters))
ValueError: n_samples=1 should be >= n_clusters=3
回溯(最近一次呼叫最后一次):
文件“hmm_loyalty.py”,第55行,在
x=模型拟合([x])
文件“build/bdist.macosx-10.6-x86_64/egg/hmmlearn/base.py”,第421行,在fit中
文件“build/bdist.macosx-10.6-x86_64/egg/hmmlearn/hmm.py”,第183行,在_init中
文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site packages/sklearn/cluster/k_means_uu.py”,第785行
X=自检查拟合数据(X)
文件“/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site packages/sklearn/cluster/k_means_uu.py”,第758行,在_check_fit_数据中
X.shape[0],self.n_簇)
ValueError:n_samples=1应大于等于n_clusters=3
有人知道这意味着什么,我能做些什么来解决它吗 您的代码存在许多问题:
model
是一种GaussianHMM
。您可能想要多项式hmm
多项式hmm
X必须具有形状(n_样本,1)
,因为观测值是一维的fit
import numpy as np
from hmmlearn import hmm
model = hmm.MultinomialHMM(n_components=3)
model.startprob_ = np.array([0.3, 0.4, 0.3])
model.transmat_ = np.array([[0.2, 0.6, 0.2],
[0.4, 0.0, 0.6],
[0.1, 0.2, 0.7]])
model.emissionprob_ = np.array([[0.2, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1, 0.2, 0.1, 0.1, 0.1, 0.1],
[0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.1, 0.2]])
# Predict the optimal sequence of internal hidden state
X = np.atleast_2d([3, 4, 5, 6, 7]).T
print(model.decode(X))
作为一个快速的跟进,为什么我们要使用X的转置?因为在
np.之后,X
的形状至少是(1,n个样本)
。假设我没有设置模型参数,我将如何调用fit函数?它说我需要(n_样本,1),但上面的X形状不适合我。它仍然表示ValueError:多项式分布的预期样本该错误可能是由X
不连续引起的。确保X
包含[X.min();X.max()]
范围内的所有值。在np.之后,X的形状至少为(5,1)
,其中5为X,1为长度。那么我可以这样理解吗???(model.fit(X,长度)
根据文件)@SergeiLebedev