-
Notifications
You must be signed in to change notification settings - Fork 1
/
predict.py
173 lines (122 loc) · 4.19 KB
/
predict.py
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
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
# sklearn functions
from sklearn.svm import LinearSVC, SVC
from sklearn.cross_validation import cross_val_score
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.cross_validation import train_test_split
from sklearn import preprocessing
import warnings
import json
import os
from sklearn.externals import joblib
import numpy as np
import pickle
import time
# My helpers
from preprocess import extractFeatures
from preprocess import sampleSet
def loadObject(filename):
with open(filename, 'r') as input:
obj = pickle.load(input)
return obj
def modelDir(sensor):
return 'sensors/' + sensor + '/model/'
def dataDir(sensor):
return 'sensors/' + sensor + '/samples/'
def predictionDir(sensor):
return 'sensors/' + sensor + '/predictions/'
def commandDir(sensor):
return 'cmd/'
# Read a meta file
def readMeta(sensor):
path = predictionDir(sensor) + 'meta.json'
meta = json.loads(open(path,'r').read())
return meta
# Generate a list of labels from meta.json
def generateLabels(meta):
labels = []
for sample in meta:
labels.append(sample['label'])
# Remove duplicate
output = []
for i in labels:
if not i in output:
output.append(i)
return output
def generateData(meta,dataDir):
allFeatures = []
allLabels = []
for sample in meta:
# Extract features and a label
rawData = np.genfromtxt(dataDir + sample['filename'], delimiter=',')
features = extractFeatures(rawData)
# Stack features and labels
if allFeatures == []:
allFeatures = features
else:
allFeatures = np.vstack((allFeatures,features))
return allFeatures
def makePrediction(sensor):
# create a lock file to avoid collision
lockPath = commandDir(sensor) + 'lock'
open(lockPath, 'a').close()
command = {"command":"predict", "sensor":sensor, "sampleNum":3}
with open(commandDir(sensor) + 'cmd', 'w') as f:
f.write(json.dumps(command))
os.remove(lockPath)
while not os.path.exists(predictionDir(sensor)+'meta.json'):
time.sleep(0.1)
time.sleep(1)
# Read labels from meta.json
meta = readMeta(sensor)
features = generateData(meta, predictionDir(sensor))
# prescaling
scaler = joblib.load(modelDir(sensor)+'scaler.pkl')
scaledFeatures = scaler.transform(features)
# Feture selection
selector = joblib.load(modelDir(sensor)+'selector.pkl')
selectedFeatures = selector.transform(scaledFeatures)
clf = joblib.load(modelDir(sensor)+'model.pkl')
predictions = clf.predict(selectedFeatures)
labels = loadObject(modelDir(sensor)+'labels.pkl')
for p in predictions:
print labels[p.astype(int)]
for sample in meta:
os.remove(predictionDir(sensor) + sample['filename'])
os.remove(predictionDir(sensor) + 'meta.json')
#pred = hardCoded(data)
#return pred
return labels[predictions[predictions.size-1].astype(int)]
def predictWithData(sensor,data):
pred = hardCoded(data)
return pred
# Read labels from meta.json
#meta = readMeta(sensor)
features = extractFeatures(data)
# prescaling
scaler = joblib.load(modelDir(sensor)+'scaler.pkl')
scaledFeatures = scaler.transform(features)
# Feture selection
selector = joblib.load(modelDir(sensor)+'selector.pkl')
selectedFeatures = selector.transform(scaledFeatures)
clf = joblib.load(modelDir(sensor)+'model.pkl')
predictions = clf.predict(selectedFeatures)
labels = loadObject(modelDir(sensor)+'labels.pkl')
return labels[predictions[0].astype(int)]
def hardCoded(data):
acc = data[:,6]
d = np.max(acc) - np.min(acc)
if(d > 2):
return 'knocking'
else:
return 'silent'
# Main function
if __name__ == "__main__":
warnings.filterwarnings('ignore')
sensor = 'knocking2'
# Read labels from meta.json
rawData = np.genfromtxt('./sensors/knocking2/samples/1.csv', delimiter=',')
prediction = predictWithData(sensor,rawData);
print prediction
#for sample in meta:
#os.remove(predictionDir(sensor) + sample['filename'])
#os.remove(predictionDir(sensor) + 'meta.json')