Example #1
0
class HMMGestureMonitor (GestureMonitor):

	def __init__ (self, _train_ms_list, _gesture_name, FeatureExtractor=AVFeatureExtractor):

		GestureMonitor.__init__ (self, _train_ms_list, _gesture_name, FeatureExtractor)

	def train (self, motion_sequences):

		dfs 					= [ms.get_dataframe () for ms in motion_sequences]
		examples				= [self.feature_extractor.extract (df) for df in dfs]
		examples				= [e for e in examples if not np.isnan(np.sum(e))]

		self.hmm 				= GaussianHMM (n_components=5).fit (examples)
		self.score_threshold 	= GMScoreThreshold (self.hmm.score, examples)
		self.window_timespans 	= self.calculate_window_timespans (motion_sequences)

	def classify_window_df (self, window_df):

		features = self.feature_extractor.extract (window_df)
		score = self.score_threshold.classify (features)
		return score

	def get_current_reaction (self):

		scores = [self.hmm.score (self.feature_extractor.extract(window_df)) for window_df in self.get_window_dfs ()]
		if len(scores) > 0:
			return np.max(scores)
		else:
			return None
Example #2
0
    def get_hmms(self):

        for gesture_type in self.gesture_types:

            print_status("Get_Hmms",
                         "Fitting for gesture_type: " + gesture_type)

            ### Step 1: fill hmm_examples appropriately ###
            hmm_examples = []
            for gesture in self.gestures[gesture_type]:
                hmm_rep = gesture.get_hmm_rep()
                hmm_examples.append(hmm_rep)

            ### Step 2: fit parameters for the hmm ###
            hmm = GaussianHMM(self.num_hmm_states)
            hmm.fit(hmm_examples)

            ### Step 3: store the hmm in self.hmms ###
            self.hmms[gesture_type] = hmm

            print_inner_status(
                gesture_type,
                "predicted the following sequences: (score: sequence)")
            for example in hmm_examples:
                print "		", hmm.score(example), ": ", hmm.predict(example)
	def get_hmms (self):

		for gesture_type in self.gesture_types:

			print_status ("Get_Hmms", "Fitting for gesture_type: " + gesture_type)
			### Step 1: fill hmm_examples appropriately ###
			hmm_examples = []
			for gesture in self.gestures[gesture_type]:
				hmm_rep = gesture.get_hmm_rep ()
				hmm_examples.append (hmm_rep)

			### Step 2: fit parameters for the hmm ###
			hmm = GaussianHMM (self.num_hmm_states)
			hmm.fit (hmm_examples)

			### Step 3: store the hmm in self.hmms ###
			self.hmms[gesture_type] = hmm

			print_inner_status (gesture_type, "predicted the following sequences: (score: sequence)")
			for example in hmm_examples:
				print "		", hmm.score (example), ": ", hmm.predict (example)
Example #4
0
def train_hmm(X):
    hmm = GaussianHMM(n_components=8)
    hmm.fit(X);
    print hmm.score(X[0])
    print np.shape(X[0])
    return hmm
         np.linalg.cholesky(covs[i])
         print np.linalg.eigvals(covs[i])
 tmat, smat = get_tmat_and_smat(pre_states, end=False, start=False)
 print tmat, smat
 model = GaussianHMM(n_components=n_states, n_iter=n_iter, covariance_type=cov_type, startprob=smat, transmat=tmat, init_params='mc')
 model.means_ = means
 model.covars_ = covs
 sum_inital_ll = 0.0
 sum_initial_score = 0.0
 sum_initial_map = 0.0
 remove_idx = []
 for idx, feat_from_list in enumerate(feats_as_list):
     if np.shape(feat_from_list)[0] > n_states:
         initial_ll, initial_best_seq = model.decode(feat_from_list)
         initial_map, initial_best_sep_map = model.decode(feat_from_list, algorithm='map')
         sum_initial_score += model.score(feat_from_list)
         sum_inital_ll += initial_ll
         sum_initial_map += initial_map
     else:
         remove_idx.append(idx)
         print 'too few samples in file', list_of_patient_file_paths[idx], np.shape(feat_from_list)
 print 'initial viterbi log-likelihood,', sum_inital_ll
 print 'initial score log-likelihood,', sum_initial_score
 print 'initial map log-likelihood', sum_initial_map
 remove_idx.sort()
 remove_idx.reverse()
 print 'removing...', remove_idx
 for r in remove_idx:
     del feats_as_list[r]
 model.fit(feats_as_list)
 sum_final_ll = 0.0
        covars[covars==0] = 1e-5
        
        model = GaussianHMM(numState, covariance_type="tied", n_iter=1000, init_params='abdefghijklnopqrstuvwxyzABDEFGHIJKLNOPQRSTUVWXYZ')
        model.means_ = means
        model.covars_ = covars
        
        print("Fitting model...")
        sys.stdout.flush()
        model.fit(data)

        print("Decoding states...")
        sys.stdout.flush()
        # do a loop over everything and record in one long array
        states = np.array([])
        score = 0
        for i in range(0, len(data)):
            hidden_states = model.decode(data[i])
            states = np.append(states, hidden_states[1])
            score = score + model.score(data[i])

        print("Saving data...")
        sys.stdout.flush()

        # save the states and LLH
        np.savetxt("data/substates/%s%d/%d/rep_%d_states.txt" % (basepath,stateNum,numState,repInx), states, fmt="%d")
        with open("data/substates/%s%d/%d/rep_%d_LLH.txt" % (basepath,stateNum,numState,repInx), 'w') as f:
        	f.write(str(score))
	
        saveobject(model, "data/substates/%s%d/%d/rep_%d.pk" % (basepath,stateNum,numState,repInx))    
        
print "Number of states:", sys.argv[1]

print("Loading data...")
sys.stdout.flush()
data = np.loadtxt("data/scikit-BG3Kc-K56ac.tsv", skiprows=1)
model = GaussianHMM(int(sys.argv[1]), covariance_type="tied", n_iter=1000)

print("Fitting model...")
sys.stdout.flush()
model.fit([data])

print("Decoding states...")
sys.stdout.flush()

hidden_states = model.decode(data)
llh = model.score(data)

print("Saving data...")
sys.stdout.flush()

# save the states and LLH
np.savetxt("scikit-states-all.txt", hidden_states[1], fmt="%d")
np.savetxt("scikit-states-all-LLH.txt", [llh], fmt="%f")
	
# save the actual object
def saveobject(obj, filename):
    with open(filename, 'wb') as output:
        pickle.dump(obj, output, pickle.HIGHEST_PROTOCOL)

saveobject(model, r'scikit-model.pk')