-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhmm.py
More file actions
65 lines (57 loc) · 1.94 KB
/
Copy pathhmm.py
File metadata and controls
65 lines (57 loc) · 1.94 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
from socketIO_client import SocketIO, BaseNamespace
from sklearn.externals import joblib
from hmmlearn import hmm
import numpy as np
import time
import os.path
import pickle
class HMMNamespace(BaseNamespace):
def on_connect(self):
print 'Connected to http://localhost:3000'
def on_train(self, data):
#Create dictionary of classes and raw incoming data
rawDict = {}
for entry in data:
if rawDict.has_key(entry[0]):
rawDict[entry[0]].append(entry[1])
else:
rawDict[entry[0]] = entry[1]
#Create dictionary with raw data formatted properly
dataDict = {}
for key in rawDict.keys():
final = []
for set in rawDict[key]:
for point in set['data']:
formatted = [point['gyroX'], point['gyroY'], point['gyroZ'], point['accelX'], point['accelY'], point['accelZ']]
final.append(formatted)
dataDict[key] = final
#Arrange data for hmm reading
model = []
labels = []
filename = time.strftime('%Y%m%d-%H%M%S')
for key in dataDict.keys():
model.append(hmm.GaussianHMM(n_components=1).fit(dataDict[key]))
filename += str(key)
labels.append(key)
#Save to file
filename = filename.replace(' ', '')
for i in range(0, len(model)):
joblib.dump(model[i], 'dump/HMM_' + filename + str(i) + '.pkl')
pickle.dump(labels, open('dump/' + filename + 'labels.pkl', 'wb'))
hmm_sock.emit('trained', filename)
def on_predict(self, data):
model = []
labels = pickle.load(open('dump/' + str(data['model']) + 'labels.pkl', 'rb'))
i = 0
while os.path.isfile('dump/HMM_' + str(data['model']) + str(i) + '.pkl'):
model.append(joblib.load('dump/HMM_' + str(data['model']) + str(i) + '.pkl'))
i += 1
X = np.asarray(data['myodata']).reshape(1, -1)
scores = []
for m in model:
scores.append(m.score(X))
result = labels[scores.index(max(scores))]
hmm_sock.emit('predict_data', result)
socketIO = SocketIO('localhost', 3000)
hmm_sock = socketIO.define(HMMNamespace, '/hmm_namespace')
socketIO.wait()