-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmachine_learning_models.py
403 lines (385 loc) · 27.7 KB
/
machine_learning_models.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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
import numpy as np
from sklearn.metrics import log_loss
from sklearn.neighbors import KNeighborsClassifier
import pylab as pl
import aux_functions
from sklearn import svm, metrics
from sklearn import neighbors
from sklearn.linear_model import Perceptron
from sklearn.linear_model import LogisticRegression
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier
from sklearn.naive_bayes import GaussianNB
from sklearn.cross_validation import KFold
from sklearn.grid_search import GridSearchCV
from sklearn.cross_validation import StratifiedShuffleSplit
#from sklearn.discriminant_analysis import LinearDiscriminantAnalysis
#from sklearn.discriminant_analysis import QuadraticDiscriminantAnalysis
def naive_bayes(train_data_features, train_data_split_crossfold_features, test_data_features, labels, labels_cross_validation_classwise, kf, settings):
gnb = GaussianNB()
model = gnb.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
def perc(train_data_features, train_data_split_crossfold_features, test_data_features, labels, labels_cross_validation_classwise, kf, settings):
prc = Perceptron()
model = prc.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
def log_res(train_data_features, train_data_cross_validation_classwise_features, test_data_features, labels, labels_cross_validation_classwise, using_cross_validation2, kf, settings):
if using_cross_validation2:
logres_C = 1
logres_results = []
if(len(train_data_cross_validation_classwise_features) > 0):
"""train_all = np.append(train_data_features, train_data_cross_validation_classwise_features, axis=0)
labels_all = np.append(labels, labels_cross_validation_classwise)
kf_all = KFold(len(train_all)-1, n_folds=int(settings['Data']['CrossValidation2']), shuffle=True)
for train, test in kf_all:
C = logres_C
p = 'l1'
clf_l1_LR = LogisticRegression(C=C, penalty=p, tol=0.01)
model = clf_l1_LR.fit(train_all[train], labels_all[train])
predicted_classes = model.predict(train_all[test])
predicted_classes_train = model.predict(train_all[train])
print("N points:", len(predicted_classes), " percentage: ",(labels_all[test] != predicted_classes).sum()*100/len(predicted_classes),"%, percentage_train: ", (labels_all[train] != predicted_classes_train).sum()*100/len(predicted_classes_train))
logres_results.append((labels_all[test] != predicted_classes).sum())
logres_C += 1"""
for c in pl.frange(logres_C,15, 1):
clf_l1_LR = LogisticRegression(C=c, solver='lbfgs', penalty='l2', tol=0.01)
model = clf_l1_LR.fit(train_data_features, labels)
predicted_classes = model.predict(train_data_cross_validation_classwise_features)
predicted_classes_train = model.predict(train_data_features)
class_probabilities = model.predict_proba(train_data_cross_validation_classwise_features)
logres_results.append(log_loss(labels_cross_validation_classwise, class_probabilities))
print("N points:", len(predicted_classes), " percentage: ",(labels_cross_validation_classwise != predicted_classes).sum()*100/len(predicted_classes),
"%, percentage_train: ", (labels != predicted_classes_train).sum()*100/len(predicted_classes_train))
print("Log_loss: ", log_loss(labels_cross_validation_classwise, class_probabilities))
else:
for train, test in kf:
C = logres_C
p = 'l1'
clf_l1_LR = LogisticRegression(C=C, penalty=p, tol=0.01)
model = clf_l1_LR.fit(train_data_features[train], labels[train])
predicted_classes = model.predict(train_data_features[test])
predicted_classes_train = model.predict(train_data_features[train])
print("N points:", len(predicted_classes), " percentage: ",(labels[test] != predicted_classes).sum()*100/len(predicted_classes),"%, percentage_train: ", (labels[train] != predicted_classes_train).sum()*100/len(predicted_classes_train))
logres_results.append((labels[test] != predicted_classes).sum())
logres_C += 1
print(logres_results)
logres_C = logres_results.index(min(logres_results)) + 1
print("Log Res C: ", logres_C)
if(len(train_data_cross_validation_classwise_features) > 0):
clf_l1_LR = LogisticRegression(C=logres_C, penalty='l2', tol=0.01)
model = clf_l1_LR.fit(train_data_features, labels)
predicted_classes = model.predict(train_data_cross_validation_classwise_features)
predicted_classes_train = model.predict(train_data_features)
class_probabilities = model.predict_proba(train_data_cross_validation_classwise_features)
print("N points:", len(predicted_classes), " percentage: ",(labels_cross_validation_classwise != predicted_classes).sum()*100/len(predicted_classes),"%, percentage_train: ", (labels != predicted_classes_train).sum()*100/len(predicted_classes_train))
print("Log_loss: ", log_loss(labels_cross_validation_classwise, class_probabilities))
clf_l1_LR = LogisticRegression(C=logres_C, penalty='l1', tol=0.01)
model = clf_l1_LR.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
else:
C = 1
p = 'l1'
clf_l1_LR = LogisticRegression(C=C, penalty=p, tol=0.01)
model = clf_l1_LR.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
def cross_test(train_data_features, train_data_split_crossfold_features, test_data_features, labels, labels_cross_validation_classwise, using_cross_validation2, kf, settings):
if using_cross_validation2:
_results = []
global_results = []
names = ["Nearest Neighbors", "Linear SVM", "RBF SVM", "Decision Tree",
"Random Forest", "AdaBoost", "Naive Bayes", "Linear Discriminant Analysis",
"Quadratic Discriminant Analysis"]
classifiers = [
KNeighborsClassifier(3),
SVC(kernel="linear", C=0.025, probability=True),
SVC(gamma=2, C=1, probability=True),
DecisionTreeClassifier(max_depth=5),
RandomForestClassifier(max_depth=5, n_estimators=10, max_features=1),
AdaBoostClassifier(),
GaussianNB(),
LinearDiscriminantAnalysis(),
QuadraticDiscriminantAnalysis()]
for name, clf in zip(names, classifiers):
for train, test in kf:
model = clf.fit(train_data_features[train], labels[train])
predicted_classes = model.predict(train_data_features[test])
class_probabilities = model.predict_proba(train_data_features[test])
print(name," n points:", len(predicted_classes), ", wrong: ", (labels[test] != predicted_classes).sum(), " percentage: ",(labels[test] != predicted_classes).sum()*100/len(predicted_classes),"%")
_results.append((labels[test] != predicted_classes).sum())
result = min(_results)
global_results.append((name,result))
print(global_results)
clf = AdaBoostClassifier()
model = clf.fit(train_data_features, labels)
predicted_classes = model.predict(test_data_features)
class_probabilities = model.predict_proba(test_data_features)
else:
clf = AdaBoostClassifier()
model = clf.fit(train_data_features, labels)
predicted_classes = model.predict(test_data_features)
class_probabilities = model.predict_proba(test_data_features)
def linear_svm(train_data_features, train_data_cross_validation_classwise_features, test_data_features, labels, labels_cross_validation_classwise, using_cross_validation2, kf, settings):
if using_cross_validation2:
C_base = 0.5
C_step = 0.5#0.005
C = C_base
_results = []
if(len(train_data_cross_validation_classwise_features) > 0):
"""train_all = np.append(train_data_features, train_data_cross_validation_classwise_features, axis=0)
labels_all = np.append(labels, labels_cross_validation_classwise)
kf_all = KFold(len(train_all)-1, n_folds=int(settings['Data']['CrossValidation2']), shuffle=True)
for train, test in kf_all:
svc = SVC(kernel="linear", C=C, probability=True)
model = svc.fit(train_all[train], labels_all[train])
predicted_classes = model.predict(train_all[test])
predicted_classes_train = model.predict(train_all[train])
class_probabilities = model.predict_proba(train_all[test])
print("C: ",C," n points:", len(predicted_classes), " percentage: ",(labels_all[test] != predicted_classes).sum()*100/len(predicted_classes),"% percentage_train: ", (labels_all[train] != predicted_classes_train).sum()*100/len(predicted_classes_train),"%")
_results.append((labels_all[test] != predicted_classes).sum())
C += C_step"""
for c in pl.frange(C_base,9, C_step):
svc = SVC(kernel="linear", C=c, probability=True)
model = svc.fit(train_data_features, labels)
predicted_classes = model.predict(train_data_cross_validation_classwise_features)
predicted_classes_train = model.predict(train_data_features)
class_probabilities = model.predict_proba(train_data_cross_validation_classwise_features)
print("C: ",c," N points:", len(predicted_classes), " percentage: ",(labels_cross_validation_classwise != predicted_classes).sum()*100/len(predicted_classes),"% percentage_train: ", (labels != predicted_classes_train).sum()*100/len(predicted_classes_train),"%")
print("Log_loss: ", log_loss(labels_cross_validation_classwise, class_probabilities))
_results.append(log_loss(labels_cross_validation_classwise, class_probabilities))
else:
for train, test in kf:
svc = SVC(kernel="linear", C=C, probability=True)
model = svc.fit(train_data_features[train], labels[train])
predicted_classes = model.predict(train_data_features[test])
predicted_classes_train = model.predict(train_data_features[train])
class_probabilities = model.predict_proba(train_data_features[test])
print("C: ",C," n points:", len(predicted_classes), " percentage: ",(labels[test] != predicted_classes).sum()*100/len(predicted_classes),"% percentage_train: ", (labels[train] != predicted_classes_train).sum()*100/len(predicted_classes_train),"%")
_results.append((labels[test] != predicted_classes).sum())
C += C_step
C = C_base + C_step * _results.index(min(_results))
print("C: ", C)
if(len(train_data_cross_validation_classwise_features) > 0):
svc = SVC(kernel="linear", C=C, probability=True)
model = svc.fit(train_data_features, labels)
predicted_classes = model.predict(train_data_cross_validation_classwise_features)
class_probabilities = model.predict_proba(train_data_cross_validation_classwise_features)
print("C: ",C," N points:", len(predicted_classes), " percentage: ",(labels_cross_validation_classwise != predicted_classes).sum()*100/len(predicted_classes),"%")
print("Log_loss: ", log_loss(labels_cross_validation_classwise, class_probabilities))
svc = SVC(kernel="linear", C=C, probability=True)
model = svc.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
else:
svc = SVC(kernel="linear", C=8, probability=True)
model = svc.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
def rbf_svm(train_data_features, train_data_cross_validation_classwise_features, test_data_features, labels, labels_cross_validation_classwise, using_cross_validation2, kf, settings):
if using_cross_validation2:
C_base = 1000
C_step = 1000#0.005
C = C_base
gamma_base = (1/(len(train_data_cross_validation_classwise_features)))/5
gamma_step = 1/(len(train_data_cross_validation_classwise_features))/10
gamma = gamma_base
_results = []
if(len(train_data_cross_validation_classwise_features) > 0):
train_all = np.append(train_data_features, train_data_cross_validation_classwise_features, axis=0)
labels_all = np.append(labels, labels_cross_validation_classwise)
kf_all = KFold(len(train_all)-1, n_folds=int(settings['Data']['CrossValidation2']), shuffle=True)
print(1/(len(train_data_cross_validation_classwise_features)))
#for c in pl.frange(gamma_base,1/(len(train_data_cross_validation_classwise_features)), gamma_step):
"""for c in pl.frange(C_base,10000, C_step):
svc = SVC(kernel="rbf", C=c, probability=True)
model = svc.fit(train_data_features, labels)
predicted_classes = model.predict(train_data_cross_validation_classwise_features)
predicted_classes_train = model.predict(train_data_features)
class_probabilities = model.predict_proba(train_data_cross_validation_classwise_features)
print("C: ",c," N points:", len(predicted_classes), " percentage: ",(labels_cross_validation_classwise != predicted_classes).sum()*100/len(predicted_classes),"% percentage_train: ", (labels != predicted_classes_train).sum()*100/len(predicted_classes_train),"%")
print("Log_loss: ", log_loss(labels_cross_validation_classwise, class_probabilities))
_results.append(log_loss(labels_cross_validation_classwise, class_probabilities))"""
"""for train, test in kf_all:
svc = SVC(kernel="rbf", C=C, gamma = gamma, probability=True)
model = svc.fit(train_all[train], labels_all[train])
predicted_classes = model.predict(train_all[test])
predicted_classes_train = model.predict(train_all[train])
class_probabilities = model.predict_proba(train_all[test])
print("C: ",C," n points:", len(predicted_classes), " percentage: ",(labels_all[test] != predicted_classes).sum()*100/len(predicted_classes),"% percentage_train: ", (labels_all[train] != predicted_classes_train).sum()*100/len(predicted_classes_train),"%")
_results.append((labels_all[test] != predicted_classes).sum())
C += C_step"""
else:
for train, test in kf:
svc = SVC(kernel="rbf", C=C, gamma = gamma)
model = svc.fit(train_data_features[train], labels[train])
predicted_classes = model.predict(train_data_features[test])
predicted_classes_train = model.predict(train_data_features[train])
print("C: ",C," n points:", len(predicted_classes), " percentage: ",(labels[test] != predicted_classes).sum()*100/len(predicted_classes),"% percentage_train: ", (labels[train] != predicted_classes_train).sum()*100/len(predicted_classes_train),"%")
_results.append((labels[test] != predicted_classes).sum())
C += C_step
#C = C_base + C_step * _results.index(min(_results))
C = 1000
print("C: ", C)
if(len(train_data_cross_validation_classwise_features) > 0):
svc = SVC(kernel="rbf", C=C, probability=True)
model = svc.fit(train_data_features, labels)
predicted_classes = model.predict(train_data_cross_validation_classwise_features)
class_probabilities = model.predict_proba(train_data_cross_validation_classwise_features)
print("C: ",C," N points:", len(predicted_classes), " percentage: ",(labels_cross_validation_classwise != predicted_classes).sum()*100/len(predicted_classes),"%")
print("Log_loss: ", log_loss(labels_cross_validation_classwise, class_probabilities))
svc = SVC(kernel="rbf", C=C, gamma = gamma, probability=True)
model = svc.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
else:
svc = SVC(kernel="rbf", C=8, gamma = 0.4, probability=True)
model = svc.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
def adaboost(train_data_features, train_data_split_crossfold_features, test_data_features, labels, labels_cross_validation_classwise, using_cross_validation2, kf, settings):
if using_cross_validation2:
_results = np.zeros(10)
base_n_estimators = 100 # week learners
step_n_estimators = 100
ada_results = []
n_estimators = base_n_estimators
lr = 1.48
for train, test in kf:
rf = RandomForestClassifier(max_depth=395, n_estimators=80, max_features=7).fit(train_data_features, labels)
clf = AdaBoostClassifier(algorithm='SAMME.R', base_estimator=rf, n_estimators = n_estimators, learning_rate = lr)
model = clf.fit(train_data_features[train], labels[train])
predicted_classes = model.predict(train_data_features[test])
class_probabilities = model.predict_proba(train_data_features[test])
print("ada week learners: ", n_estimators ,"learning rate ",lr," n points:", len(predicted_classes),
" percentage: ",(labels[test] != predicted_classes).sum()*100/len(predicted_classes),"%"," sum of errors: ", _results[0])
_results[0] += (labels[test] != predicted_classes).sum()
ada_results.append((labels[test] != predicted_classes).sum())
n_estimators += step_n_estimators
n_estimators = base_n_estimators + step_n_estimators * ada_results.index(min(ada_results))
print("optimized week learners ", n_estimators)
if(len(train_data_split_crossfold_features) > 0):
rf = RandomForestClassifier(max_depth=395, n_estimators=80, max_features=7).fit(train_data_features, labels)
clf = AdaBoostClassifier(base_estimator=rf, n_estimators = n_estimators, learning_rate = lr)
model = clf.fit(train_data_features, labels)
predicted_classes = model.predict(train_data_split_crossfold_features)
class_probabilities = model.predict_proba(train_data_split_crossfold_features)
print("N points:", len(predicted_classes), " percentage: ",(labels_cross_validation_classwise != predicted_classes).sum()*100/len(predicted_classes),"%")
print("Log_loss: ", log_loss(labels_cross_validation_classwise, class_probabilities))
#dt = DecisionTreeClassifier(max_depth=26).fit(train_data_features, labels)
rf = RandomForestClassifier(max_depth=395, n_estimators=80, max_features=7).fit(train_data_features, labels)
clf = AdaBoostClassifier(base_estimator=rf, n_estimators = n_estimators, learning_rate = lr)
model = clf.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
else:
clf_l1_LR = LogisticRegression(C=1, penalty='l1', tol=0.01)
lr = clf_l1_LR.fit(train_data_features, labels)
dt = DecisionTreeClassifier()
dt = dt.fit(train_data_features, labels)
clf = AdaBoostClassifier(
base_estimator=dt,
learning_rate=1,
n_estimators=250)
model = clf.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
def des_tree(train_data_features, train_data_split_crossfold_features, test_data_features, labels, labels_cross_validation_classwise, using_cross_validation2, kf, settings):
if using_cross_validation2:
_results = []
base_max_depth = 6
max_depth = base_max_depth
step_max_depth = 100
for train, test in kf:
clf = DecisionTreeClassifier(max_depth=max_depth)
model = clf.fit(train_data_features[train], labels[train])
predicted_classes = model.predict(train_data_features[test])
class_probabilities = model.predict_proba(train_data_features[test])
print("maxd ",max_depth," |n points:", len(predicted_classes), ", wrong: ", (labels[test] != predicted_classes).sum(), " percentage: ",(labels[test] != predicted_classes).sum()*100/len(predicted_classes),"%")
max_depth += step_max_depth
_results.append((labels[test] != predicted_classes).sum())
max_depth = 6 + step_max_depth * list(_results).index(min(_results))
print("opt max depth ",max_depth)
clf = DecisionTreeClassifier(max_depth = max_depth)
model = clf.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
else:
clf = DecisionTreeClassifier()
model = clf.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
def svm_model(train_data_features, train_data_split_crossfold_features, test_data_features, labels, labels_cross_validation_classwise, using_cross_validation2, kf, settings):
if using_cross_validation2:
C_base = 4.5
C_step = 0.5#0.005
C = C_base
_results = []
if(len(train_data_cross_validation_classwise_features) > 0):
"""train_all = np.append(train_data_features, train_data_cross_validation_classwise_features, axis=0)
labels_all = np.append(labels, labels_cross_validation_classwise)
kf_all = KFold(len(train_all)-1, n_folds=int(settings['Data']['CrossValidation2']), shuffle=True)
for train, test in kf_all:
svc = SVC(kernel="linear", C=C, probability=True)
model = svc.fit(train_all[train], labels_all[train])
predicted_classes = model.predict(train_all[test])
predicted_classes_train = model.predict(train_all[train])
class_probabilities = model.predict_proba(train_all[test])
print("C: ",C," n points:", len(predicted_classes), " percentage: ",(labels_all[test] != predicted_classes).sum()*100/len(predicted_classes),"% percentage_train: ", (labels_all[train] != predicted_classes_train).sum()*100/len(predicted_classes_train),"%")
_results.append((labels_all[test] != predicted_classes).sum())
C += C_step"""
for c in pl.frange(C_base,9, C_step):
svc = SVC(kernel="linear", C=c, probability=True)
model = svc.fit(train_data_features, labels)
predicted_classes = model.predict(train_data_cross_validation_classwise_features)
class_probabilities = model.predict_proba(train_data_cross_validation_classwise_features)
print("C: ",c," N points:", len(predicted_classes), " percentage: ",(labels_cross_validation_classwise != predicted_classes).sum()*100/len(predicted_classes),"%")
print("Log_loss: ", log_loss(labels_cross_validation_classwise, class_probabilities))
for c in pl.frange(1,3, 1):
svc = SVC(kernel="linear", C=c, probability=True)
model = svc.fit(train_data_features, labels)
predicted_classes = model.predict(train_data_cross_validation_classwise_features)
class_probabilities = model.predict_proba(train_data_cross_validation_classwise_features)
print("C: ",c," N points:", len(predicted_classes), " percentage: ",(labels_cross_validation_classwise != predicted_classes).sum()*100/len(predicted_classes),"%")
print("Log_loss: ", log_loss(labels_cross_validation_classwise, class_probabilities))
else:
for train, test in kf:
svc = SVC(kernel="linear", C=C, probability=True)
model = svc.fit(train_data_features[train], labels[train])
predicted_classes = model.predict(train_data_features[test])
predicted_classes_train = model.predict(train_data_features[train])
class_probabilities = model.predict_proba(train_data_features[test])
print("C: ",C," n points:", len(predicted_classes), " percentage: ",(labels[test] != predicted_classes).sum()*100/len(predicted_classes),"% percentage_train: ", (labels[train] != predicted_classes_train).sum()*100/len(predicted_classes_train),"%")
_results.append((labels[test] != predicted_classes).sum())
C += C_step
C = C_base + C_step * _results.index(min(_results))
print("C: ", C)
if(len(train_data_cross_validation_classwise_features) > 0):
svc = SVC(kernel="linear", C=C, probability=True)
model = svc.fit(train_data_features, labels)
predicted_classes = model.predict(train_data_cross_validation_classwise_features)
class_probabilities = model.predict_proba(train_data_cross_validation_classwise_features)
print("C: ",C," N points:", len(predicted_classes), " percentage: ",(labels_cross_validation_classwise != predicted_classes).sum()*100/len(predicted_classes),"%")
print("Log_loss: ", log_loss(labels_cross_validation_classwise, class_probabilities))
svc = SVC(kernel="linear", C=C, probability=True)
model = svc.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
else:
svc = SVC(kernel="linear", C=8, probability=True)
model = svc.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
def k_nearest_neighbors(train_data_features, train_data_split_crossfold_features, test_data_features, labels, labels_cross_validation_classwise, using_cross_validation2, kf, settings):
if using_cross_validation2:
k_neighbors_results = np.zeros(10)
#k_neighbors = 1
#k_neighbors_results = []
for train, test in kf:
for k_neighbors in range(2,10):
clf = neighbors.KNeighborsClassifier(k_neighbors)
model = clf.fit(train_data_features[train], labels[train])
predicted_classes = model.predict(train_data_features[test])
class_probabilities = model.predict_proba(train_data_features[test])
print("K result, i - ", k_neighbors, ", n points:", len(predicted_classes), ", wrong: ", (labels[test] != predicted_classes).sum(), " sum of errors: ", k_neighbors_results[k_neighbors], " percentage: ",(labels[test] != predicted_classes).sum()*100/len(predicted_classes),"%")
k_neighbors_results[k_neighbors] += (labels[test] != predicted_classes).sum()
k_neighbors = list(k_neighbors_results).index(min(k_neighbors_results)) + 2
print("k = ",k_neighbors)
clf = neighbors.KNeighborsClassifier(k_neighbors)
model = clf.fit(train_data_features, labels)
predicted_classes = model.predict(test_data_features)
return model.predict_proba(test_data_features), model.predict(test_data_features), model
else:
k_neighbors = 8
clf = neighbors.KNeighborsClassifier(k_neighbors)
model = clf.fit(train_data_features, labels)
return model.predict_proba(test_data_features), model.predict(test_data_features), model