前提准备
pip install sklearn
pip install hmmlearn
代码
import numpy as npfrom hmmlearn import hmm############################################################### Prepare parameters for a 4-components HMM# Initial population probabilitystartprob = np.array([0.6, 0.3, 0.1, 0.0])# The transition matrix, note that there are no transitions possible# between component 1 and 3transmat = np.array([[0.7, 0.2, 0.0, 0.1],[0.3, 0.5, 0.2, 0.0],[0.0, 0.3, 0.5, 0.2],[0.2, 0.0, 0.2, 0.6]])# The means of each componentmeans = np.array([[0.0, 0.0],[0.0, 11.0],[9.0, 10.0],[11.0, -1.0]])# The covariance of each componentcovars = .5 * np.tile(np.identity(2), (4, 1, 1))# Build an HMM instance and set parametersmodel = hmm.GaussianHMM(n_components=4, covariance_type="full")# Instead of fitting it from the data, we directly set the estimated# parameters, the means and covariance of the componentsmodel.startprob_ = startprobmodel.transmat_ = transmatmodel.means_ = meansmodel.covars_ = covars################################################################ Generate samplesX, Z = model.sample(500)print(Z)
