前提准备

  • pip install sklearn

  • pip install hmmlearn

代码

  1. import numpy as np
  2. from hmmlearn import hmm
  3. ##############################################################
  4. # Prepare parameters for a 4-components HMM
  5. # Initial population probability
  6. startprob = np.array([0.6, 0.3, 0.1, 0.0])
  7. # The transition matrix, note that there are no transitions possible
  8. # between component 1 and 3
  9. transmat = np.array([[0.7, 0.2, 0.0, 0.1],
  10. [0.3, 0.5, 0.2, 0.0],
  11. [0.0, 0.3, 0.5, 0.2],
  12. [0.2, 0.0, 0.2, 0.6]])
  13. # The means of each component
  14. means = np.array([[0.0, 0.0],
  15. [0.0, 11.0],
  16. [9.0, 10.0],
  17. [11.0, -1.0]])
  18. # The covariance of each component
  19. covars = .5 * np.tile(np.identity(2), (4, 1, 1))
  20. # Build an HMM instance and set parameters
  21. model = hmm.GaussianHMM(n_components=4, covariance_type="full")
  22. # Instead of fitting it from the data, we directly set the estimated
  23. # parameters, the means and covariance of the components
  24. model.startprob_ = startprob
  25. model.transmat_ = transmat
  26. model.means_ = means
  27. model.covars_ = covars
  28. ###############################################################
  29. # Generate samples
  30. X, Z = model.sample(500)
  31. print(Z)