Skip to content

Instantly share code, notes, and snippets.

@tristanwietsma
Created March 12, 2014 02:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tristanwietsma/9499344 to your computer and use it in GitHub Desktop.
Save tristanwietsma/9499344 to your computer and use it in GitHub Desktop.
Hidden Markov model example
from __future__ import division
import numpy
from sklearn import hmm
"""
X is a numpy array with shape (#samples, #sensors).
X = [[sensor1(0), sensor2(0)], [sensor1(1), sensor2(1)], ..., [sensor1(T), sensor2(T)]]
nc = number of latent states (3 would imply three strata)
"""
def Fit(X, nc):
NUM_COMPONENTS = nc
model = hmm.GaussianHMM(
NUM_COMPONENTS, covariance_type="full", n_iter=1000)
model.fit([X])
hidden_states = model.predict(X)
h = numpy.array(hidden_states)
diff = h[1:] - h[:-1]
return list(numpy.transpose(numpy.argwhere(diff != 0))[0])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment