forked from applied-ml-ucla/homework-1
-
Notifications
You must be signed in to change notification settings - Fork 0
/
ML_HW1.py
476 lines (334 loc) · 14.6 KB
/
ML_HW1.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
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
#!/usr/bin/env python
# coding: utf-8
# (a) loading data
# In[3]:
import matplotlib.pyplot as plt
import pandas as pd
import seaborn as sns
import numpy as np
from sklearn.metrics import confusion_matrix
from sklearn.neighbors import KNeighborsClassifier
from sklearn.metrics import accuracy_score
dt = pd.read_csv('C:/Users/simeon/Desktop/ML_HW1_data.csv')
dt=pd.DataFrame(dt)
print(dt.head())
# (b) pre processing Exploratory and data analysis
# i.
# In[5]:
print(sns.lmplot( x="pelvic_incidence", y="pelvic_tilt", data=dt, fit_reg=False, hue='class1', legend=True))
print(sns.lmplot( x="lumbar_lordosis", y="sacral_slope", data=dt, fit_reg=False, hue='class1', legend=True))
plt.ylim(-50,150)
print(sns.lmplot( x="pelvic_radius", y="spondyloisthesis", data=dt, fit_reg=False, hue='class1', legend=True))
plt.ylim(-50,150)
# ii.
# In[7]:
fig, ax = plt.subplots(2,1)
sns.boxplot(x="class1", y="pelvic_incidence", data=dt, order=["Normal", "Abnormal"],ax=ax[0])
sns.boxplot(x="class1", y="pelvic_tilt", data=dt, order=["Normal", "Abnormal"],ax=ax[1])
plt.show
fig, ax = plt.subplots(2,1)
sns.boxplot(x="class1", y="lumbar_lordosis", data=dt, order=["Normal", "Abnormal"],ax=ax[0])
sns.boxplot(x="class1", y="sacral_slope", data=dt, order=["Normal", "Abnormal"],ax=ax[1])
plt.show
fig, ax = plt.subplots(2,1)
sns.boxplot(x="class1", y="pelvic_radius", data=dt, order=["Normal", "Abnormal"],ax=ax[0])
sns.boxplot(x="class1", y="spondyloisthesis", data=dt, order=["Normal", "Abnormal"],ax=ax[1])
plt.show
# iii. creating training and testing sets
# In[8]:
a = dt[dt.class1 =="Normal"]
a = np.array(a)
tr_no = a[0:70,]
a = dt[dt.class1 =="Normal"]
a = np.array(a)
tst_no = a[70:310,]
a = dt[dt.class1 =="Abnormal"]
a = np.array(a)
tr_ab = a[0:140,]
a = dt[dt.class1 =="Abnormal"]
a = np.array(a)
tst_ab = a[140:310,]
train = np.concatenate([tr_no, tr_ab])
test = np.concatenate([tst_no, tst_ab])
#train = pd.DataFrame(train)
#train.columns = ['pelvic_incidence', 'pelvic_tilt', 'lumbar_lordosis', 'sacral_slope', 'pelvic_radius', 'spondyloisthesis', 'class1']
x_train = train[:,0:6]
y_train = train[:,6]
x_test = test[:,0:6]
y_test =test[:,6]
#######################
# (c) Classification using KNN on Vertebral Column Data Set
#
# i.& ii.
# In[12]:
train_error = list(range(208))
test_error = list(range(208))
for K in range(208):
K_value = K+1
neigh = KNeighborsClassifier(n_neighbors = K_value, weights='uniform', algorithm='auto', metric = 'euclidean')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
print( "error rate is ", 1-accuracy_score(y_test,y_pred_test),"% for K-Value:",K_value)
test_error[K] = 1- accuracy_score(y_test, y_pred_test)
for K in range(208):
K_value = K+1
neigh = KNeighborsClassifier(n_neighbors = K_value, weights='uniform', algorithm='auto', metric = 'euclidean')
neigh.fit(x_train, y_train)
y_pred_train = neigh.predict(x_train)
print( "error rate is ", 1- accuracy_score(y_train,y_pred_train),"% for K-Value:",K_value)
train_error[K] = 1- accuracy_score(y_train, y_pred_train)
K_value = range(208)
#plotting results
plt.ylim(0,.4)
plt.plot( K_value, train_error, marker='', markerfacecolor='blue', markersize=1, color='blue', linewidth=1)
plt.plot( K_value, test_error, marker='', color='green', linewidth=1)
plt.title('accuracy with various K values')
plt.xlabel("K value")
plt.ylabel('accuracy in %')
print(plt.legend())
# we can see that our highest accuracy and lowest error occurs at a k value of 3, with accuracy = 81% test and 84% train however the highest total accuracy i which we add the two values together
#happens when k=1 with accuracy = 74% test and 100% train, to test we will try both of these values for K
neigh = KNeighborsClassifier(n_neighbors = 3, weights='uniform', algorithm='auto', metric = 'euclidean')
neigh.fit(x_train, y_train)
labels = ['Abnormal', 'Normal']
y_pred_train = neigh.predict(x_train)
y_pred_test = neigh.predict(x_test)
print(confusion_matrix(y_train, y_pred_train, labels))
print(confusion_matrix(y_test, y_pred_test))
#both output identical confusion matrixes
#therefore we will say k = 3 is our k*
#true positive rate for train aka recall
print(59/(59+11))
#true positive rate for test aka recall
print(23/(23+7))
# true negative rate for train
print(11/(11+11))
# true negative rate for test
print(7/(7+1))
# precision for train
print(59/(59+11))
# precision for test
print(23/(23+1))
#F-score for train
print(2*((0.8428571428571429*.8428571428571429)/(0.8428571428571429+.8428571428571429)))
#F-score for test
print(2*((.9583333333333334*.7666666666666667)/(.9583333333333334+.7666666666666667)))
# we can see that our highest accuracy and lowest error occurs at a k value of 3, with accuracy = 92% test and 84% train and corresponding errors of 1-accuracy
#
# iii.
# In[14]:
N = list(range(10, 211, 10))
plot_error = []
for i in N:
tr_no1 = tr_no[0:round(i/3),:]
tr_ab1 = tr_ab[0:(i-round(i/3)),:]
train = np.concatenate([tr_no1, tr_ab1])
x_train = train[:,0:6]
y_train = train[:,6]
num =int( i/10)
test_error= []
for K in list(range(1, i,5)):
K_value = K
neigh = KNeighborsClassifier(n_neighbors = K_value, weights='uniform', algorithm='auto', metric = 'euclidean')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
( "error rate is ", 1-accuracy_score(y_test,y_pred_test),"% for K-Value:",K_value)
bwb = ( 1- accuracy_score(y_test, y_pred_test))
test_error.append(bwb)
minpos = test_error.index(min(test_error))
k_use = (minpos*5)+1
neigh = KNeighborsClassifier(n_neighbors = k_use, weights='uniform', algorithm='auto', metric = 'euclidean')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
bwb2 = ( 1- accuracy_score(y_test, y_pred_test))
plot_error.append(bwb2)
plt.plot( N, plot_error, marker='', markerfacecolor='blue', markersize=1, color='blue', linewidth=1)
plt.title('accuracy with various trainging sample sizes')
plt.xlabel("training sample size")
plt.ylabel('error')
# as we can see, the larger the training sample the better our model, with some exceptions occuring between a sample size of 30 and 100
# D. Replace the Euclidean metric with the following metrics
# and test them. Summarize the test errors
# In[19]:
test_error = []
for K in list(range(1, 196,5)):
K_value = K
neigh = KNeighborsClassifier(n_neighbors = K_value, weights='uniform', algorithm='auto', metric = 'minkowski')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
print( "error rate is ", 1-accuracy_score(y_test,y_pred_test),"% for K-Value:",K_value)
bwb = ( 1- accuracy_score(y_test, y_pred_test))
test_error.append(bwb)
minpos = int((test_error.index(min(test_error))))
k_use = (minpos*5)+1
neigh = KNeighborsClassifier(n_neighbors = k_use, weights='uniform', algorithm='auto', metric = 'minkowski')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
test_error_minowski = 1- accuracy_score(y_test, y_pred_test)
# Manhattan
test_error = []
for K in list(range(1, 196,5)):
K_value = K
neigh = KNeighborsClassifier(n_neighbors = K_value, weights='uniform', algorithm='auto', metric = 'manhattan')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
( "error rate is ", 1-accuracy_score(y_test,y_pred_test),"% for K-Value:",K_value)
bwb = ( 1- accuracy_score(y_test, y_pred_test))
test_error.append(bwb)
minpos = test_error.index(min(test_error))
k_use = (minpos*5)+1
neigh = KNeighborsClassifier(n_neighbors = k_use, weights='uniform', algorithm='auto', metric = 'manhattan')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
test_error_manhattan = 1- accuracy_score(y_test, y_pred_test)
#minoswki with various logbase(10) values
neigh = KNeighborsClassifier(n_neighbors = k_use, weights='uniform', algorithm='auto', metric = 'minkowski', p=1)
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
test_error = []
test_error_minowski_log = []
for i in np.linspace(.1,1,10):
print(i)
neigh = KNeighborsClassifier(n_neighbors = k_use, weights='uniform', algorithm='auto', metric = 'minkowski', p = 10**i)
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
test_error_minowski_log.append(1- accuracy_score(y_test, y_pred_test))
# the best log10 P is .1 or .3
# Chebyshev
test_error = []
for K in list(range(1, 196,5)):
K_value = K
neigh = KNeighborsClassifier(n_neighbors = K_value, weights='uniform', algorithm='auto', metric = 'chebyshev')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
( "error rate is ", 1-accuracy_score(y_test,y_pred_test),"% for K-Value:",K_value)
bwb = ( 1- accuracy_score(y_test, y_pred_test))
test_error.append(bwb)
minpos = test_error.index(min(test_error))
k_use = (minpos*5)+1
neigh = KNeighborsClassifier(n_neighbors = k_use, weights='uniform', algorithm='auto', metric = 'chebyshev')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
test_error_cheb = 1- accuracy_score(y_test, y_pred_test)
#mahalanobis
from sklearn.datasets import make_classification
from sklearn.neighbors import DistanceMetric
x = x_train
y = y_train
xt = x_train
yt = y_train
test_error = []
for K in list(range(1, 99,5)):
x, y = make_classification()
xt, yt = make_classification()
DistanceMetric.get_metric('mahalanobis', V=np.cov(x))
K_value = K
neigh = KNeighborsClassifier(n_neighbors =K,algorithm='brute', metric='mahalanobis', metric_params={'V': np.cov(x)})
neigh.fit(x,y)
y_pred_test = neigh.predict(xt)
last = []
for i in range(len(y)):
if y[i] != y_pred_test[i]:
last.append(i)
accuracy = len(last)/len(y_pred_test)
bwb = ( 1- accuracy)
test_error.append(bwb)
minpos = test_error.index(min(test_error))
k_use = (minpos*5)+1
#optimal k = 4
x = x_train
y = y_train
xt = x_train
yt = y_train
test_error = []
for K in list(range(1, 99,5)):
x, y = make_classification()
xt, yt = make_classification()
DistanceMetric.get_metric('mahalanobis', V=np.cov(x))
K_value = K
neigh = KNeighborsClassifier(n_neighbors =4,algorithm='brute', metric='mahalanobis', metric_params={'V': np.cov(x)})
neigh.fit(x,y)
y_pred_test = neigh.predict(xt)
last = []
for i in range(len(y)):
if y[i] != y_pred_test[i]:
last.append(i)
accuracy = len(last)/len(y_pred_test)
bwb = ( 1- accuracy)
test_error.append(bwb)
minpos = test_error.index(min(test_error))
k_use = (minpos*5)+1
plotable_y = [.099,.10999,.10999,.10999,.47 ]
plotable_x =[1,2,3,4,5]
plotable_x_lab = {'1 minowski','2 manhattan','3 log10 = .1','4 chebyshev','5 mahalanobis'}
plt.plot( plotable_x, plotable_y, marker='', markerfacecolor='blue', markersize=1, color='blue', linewidth=1)
plt.title('accuracy with various metrics')
plt.xlabel("metric")
plt.ylabel('error')
print('1 minowski','2 manhattan','3 log10 = .1','4 chebyshev','5 mahalanobis')
# the best errors that were achieved occured with our various types was with the minowki type in which we achieved an error of .0999
# e)
# The majority polling decision can be replaced by weighted decision, in which the
# weight of each point in voting is
# inversely proportional
# to its distance from the
# query/test data point. In this case, closer neighbors of a query point will have
# a greater influence than neighbors which are further away. Use weighted voting
# with Euclidean, Manhattan, and Chebyshev distances and report the best test
# errors
# In[21]:
test_error = []
for K in list(range(1, 196,5)):
K_value = K
neigh = KNeighborsClassifier(n_neighbors = K_value, weights='distance', algorithm='auto', metric = 'euclidean')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
( "error rate is ", 1-accuracy_score(y_test,y_pred_test),"% for K-Value:",K_value)
bwb = ( 1- accuracy_score(y_test, y_pred_test))
test_error.append(bwb)
minpos = test_error.index(min(test_error))
k_use = (minpos*5)+1
neigh = KNeighborsClassifier(n_neighbors = k_use, weights='distance', algorithm='auto', metric = 'euclidean')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
test_error_euclidean = 1- accuracy_score(y_test, y_pred_test)
test_error = []
for K in list(range(1, 196,5)):
K_value = K
neigh = KNeighborsClassifier(n_neighbors = K_value, weights='distance', algorithm='auto', metric = 'manhattan')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
( "error rate is ", 1-accuracy_score(y_test,y_pred_test),"% for K-Value:",K_value)
bwb = ( 1- accuracy_score(y_test, y_pred_test))
test_error.append(bwb)
minpos = test_error.index(min(test_error))
k_use = (minpos*5)+1
neigh = KNeighborsClassifier(n_neighbors = k_use, weights='distance', algorithm='auto', metric = 'manhattan')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
test_error_manhattan = 1- accuracy_score(y_test, y_pred_test)
test_error = []
for K in list(range(1, 196,5)):
K_value = K
neigh = KNeighborsClassifier(n_neighbors = K_value, weights='distance', algorithm='auto', metric = 'chebyshev')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
( "error rate is ", 1-accuracy_score(y_test,y_pred_test),"% for K-Value:",K_value)
bwb = ( 1- accuracy_score(y_test, y_pred_test))
test_error.append(bwb)
minpos = test_error.index(min(test_error))
k_use = (minpos*5)+1
neigh = KNeighborsClassifier(n_neighbors = k_use, weights='distance', algorithm='auto', metric = 'chebyshev')
neigh.fit(x_train, y_train)
y_pred_test = neigh.predict(x_test)
test_error_cheb = 1- accuracy_score(y_test, y_pred_test)
print(test_error_euclidean)
print(test_error_manhattan)
print(test_error_cheb)
# we can see that these weights did improve the accuracy of the manhattan type but the others remained the same
#
# (f)
# What is the lowest training error rate you achieved in this homework?
# the lowest test error rate that i got was with a euclidean type and a k value of 3 and uniform weights 0.07999999999999996.
# the lowest train error rate that i got was zero, this occured with the same parameters but with a k value of 1
# In[ ]: