12-2-HMM-demo.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. import numpy as np
  2. import matplotlib.pyplot as plt
  3. from hmmlearn import hmm
  4. def main():
  5. # 初始概率矩阵
  6. startprob = np.array([0.6, 0.3, 0.1, 0.0])
  7. # 转移概率矩阵
  8. transmat = np.array([[0.7, 0.2, 0.0, 0.1],
  9. [0.3, 0.5, 0.2, 0.0],
  10. [0.0, 0.3, 0.5, 0.2],
  11. [0.2, 0.0, 0.2, 0.6]])
  12. # 每个成分的均值
  13. means = np.array([[0.0, 0.0],
  14. [0.0, 11.0],
  15. [9.0, 10.0],
  16. [11.0, -1.0]])
  17. # 每个成分的协方差
  18. covars = .5 * np.tile(np.identity(2), (4, 1, 1))
  19. # 定义算法参数
  20. model = hmm.GaussianHMM(n_components=4, covariance_type="full")
  21. # 我们没有从数据中拟合它,而是直接设置估计值
  22. # 参数、分量的均值和协方差
  23. model.startprob_ = startprob
  24. model.transmat_ = transmat
  25. model.means_ = means
  26. model.covars_ = covars
  27. # 生成示例
  28. X, Z = model.sample(500)
  29. # 画图
  30. plt.plot(X[:, 0], X[:, 1], ".-", label="observations", ms=6,
  31. mfc="orange", alpha=0.7)
  32. for i, m in enumerate(means):
  33. plt.text(m[0], m[1], 'Component %i' % (i + 1),
  34. size=17, horizontalalignment='center',
  35. bbox=dict(alpha=.7, facecolor='w'))
  36. plt.legend(loc='best')
  37. plt.show()
  38. if __name__ == '__main__':
  39. main()