-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathML2021S_HW5.py
More file actions
executable file
·568 lines (388 loc) · 65.1 KB
/
ML2021S_HW5.py
File metadata and controls
executable file
·568 lines (388 loc) · 65.1 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
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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
#!/usr/bin/env python
# coding: utf-8
# # CE-40717: Machine Learning
# ## HW5-Support Vector Machine
# ### Please fill this part
#
#
# 1. Full Name: AmirPourmand
# 2. Student Number: 99210259
#
#
# *You are just allowded to change those parts that start with "TO DO". Please do not change other parts.*
#
# *It is highly recommended to read each codeline carefully and try to understand what it exactly does. Best of luck and have fun!*
# In[2]:
# You are not allowed to import other packages.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.svm import SVC
import cvxopt
# #### About the Data:
# Heart diseases, also known as [Cardiovascular diseases (CVDs)](https://en.wikipedia.org/wiki/Cardiovascular_disease), are the first cause of death worldwide, taking an estimated 17.9 million lives each year which is about 32% of all deaths all over the world.
#
# In the present HomeWork, we are going to implement Support Vector Machines (SVM) algorithm that determines which patient is in danger and which is not.
#
# For this perpose, `Heart_Disease_Dataset.csv` file can be used that is attached to the HomeWork folder. Use `Dataset_Description.pdf` for more detail.
#
# In[3]:
df = pd.read_csv("./Heart_Disease_Dataset.csv")
df
# ### Pre-Processing - (15pts)
# #### Exploratory Data Analysis (EDA):
# In statistics, exploratory data analysis is an approach to analyze datasets to summarize their main characteristics, often using statistical graphics and other data visualization methods.
#
# This is a general approach that should be applied when you encounter a dataset.
# In[4]:
###############################################################################
## TODO: Find the shape of the dataset. ##
###############################################################################
shape = df.shape
print("shape of dataset is: " , shape)
###############################################################################
## TODO: Check if there is missing entries in the dataset columnwise. ##
###############################################################################
missings = df.info()
print("this dataset doesn't have any missing value as shown above.")
###############################################################################
## TODO: Check whether the dataset is balanced or not. ##
## If the difference between 2 classes was less than 100 for our dataset, ##
## it is called "ballanced". ##
###############################################################################
values=df.target.value_counts()
print("ballanced: ",np.abs(values[0]-values[1])<100)
###############################################################################
## TODO: plot the age distirbution and gender distrbution for both normal ##
## and heart diseses patients.(4 plots) ##
###############################################################################
print("--------------------- Plots --------------------------")
plt.figure(figsize=(10,10))
plt.subplot(2,2,1)
plt.hist(df[df.target==0].age,bins=100)
plt.title('Age distribution for Normal People')
plt.subplot(2,2,2)
plt.hist(df[df.target==0].sex)
plt.title('Gender distribution for Normal People')
plt.subplot(2,2,3)
plt.hist(df[df.target==1].age,bins=100)
plt.title('Age distribution for Ill People')
plt.subplot(2,2,4)
plt.hist(df[df.target==1].sex)
plt.title('Gender distribution for Ill People')
# #### Question 1: What do you conclude from the plots?
# #### Answer:
# #### I simply get the idea that ill people's age follows (roughly) from normal distribution. Also, the percentage of men who have heart attack is far higher than woman which means men should be more careful :)
# #### Outlier Detection & Removal:
# We will filter ouliers using Z-test.
# 
# Z-test formula:
# \begin{equation*}
# Z = \bigg|\frac {x - mu} {std}\bigg|
# \end{equation*}
# In[5]:
################################################################################
## TODO: Suppose that, based on our prior knowledge, we know some columns have##
## outliers. Calculate z-score for each featuer and determine the outliers ##
## with threshold=3, then eliminate them. Target dataframe has(1173,12)shape. ##
################################################################################
columns = ["age","resting bp s","cholesterol","max heart rate"]
threshold = 3
count = df.shape[0]
for col in columns:
z_test_age = (df[col]-df[col].mean())/df[col].std()
df=df[np.abs(z_test_age)<threshold]
df
################################################################################
# END OF YOUR CODE #
################################################################################
# #### Feature Engineering:
# Sometimes the collected data are raw; they are either incompatible with your model or hinders its performance. That’s when feature engineering comes to rescue. It encompasses preprocessing techniques to compile a dataset by extracting features from raw data.
#
# In[6]:
################################################################################
## TODO: Normalize numerical features to be between 0 and 1 ##
## Note that just numerical fetures should be normalized. type of features is ##
## determined in dataset description file. ##
################################################################################
def min_max_scaler(feature):
return (feature-feature.min())/(feature.max()-feature.min())
numberical_columns = ['age','resting bp s','cholesterol','max heart rate','oldpeak']
for col in numberical_columns:
df[col] = min_max_scaler(df[col])
df
################################################################################
# END OF YOUR CODE #
################################################################################
# ### SVM - (25pts)
# #### spliting data
# In[7]:
# The original dataset labels is 0 and 1 and in the following code we change it to -1 and 1.
df.target.replace(0 , -1 , inplace = True)
# Turn pandas dataframe to numpy array type
df = df.to_numpy()
# Splitting data into train and test part. 70% for train and 30% for test
train = df[:int(len(df) * 0.7)]
test = df[int(len(df) * 0.7):]
# Getting features
X_train = train[: , :-1]
y_train = train[: , -1]
# Getting labels
X_test = test[: , :-1]
y_test = test[: , -1]
# shapes should be:
# Train: (821, 11) (821,)
# Test: (352, 11) (352,)
print("Train: ", X_train.shape ,y_train.shape)
print("Test: " ,X_test.shape ,y_test.shape)
# #### SVM Using sklearn:
# Use the standard libarary SVM classifier (SVC) on the training data, and then test the classifier on the test data. You will need to call SVM with 3 kernels: (1) Linear, (2) Polynomial and (3) RBF. You can change C to achive better results. For "RBF" find "gamma" witch takes 90% accuracy, at least. For polynomial kernel you are allowed to change "degree" to find best results.
#
# For each kernel, reportting the followings is required:
# Accuracy, Precision, Recall, F1score.
# In[8]:
def classification_report(y_true, y_pred):
#################################################################################
## TODO: Define a function that returns the followings: ##
## Accuracy, Precision, Recall, F1score. ##
#################################################################################
True_Positive = np.sum((y_true==1)&(y_pred==1))
False_Positive = np.sum((y_true==-1)&(y_pred==1))
False_Negative = np.sum((y_true==1)&(y_pred==-1))
True_Negative = np.sum((y_true==-1)&(y_pred==-1))
Accuracy = np.mean(np.equal(y_true,y_pred))
Precision = True_Positive/(True_Positive+False_Positive)
Recall = True_Positive/(True_Positive+False_Negative)
F1score = 2*Precision*Recall/(Precision+Recall)
#################################################################################
# END OF YOUR CODE #
#################################################################################
return f'{Accuracy:.3f}', f'{Precision:.3f}', f'{Recall:.3f}', f'{F1score:.3f}'
# In[9]:
#########################################################################################
## TODO: Use svm of sklearn package (imported above) with 3 kernels. ##
## You should define model, fit using X_train, predict using X_test. ##
## your predictions known as y_pred. ##
## then use classification_report function to evaluate model. ##
#########################################################################################
linearClf=svm.SVC(kernel='linear',C=10)
linearClf.fit(X_train,y_train)
y_pred=linearClf.predict(X_test)
# linear kernel
print("results of sklearn svm linear kernel:", classification_report(y_test, y_pred))
polyClf=svm.SVC(kernel='poly',C=1,degree=2)
polyClf.fit(X_train,y_train)
y_pred=polyClf.predict(X_test)
# polynomial kernel
print("results of sklearn svm polynomial kernel:", classification_report(y_test, y_pred))
RBFClf=svm.SVC(kernel='rbf',C=50,gamma=20)
RBFClf.fit(X_train,y_train)
y_pred=RBFClf.predict(X_test)
# rbf kernel
print("results of sklearn svm RBF kernel:", classification_report(y_test, y_pred))
#########################################################################################
# END OF YOUR CODE #
#########################################################################################
# #### SVM:
# Now that you know how the standard library SVM works on the dataset, attempt to implement your own version of SVM. Implement SVM using Quadratic Programming(QP) approach. Remember that SVM objective fuction with QP is:
#
# \begin{equation*}
# min_{\alpha}\quad\frac{1}{2}\alpha^T\,Q\,\alpha-1^T\,\alpha\\
# s.t.\qquad y^T\,\alpha=0,\,\alpha\ge0
# \end{equation*}
#
# where:
# \begin{equation*}
# Q_{i,j}=y_i\,y_j\,\langle x_i\,,\,x_j\rangle
# \end{equation*}
#
# and:
# \begin{equation*}
# \text{if}\;(\alpha_n>0)\;\text{then}\;x_n\;\text{is a support vector}
# \end{equation*}
#
# For this perpose, complete the following code. You are allowed to use "cvxopt" package. It's an optimization package for Quadratic Programming. Below is the user's guide for the QP from CVXOPT:
#
# [Quadratic Programming](https://cvxopt.org/userguide/coneprog.html#quadratic-programming)
# In[17]:
# Hide cvxopt output
cvxopt.solvers.options["show_progress"] = False
#####################################################################################
## TODO: Use the information from the lecture slides to formulate the SVM ##
## kernels. These kernel functions will be called in the SVM class. ##
#####################################################################################
def linear_kernel(x,z,gamma=None,poly=None):
return np.dot(x,z)
def polynomial_kernel(x,z,gamma=None,polynomial=1):
return (1 + np.dot(x,z)) ** polynomial
def rbf_kernel(x,z,gamma,poly=None):
return np.exp(-gamma*np.linalg.norm(x-z)**2)
#####################################################################################
# END OF YOUR CODE #
#####################################################################################
class MySVM(object):
def __init__(self, kernel=linear_kernel, C=None,gamma=None,degree=None):
self.kernel = kernel
self.C = C
if self.C is not None: self.C = float(self.C)
self.gamma = gamma
self.degree = degree
def fit(self, X, y):
n_samples, n_features = X.shape
#####################################################################################
## TODO: Compute Gram matrix "K" for the given kernel. ##
#####################################################################################
K = np.zeros(shape=(n_samples,n_samples))
for i in np.arange(n_samples):
for j in np.arange(n_samples):
K[i,j] = self.kernel(X[i],X[j],self.gamma,self.degree)
#####################################################################################
# END OF YOUR CODE #
#####################################################################################
#####################################################################################
## TODO: Setup SVM objective function in QP form (Notation from attached link). ##
## Guidance: G and h have defferent definition if C is used or not. ##
#####################################################################################
P = cvxopt.matrix(y[:,None]*y[None,:]* K)
q = cvxopt.matrix(-1*np.ones(n_samples))
A = cvxopt.matrix(y, (1, n_samples))
b = cvxopt.matrix(0.0)
if self.C is None:
G = cvxopt.matrix(-1*np.identity(n_samples) )
h = cvxopt.matrix(np.zeros(n_samples))
else:
G = cvxopt.matrix(np.vstack((-1*np.identity(n_samples), np.identity(n_samples))))
h = cvxopt.matrix(np.hstack((np.zeros(n_samples), np.ones(n_samples) * self.C)))
#####################################################################################
# END OF YOUR CODE #
#####################################################################################
# solve QP problem
solution = cvxopt.solvers.qp(P, q, G, h, A, b)
# Lagrange multipliers
alpha = np.ravel(solution['x'])
# Support vectors have non zero lagrange multipliers
sv = alpha > 1e-5
#this will actually give the indices of the support vectors
ind = np.arange(len(alpha))[sv]
# get alphas of support vector , Xs and ys too.
self.alpha = alpha[sv]
self.sv = X[sv]
self.sv_y = y[sv]
#####################################################################################
## TODO: Compute the Intercept b and Weight vector w. ##
#####################################################################################
# Intercept
self.b = 0
diff = 0
for n in range(len(self.alpha)):
if self.C is not None and self.alphan[n] > self.C - 1e-5:
continue
diff =diff+ 1
self.b =self.b+ self.sv_y[n]
self.b =self.b- np.sum(self.alpha * self.sv_y * K[ind[n],sv])
if diff>0:
self.b=self.b/diff
else:
self.b = 0
# Weight vector
if self.kernel == linear_kernel:
self.w = np.zeros(n_features)
for n in range(len(self.alpha)):
self.w = self.w + self.alpha[n] * self.sv_y[n] * self.sv[n]
else:
self.w = None #Guidance: for non-linear case this should be None. (do not change)
#####################################################################################
# END OF YOUR CODE #
#####################################################################################
def predict(self, X):
if self.w is not None:
return np.dot(X, self.w) + self.b
else:
#####################################################################################
## TODO: For non-linear case, implement the kernel trick to predict the label. ##
#####################################################################################
y_predict = np.zeros(len(X))
for i in range(len(X)):
s = 0
for alpha, sv_y, sv in zip(self.alpha, self.sv_y, self.sv):
s += alpha * sv_y * self.kernel(X[i], sv,self.gamma,self.degree)
y_predict[i] = s
return y_predict + self.b
#####################################################################################
# END OF YOUR CODE #
#####################################################################################
# In[13]:
###################################################################################
## TODO: define 3 model same as previous part (SVM Using sklearn) and evaluate ##
## them. Note that for comaparing your result with that part for each kernel use ##
## same parameters in both parts. ##
###################################################################################
# linear kernel
linearSVM = MySVM(linear_kernel,C=10)
linearSVM.fit(X_train,y_train)
y_pred=np.sign(linearSVM.predict(X_test))
print("results of MySVM linear kernel:", classification_report(y_test , y_pred))
# polynomial kernel
#best degree for polynomial is 1!
polySVM=MySVM(polynomial_kernel,C=1,degree=2)
polySVM.fit(X_train,y_train)
y_pred=np.sign(polySVM.predict(X_test))
print("results of sklearn svm polynomial kernel:", classification_report(y_test, y_pred))
Rbf_SVM=MySVM(rbf_kernel,C=50,gamma=20)
Rbf_SVM.fit(X_train,y_train)
y_pred=np.sign(Rbf_SVM.predict(X_test))
# rbf kernel
print("results of sklearn svm RBF kernel:", classification_report(y_test, y_pred))
# #### Question 2: Report best results.
#
#
#
# 1. Best kernel:
# 2. Best Accuracy:
#
#
#
# #### Question 2: Report best results.
#
#
#
# 1. Best kernel: RBF Kernel
# 2. Best Accuracy: 93.18%
# ### Bonus Score - (5pts)
#
# In this step you can check other kernel functions or change parameters or any idea to get better result in compare with last section's results.
# In[14]:
df = pd.read_csv("./Heart_Disease_Dataset.csv")
columns = ["age","resting bp s","cholesterol","max heart rate"]
threshold = 3
count = df.shape[0]
for col in columns:
z_test_age = (df[col]-df[col].mean())/df[col].std()
df=df[np.abs(z_test_age)<threshold]
##here is my idea###
### we should scale all features. Not just numerical ones.
for col in df.columns:
df[col] = min_max_scaler(df[col])
df.target.replace(0 , -1 , inplace = True)
df = df.to_numpy()
train = df[:int(len(df) * 0.7)]
test = df[int(len(df) * 0.7):]
X_train = train[: , :-1]
y_train = train[: , -1]
X_test = test[: , :-1]
y_test = test[: , -1]
Rbf_SVM=MySVM(rbf_kernel,C=50,gamma=20)
Rbf_SVM.fit(X_train,y_train)
y_pred=np.sign(Rbf_SVM.predict(X_test))
print("results of sklearn svm RBF kernel:", classification_report(y_test, y_pred))
# #### My idea is simple: we should scale all features not just numerical ones.
# #### you can see the overall performance of F1_score which is the best one we have is increased 1% from 0.92 to 0.93 percent and accuracy went from 93.2 to 93.8
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]:
# In[ ]: