-
Notifications
You must be signed in to change notification settings - Fork 1
/
svm.py
407 lines (244 loc) · 7.92 KB
/
svm.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
# coding: utf-8
# In[1]:
# Philip Tenteromano
# Machine Learning
# CISC 5800
# Dr. Daniel Leeds
# 2/24/2019
# In[2]:
import scipy.io as sio
import numpy as np
import pandas as pd
# In[3]:
loadedData = sio.loadmat('hw2data.mat')
# for keys in loadedData:
# print(keys)
# In[4]:
# store into respective variables
data1 = loadedData['data']
# data below goes together
data3 = loadedData['data3']
suppVects = loadedData['suppVec3']
alphas = loadedData['alphas3'].reshape(-1,)
# scalar values
b3 = loadedData['B3'][0][0]
eps = loadedData['eps'][0][0]
# In[5]:
# Helper functions for Vector calculations
# begin with a single '_' underscore
# In[6]:
# compute dot prod if vector size is the same
def _dotProduct(a,b):
if len(a) != len(b):
return "Shapes mismatch"
dotprod = 0
for i in range(len(a)):
dotprod += a[i] * b[i]
return dotprod
# In[7]:
# absolute values for an entire vector
def _absVect(vect):
return np.array([abs(x) for x in vect])
# In[8]:
# magnitude for vector
def _magnitudeVect(vect):
squares = 0
for i in vect:
squares += i ** 2
return np.sqrt(squares)
# In[9]:
# Question 1
# using an absolute value kernel to create separable data
# Classifying with the formula 'sign = b + summation(alphai, yi, kernel(dataPt,vi))'
# returns the predicted label based on the separating hyperplane
def kernelClassify(dataPt, suppVecs, alphas, b):
sign = b
# go through each support vector, store each (feature_vector, y, alpha)
for idx, sv in enumerate(suppVecs):
sv_Features = sv[:-1]
sv_Yi = sv[-1]
alph = alphas[idx]
# map function - absolute values of dataPt vector, feature vector
xi = _absVect(dataPt)
u = _absVect(sv_Features)
# kernel is just the dot product of the mapping
kernel = _dotProduct(xi ,u)
# find out what side of the hyperplane the dataPt is on
sign += (alph * sv_Yi * kernel)
if sign >= 1:
return 1
elif sign <= -1:
return -1
else:
return 0
# In[10]:
# testing on a single data point
kernelClassify(data3[2][:-1],suppVects, alphas, b3)
# In[11]:
# Question 2
# test the data points accurancy
def testKernelClassify(dataSet, suppVecs, alphas, b, trueLabels):
correct = 0
numPts = len(dataSet)
for idx, dataPt in enumerate(dataSet):
predict = kernelClassify(dataPt, suppVecs, alphas, b)
if predict == trueLabels[idx]:
correct += 1
return correct / numPts
# In[12]:
# store data for use in 2a and 2b below
# separate data3 into xi's and labels (part a)
testData = data3[:,:-1]
labels = data3[:,-1]
# same for support Vectors (part b)
suppVec_xVal = suppVects[:,:-1]
suppVec_labels = suppVects[:,-1]
# In[13]:
# Question 2 PART A
# Testing data3
accuracy = testKernelClassify(testData, suppVects, alphas, b3, labels)
percent = round(accuracy * 100, 2)
print("Question 2a:")
print("Data3 produces a {}% classification accuracy with kernelClassify".format(percent))
# In[14]:
# Question 2 PART B
# Testing on SuppVects
accuracy = testKernelClassify(suppVec_xVal, suppVects, alphas, b3, suppVec_labels)
percent = round(accuracy * 100, 2)
print("Question 2b:")
print("Support Vectors produces a {}% classification accuracy with kernelClassify".format(percent))
# In[15]:
# Question 3
# Using 'data1'
# In[16]:
# gradient Descent helper function
# the derivative of the SVM optimization function:
# minimizing the w[j] value of the hyperplane
def _gradientDescent(xI_j, wj, lamb, label):
result = 2 * wj
if label == 1:
lamb *= -1
result += lamb * xI_j
return result
# In[17]:
# learning W hyperplane through gradient descent
# accepts data and number of iterations as arguments
def learnW(dataTrain, iters):
# constant lambda and epsilon values
lambConst = 0.1
eps = 0.001
# init an empty w of 0's
w = np.zeros(7)
# iterate arbitrary number of times (given by iters)
for d in range(iters):
# go through every data point
for i in range(len(dataTrain)):
dataPt = dataTrain[i]
# store dataPt as features vector, with 1 appended to end
x_i = dataPt[:-1]
x_i = np.append(x_i, 1)
# grab label as separate variable
x_label = dataPt[-1]
# gradient Descent towards the best w, updating over every feature
for j in range(len(x_i)):
w[j] -= eps * _gradientDescent(x_i[j], w[j], lambConst, x_label)
return w
# In[18]:
# some test runs with varying iter
w_500 = learnW(data1, 500)
w_100 = learnW(data1, 100)
w_50 = learnW(data1, 50)
w_5 = learnW(data1, 5)
w_1 = learnW(data1, 1)
# In[19]:
# testing convergence
print(w_500 == w_100)
# In[20]:
# store values to test learnW()
w = w_500[:-1]
b = w_500[-1]
# In[46]:
# Q3 testing
# Testing learnW accuracy on data1
correct = 0
for i in data1:
x = i[:-1]
label = i[-1]
result = _dotProduct(x,w) + b
if result < 0 and label == -1:
correct += 1
elif result > 0 and label == 1:
correct += 1
accuracy = round(correct/len(data1) * 100, 2)
print("learnW() accuracy on data1 after 500 iterations: {} %".format(accuracy))
# In[22]:
# Question 4
# using 'data1'
# In[23]:
# gradient Ascent helper function
# the derivative of the SVM optimization function with respect to lambda:
# either [1 - (w^Tx + b)] or [1 + w^Tx + b]
def _gradientAscent(x, w, b, label):
dot = _dotProduct(w,x) + b
if label == 1:
return 1 - dot
else:
return 1 + dot
# In[24]:
# now learning both w and best lambda for each datapoint
# wInit is the initial w Vector: shape (1,7)
# lamInit is the initial lambda values: shape (n,1)
# also accepts data and number of iterations
def learnWlam(dataTrain, wInit, lamInit, iters):
# constant epsilon value, copy of lambda vector and w vector
eps = 0.001
lamVect = lamInit
w = wInit
# loop over dataset, iters number of times
for d in range(iters):
# go through every data point
for i in range(len(dataTrain)):
dataPt = dataTrain[i]
# store dataPt as features vector, with 1 appended to end
x_i = dataPt[:-1]
x_i = np.append(x_i, 1)
# grab label as separate variable
x_label = dataPt[-1]
# gradient descent on the best w value
for j in range(len(x_i)):
w[j] -= eps * _gradientDescent(x_i[j], w[j], lamVect[i], x_label)
# gradient ascent on the best lambda value for respective dataPt
lamVect[i] += eps * _gradientAscent(x_i[:-1], w[:-1], w[-1], x_label)
# lambda must be non-negative
if lamVect[i] < 0:
lamVect[i] = 0
return {'wFin': w, 'lambdaFin': lamVect}
# In[26]:
# Question 5
# Testing learnWlam() after 5000 iterations
# In[30]:
# CAUTION: THIS CELL TAKES A LONG TIME
# init a zero vector for w
w_Q4 = np.zeros(7)
# init lambdas to 0.01
lambdas_Q4 = np.full((len(data1), 1), 0.01)
# get the dictionary for 5000 iterations
wLamDict_5000 = learnWlam(data1, w_Q4, lambdas_Q4, 5000)
# In[43]:
print("W vector for 5000 iterations: ", wLamDict_5000['wFin'][:-1])
print("B value for 5000 iterations: ", wLamDict_5000['wFin'][-1])
# In[47]:
correct = 0
w_testQ5 = wLamDict_5000['wFin']
for dataPt in data1:
xi = dataPt[:-1]
xi = np.append(xi, 1)
yi = dataPt[-1]
# w^Tx + b
sign = _dotProduct(xi, w_testQ5)
if sign > 0 and yi == 1:
correct += 1
elif sign < 0 and yi == -1:
correct += 1
accuracy = round(correct/len(data1) * 100, 2)
print("Accuracy for learnWlam() with 5000 iters: {} %".format(accuracy))