forked from schollz/find
-
Notifications
You must be signed in to change notification settings - Fork 0
/
rf.py
242 lines (214 loc) · 8.13 KB
/
rf.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
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
import json
import sys
import os
import pickle
import sklearn
import random
import numpy
import socket
import threading
import argparse
from random import shuffle
import socketserver
from sklearn.ensemble import RandomForestClassifier
from sklearn.feature_extraction import DictVectorizer
from sklearn.pipeline import make_pipeline
from sklearn.neural_network import MLPClassifier
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.gaussian_process import GaussianProcessClassifier
from sklearn.gaussian_process.kernels import RBF
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
DEBUG = False
random.seed(123)
class RF(object):
#data = []
def __init__(self):
self.size = 0
self.data = []
self.nameX = []
self.trainX = numpy.array([])
self.testX = numpy.array([])
self.nameY = []
self.trainY = []
self.testY = []
self.macSet = set()
self.locationSet = set()
def get_data(self, fname, splitRatio):
# First go through once and get set of macs/locations
X = []
with open("data/" + fname + ".rf.json", 'r') as f_in:
for fingerprint in f_in:
try:
data = json.loads(fingerprint)
except:
pass
X.append(data)
self.locationSet.add(data['location'])
for signal in data['wifi-fingerprint']:
self.macSet.add(signal['mac'])
if DEBUG:
print("Loaded %d fingerprints" % len(X))
# Convert them to lists, for indexing
self.nameX = list(self.macSet)
self.nameY = list(self.locationSet)
# Go through the data again, in a random way
shuffle(X)
# Split the dataset for training / learning
trainSize = int(len(X) * splitRatio)
if DEBUG:
print("Training size is %d fingerprints" % trainSize)
# Initialize X, Y matricies for training and testing
self.trainX = numpy.zeros((trainSize, len(self.nameX)))
self.testX = numpy.zeros((len(X) - trainSize, len(self.nameX)))
self.trainY = [0] * trainSize
self.testY = [0] * (len(X) - trainSize)
curRowTrain = 0
curRowTest = 0
for i in range(len(X)):
newRow = numpy.zeros(len(self.nameX))
for signal in X[i]['wifi-fingerprint']:
newRow[self.nameX.index(signal['mac'])] = signal['rssi']
if i < trainSize: # do training
self.trainX[curRowTrain, :] = newRow
self.trainY[curRowTrain] = self.nameY.index(X[i]['location'])
curRowTrain = curRowTrain + 1
else:
self.testX[curRowTest, :] = newRow
self.testY[curRowTest] = self.nameY.index(X[i]['location'])
curRowTest = curRowTest + 1
def learn(self, dataFile, splitRatio):
self.get_data(dataFile, splitRatio)
if DEBUG:
names = [
"Nearest Neighbors",
"Linear SVM",
"RBF SVM",
"Gaussian Process",
"Decision Tree",
"Random Forest",
"Neural Net",
"AdaBoost",
"Naive Bayes",
"QDA"]
classifiers = [
KNeighborsClassifier(3),
SVC(kernel="linear", C=0.025),
SVC(gamma=2, C=1),
GaussianProcessClassifier(1.0 * RBF(1.0), warm_start=True),
DecisionTreeClassifier(max_depth=5),
RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
MLPClassifier(alpha=1),
AdaBoostClassifier(),
GaussianNB(),
QuadraticDiscriminantAnalysis()]
for name, clf in zip(names, classifiers):
try:
clf.fit(self.trainX, self.trainY)
score = clf.score(self.testX, self.testY)
print(name, score)
except:
pass
# for max_feature in ["auto","log2",None,"sqrt"]:
# for n_estimator in range(1,30,1):
# for min_samples_split in range(2,10):
# clf = RandomForestClassifier(n_estimators=n_estimator,
# max_features=max_feature,
# max_depth=None,
# min_samples_split=min_samples_split,
# random_state=0)
# clf.fit(self.trainX, self.trainY)
# print(max_feature,n_estimator,min_samples_split,clf.score(self.testX, self.testY))
clf = RandomForestClassifier(
n_estimators=10,
max_depth=None,
min_samples_split=2,
random_state=0)
clf.fit(self.trainX, self.trainY)
score = clf.score(self.testX, self.testY)
with open('data/' + dataFile + '.rf.pkl', 'wb') as fid:
pickle.dump([clf, self.nameX, self.nameY], fid)
return score
def classify(self, groupName, fingerpintFile):
with open('data/' + groupName + '.rf.pkl', 'rb') as pickle_file:
[clf, self.nameX, self.nameY] = pickle.load(pickle_file)
# As before, we need a row that defines the macs
newRow = numpy.zeros(len(self.nameX))
data = {}
with open(fingerpintFile, 'r') as f_in:
for line in f_in:
data = json.loads(line)
if len(data) == 0:
return
for signal in data['wifi-fingerprint']:
# Only add the mac if it exists in the learning model
if signal['mac'] in self.nameX:
newRow[self.nameX.index(signal['mac'])] = signal['rssi']
prediction = clf.predict_proba(newRow.reshape(1, -1))
predictionJson = {}
for i in range(len(prediction[0])):
predictionJson[self.nameY[i]] = prediction[0][i]
return predictionJson
class EchoRequestHandler(socketserver.BaseRequestHandler):
def handle(self):
# Echo the back to the client
data = self.request.recv(1024)
data = data.decode('utf-8').strip()
print("received data:'%s'" % data)
group = data.split('=')[0].strip()
filename = data.split('=')[1].strip()
payload = "error".encode('utf-8')
if len(group) == 0:
self.request.send(payload)
return
randomF = RF()
if len(filename) == 0:
payload = json.dumps(randomF.learn(group, 0.9)).encode('utf-8')
else:
payload = json.dumps(
randomF.classify(
group,
filename +
".rftemp")).encode('utf-8')
self.request.send(payload)
return
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument(
"-p",
"--port",
type=int,
help="select the port to run on")
parser.add_argument("-g", "--group", type=str, help="select a group")
parser.add_argument(
"-f",
"--file",
type=str,
help="select a file with fingerprints")
parser.add_argument("-d", "--debug", help="debug mode")
args = parser.parse_args()
DEBUG = args.debug
if args.port is not None:
socketserver.TCPServer.allow_reuse_address = True
address = ('localhost', args.port) # let the kernel give us a port
server = socketserver.TCPServer(address, EchoRequestHandler)
ip, port = server.server_address # find out what port we were given
server.serve_forever()
elif args.file is not None and args.group is not None:
randomF = RF()
print(randomF.classify(args.group, args.file))
elif args.group is not None:
randomF = RF()
print(randomF.learn(args.group, 0.5))
else:
print("""Usage:
To just run as TCP server:
python3 rf.py --port 5009
To just learn:
python3 rf.py --group GROUP
To classify
python3 rf.py --group GROUP --file FILEWITHFINGERPRINTS
""")