-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGradientDescent.py
More file actions
479 lines (359 loc) · 12.9 KB
/
GradientDescent.py
File metadata and controls
479 lines (359 loc) · 12.9 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
__title__ = "HW1 Q6"
__author__ = "Wonkyung Kim(wk2294), Shreya Jain(sj2842), Yu Bai(yb2300)"
__date__ = "$Oct 8, 2017"
import sys
import numpy as np
import scipy.io as spio
import math
import random
import time
from collections import defaultdict
import matplotlib.pyplot as plt
np.set_printoptions(threshold=sys.maxint)
def one_hot_encode( label_list ):
"""
Get one-hot-encoding vectors from the label.
"""
encoded_list = []
for i in range( len( label_list ) ):
encoded_num = []
for j in range( 10 ):
if j == label_list[i,0]:
encoded_num.append( 1 )
else:
encoded_num.append( 0 )
encoded_list.append( encoded_num )
return np.matrix( encoded_list )
def op_func( theta, X, Y ):
"""
Get optimal function value.
"""
result = 0
for i in range( X.shape[0] ):
x_i = X[i]
y_i = Y[i]
theta_t = theta.transpose()
mat = -2 * np.dot( theta_t, x_i )
mat += np.multiply( x_i, x_i ) + np.multiply( theta, theta ).transpose()
mat *= 1/2.0
mat = np.dot( y_i, mat)
result += mat
return np.sum( result )
########################################################################
# Code which follows the exact same step as homework description #
# Too slow to calculate this large data #
# op_func() is the Matrix/vectorized version of this #
########################################################################
def op_func2( theta, X, Y ):
result = 0
for i in range( X.shape[0] ):
for k in range( Y.shape[1] ):
for d in range( X.shape[1] ):
cal = 0.5 * Y[i, k] * ( ( X[i, d] - theta[0, k] ) ** 2 )
result += cal
return result
# Question (i)
def get_grad_f( theta, X, Y ):
"""
Get gradient f value.
"""
result = []
for k in range( label.shape[1] ):
y_k = Y[:, k]
theta_k = theta[0, k]
cal = y_k.transpose()
cal = np.dot( cal, ( -1 * X ) + theta_k )
cal = np.sum( cal )
result.append( cal )
result = np.matrix( result )
return result
########################################################################
# Code of the gradient value #
# Too slow to calculate this large data #
# get_grad_f() is the Matrix/vectorized version of this #
########################################################################
def get_grad_f2( theta, X, Y ):
"""
Get gradient f value.
"""
result = []
for k in range( label.shape[1] ):
sum = 0
for i in range( X.shape[0] ):
for d in range( X.shape[1] ):
cal = Y[i, k] * ( -1 * X[i, d] + theta[0,k] )
sum += cal
print sum
result.append( sum )
result = np.matrix( result )
return result
# Question (iii)
def get_grad_f_i( theta, X, Y, i ):
"""
Get gradient f_i value for i-1th data
"""
result = []
for k in range( label.shape[1] ):
y_k = Y[i, k]
theta_k = theta[0, k]
cal = y_k.transpose()
cal = np.dot( cal, ( -1 * X[i,:] ) + theta_k )
cal = np.sum( cal )
result.append( cal )
result = np.matrix( result )
return result
def get_all_grad_f_i( theta, X, Y ):
"""
Get all grad_f_i and store into a liast
Output the list
"""
num_of_data = X.shape[0]
grads = [] # Matrix of all grad_f_i
for i in range( num_of_data ):
grad_f_i = get_grad_f_i( theta, X, Y, i )
grads.append( grad_f_i )
return grads
# Question (ii)
def get_op_theta( theta, X, Y ):
"""
Get optimazed theta which minimizes the function f
Output optimized theta value,
the list of time wall: x-axis,
and the list of the value: y-axis
"""
# Get difference of uclidean distance
def get_difference( old_theta, new_theta ):
difference_mat = old_theta - new_theta
difference_square = np.multiply( difference_mat, difference_mat )
difference = math.sqrt( np.sum( difference_square ) )
return difference
# Get updated theta
def get_new_theta( old_theta, eta ):
grad_val = get_grad_f( old_theta, X, Y )
new_theta = old_theta - ( eta * grad_val )
return new_theta
############################################################
precision = 0.01 #
eta = 0.000000008 #
time_list = [] #
value_list = [] #
############################################################
old_theta = theta
new_theta = get_new_theta( old_theta, eta )
difference = get_difference( old_theta, new_theta )
while difference > precision:
old_theta = new_theta
new_theta = get_new_theta( old_theta, eta )
# Get new difference
difference = get_difference( old_theta, new_theta )
# Update time_list and value_list to make a plot
cur_time = time.clock()
time_list.append( cur_time )
value = op_func( new_theta, X, Y )
value_list.append( value )
# Showing Information...
print
print "difference: " + str( difference )
print "theta: "
print new_theta
print "function value: " + str( value )
return new_theta, time_list, value_list
# Question (iv)
def get_op_theta_fast( theta, X, Y ):
"""
Get optimazed theta which minimizes the function f
Output optimized theta value,
the list of time wall: x-axis,
and the list of the value: y-axis
"""
# Get difference of uclidean distance
def get_difference( old_theta, new_theta ):
difference_mat = old_theta - new_theta
difference_square = np.multiply( difference_mat, difference_mat )
difference = math.sqrt( np.sum( difference_square ) )
return difference
# Mini_batch example!!
def get_mini_batch_grad( theta ):
random.seed( 1000 )
grad_sum = None
size = 256
for i in range( size ):
random.seed()
rand_num = random.randint( 0, X.shape[0] - 1 )
grad = get_grad_f_i( theta, X, Y, rand_num )
if grad_sum == None:
grad_sum = grad
else:
grad_sum = grad_sum + grad
return grad_sum / size
# Set random seed
random.seed( 1 )
# Get updated theta
def get_new_theta( old_theta, eta ):
# Code for using single sample gradient
random_i = random.randint( 0, X.shape[0] - 1 )
grad_val = get_grad_f_i( old_theta, X, Y, random_i )
# Scale by the size N (multiply by 10,000)
grad_val = grad_val * X.shape[0]
new_theta = old_theta - ( eta * grad_val )
'''Code for Using Mini-batch'''
#grad_val = get_mini_batch_grad( old_theta )
#grad_val = grad_val * X.shape[0]
#new_theta = old_theta - ( eta * grad_val )
return new_theta
############################################################
precision = 0.01 #
eta = 0.000000008 #
time_list = [] #
value_list = [] #
############################################################
old_theta = theta
new_theta = get_new_theta( old_theta, eta )
difference = get_difference( old_theta, new_theta )
while difference > precision:
old_theta = new_theta
new_theta = get_new_theta( old_theta, eta )
# Get new difference
difference = get_difference( old_theta, new_theta )
# Update time_list and value_list to make a plot
cur_time = time.clock()
time_list.append( cur_time )
value = op_func( new_theta, X, Y )
value_list.append( value )
# Showing Information...
print
print "difference: " + str( difference )
print "theta: "
print new_theta
print "function value: " + str( value )
#return new_theta, grad_val_observe, time_list, value_list
return new_theta, time_list, value_list
# Question (v)
def get_all_gradients_for_Q4( theta, X, Y ):
"""
Do the same thing as Q(iv) but it is actually only for storing and
observing the sample gradient and whole gradient for the Q(iv) step
Output the sample grdient and whole grdient data
"""
# Get difference of uclidean distance
def get_difference( old_theta, new_theta ):
difference_mat = old_theta - new_theta
difference_square = np.multiply( difference_mat, difference_mat )
difference = math.sqrt( np.sum( difference_square ) )
return difference
# Contains all gradient_i
grad_i_val_observe = []
grad_val_observe = []
# Set random seed
random.seed( 1 )
# Get updated theta
def get_new_theta( old_theta, eta ):
# Code for using single sample gradient
random_i = random.randint( 0, X.shape[0] - 1 )
grad_i_val = get_grad_f_i( old_theta, X, Y, random_i )
# Get the whole gradient to observe
grad_val = get_grad_f( old_theta, X, Y )
# Scale by the size N (multiply by 10,000)
grad_i_val = grad_i_val * X.shape[0]
# Store grad_val to observe Q(v)
grad_i_val_list = grad_i_val.tolist()
grad_i_val_list = grad_i_val_list[0]
grad_val_list = grad_val.tolist()
grad_val_list = grad_val_list[0]
grad_i_val_observe.append( grad_i_val_list )
grad_val_observe.append( grad_val_list )
new_theta = old_theta - ( eta * grad_i_val )
return new_theta
############################################################
precision = 0.01 #
eta = 0.000000008 #
############################################################
old_theta = theta
new_theta = get_new_theta( old_theta, eta )
difference = get_difference( old_theta, new_theta )
while difference > precision:
old_theta = new_theta
new_theta = get_new_theta( old_theta, eta )
# Get new difference
difference = get_difference( old_theta, new_theta )
value = op_func( new_theta, X, Y )
# Showing information...
print
print "difference: " + str( difference )
print "theta: "
print new_theta
print "function value: " + str( value )
return grad_i_val_observe, grad_val_observe
if __name__ == "__main__":
mat = spio.loadmat( "hw1data.mat" )
data = np.matrix( mat["X"] )
label = mat["Y"]
label = one_hot_encode( label )
# arbitrary starting theta
theta = np.matrix( [1, 1, 1, 1, 1, 1, 1, 1, 1, 1] )
# Make sure double precision
data = data.astype( float )
label = label.astype( float )
theta = theta.astype( float )
# Code for Q2
'''
op, time, value = get_op_theta( theta, data, label )
print op
print "time"
print time
print "value"
print value
print
plt.plot( time, value )
plt.title("Q2" )
plt.xlabel( 'Time' )
plt.ylabel( 'Value' )
plt.show()
'''
# Result of Q2
#difference: 0.00994694761547
#theta:
#[[ 44.57708335 19.8437914 37.72223372 36.06837667 30.94106278
# 31.78815657 34.71347163 29.14377477 37.74894346 31.4059688 ]]
#function value: 24298968782.1
# Code for Q4
'''
op_theta, time, value = get_op_theta_fast( theta, data, label )
print
print "time"
print time
print
print "value"
print value
plt.plot( time, value )
plt.title("Q6" )
plt.xlabel( 'Time' )
plt.ylabel( 'Value' )
plt.show()
'''
# Result of Q4
# difference: 0.00836123518975
# theta:
# [[ 44.27442517 18.92473978 34.2421971 35.53165227 29.22544425
# 29.75770379 35.12970592 30.83726659 34.03855463 30.05652166]]
# function value: 24318995689.0
# Code for Q5
'''
# Making 10 histograms for gradient and sample gradients data
grad_i, grad = get_all_gradients_for_Q4( theta, data, label )
# For each k, make the histogram
for k in range( len( grad[0] ) ):
grad_i_k = []
grad_k = []
for list in grad_i:
grad_i_k.append( list[k] )
for list in grad:
grad_k.append( list[k] )
plt.hist( grad_i_k, label='sampe gradients k' )
plt.hist( grad_k, label='gradient k' )
plt.title( "k = " + str(k) )
plt.xlabel( 'Value' )
plt.ylabel( 'Frequent' )
plt.legend( loc='upper right' )
plt.show()
'''