HMMR_HMM implement kmeans, hmmlearn
@@ -22,6 +22,10 @@ info = logging.info
import numpy as np
cimport numpy as np
from cpython cimport bool
+from hmmlearn import hmm
+from hmmlearn cimport hmm
+from sklearn.cluster import KMeans
+from sklearn.cluster cimport KMeans
# ------------------------------------
# MACS3 modules
@@ -52,13 +56,28 @@ cdef inline float get_weighted_density( int x, float m, float v, w ):
# public functions
# ------------------------------------
-cpdef initial_state_kmeans( dict training_data, k = 3 ):
- return None
+cpdef initial_state_kmeans( list training_data, k = 3 ):
+ # trial for kmeans:
+ kmeans = KMeans(n_clusters = k, random_state = 0).fit(training_data)
+ labels = kmeans.labels_.tolist()
+ ls = []
+ for i in range (k):
+ ls.append(labels.count(i))
+ initial_state = [x / sum(ls) for x in ls]
+ return initial_state
-cpdef hmm_training( dict training_data, initial_state ):
- return None
+cpdef hmm_training( list training_data, initial_state ):
+ # training data should be in array like format: X = np.array([[.5, .3, .1, .1], [.6, .4, 0, 0]])
+ # if we do not want init_prob to be updated through learning, set params = 'tmc' and init_prob = initial_state otherwise it will be overwritten
+ # according to base documentation, if init_prob not stated, it is set to be equally likely for any state (1/ # of components)
+ # if we have other known parameters, we should set these (ie: means_weights, covariance_type etc.)
+ # hmm_model = hmm.GaussianHMM( n_components=3, covariance_type = 'full' )
+ hmm_model = hmm.GaussianHMM( n_components=3, init_prob=initial_state, params='tmc')
+ hmm_model.fit( training_data )
+ return hmm_model
-cpdef hmm_predict( dict signals, hmm_model, binsize = 10 ):
- return None
+cpdef hmm_predict( list signals, hmm_model, binsize = 10 ):
+ predictions = hmm_model.predict( signals )
+ return predictions
