-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgradient+descent.py
295 lines (150 loc) · 7.55 KB
/
gradient+descent.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
# coding: utf-8
# In[1]:
import numpy as np
from IPython.display import display, Math, Latex
## basic idea https://github.com/llSourcell/linear_regression_live/blob/master/demo.py
# In[68]:
points = np.genfromtxt("data.csv", delimiter=",")
points[0:2] ## first two data points
# In[5]:
## error for these two data points for m and b = 0
( (31.70700585-(0*32.50234527+0))**2 + (68.77759598-(0*53.42680403+0))**2 ) / 2
# In[6]:
display(Math(r' Error = \frac{1}{N} \sum_{i=1}^{N} (y_{i} - (mx_{i} + b)) ^2'))
# In[46]:
# y = mx + b ||| m is slope, b is y-intercept
def compute_error_for_line_given_points(b, m, points):
"""points are the data"""
totalError = 0
for i in range(0, len(points)): # looping through the respective data pairs
x = points[i, 0]
y = points[i, 1]
## x += 2 means x = x + 2 ##
totalError += (y - (m * x + b)) ** 2 ### summation part ##
# ( squared error for each data pair)
return totalError / float(len(points)) ## divide by 1/N at the end
# In[8]:
compute_error_for_line_given_points(0, 0, points[0:2])
# In[9]:
# derivates of loss function wrt to paramters
display(Math(r' \frac{\partial }{\partial m} = \frac{2}{N} \sum_{i=1}^{N} -x_{i}(y_{i} - (mx_{i} + b))'))
display(Math(r' \frac{\partial }{\partial b} = \frac{2}{N} \sum_{i=1}^{N} -(y_{i} - (mx_{i} + b))'))
# In[10]:
def step_gradient(b_current, m_current, points, learningRate):
b_gradient = 0
m_gradient = 0
N = float(len(points))
for i in range(0, len(points)): # looping through the respective data pairs
x = points[i, 0]
y = points[i, 1]
# updating the gradient (how to update the parameter values in order to minimize overall error)
b_gradient += -(2/N) * (y - ((m_current * x) + b_current)) # derivates of loss function wrt to b
m_gradient += -(2/N) * x * (y - ((m_current * x) + b_current)) # derivates of loss function wrt to m
new_b = b_current - (learningRate * b_gradient) # updating the parameter value for next iteration
new_m = m_current - (learningRate * m_gradient)
return [new_b, new_m]
# In[11]:
def gradient_descent_runner(points, initial_b, initial_m, learning_rate, num_iterations):
b = initial_b # defined in run()
m = initial_m # defined in run()
for i in range(num_iterations):
b, m = step_gradient(b, m, np.array(points), learning_rate)
print "At iteration {0}, b = {1} and m ={2}".format(i+1, b, m)
return [b, m]
# In[87]:
def run(learning_rate = 0.0001, num_iterations = 1000):
points = np.genfromtxt("data.csv", delimiter=",")
initial_b = 0 # initial y-intercept guess
initial_m = 0 # initial slope guess
print "Starting gradient descent at b = {0}, m = {1}, error = {2}".format(initial_b, initial_m,
compute_error_for_line_given_points(initial_b, initial_m, points)
)
print "Running..."
[b, m] = gradient_descent_runner(points, initial_b, initial_m, learning_rate, num_iterations)
print "After {0} iterations b = {1}, m = {2}, error = {3}".format(num_iterations, b, m,
compute_error_for_line_given_points(b, m, points)
)
# In[13]:
run()
# In[14]:
run(num_iterations = 5)
# # Replacing loops via numpy computations
# In[67]:
def compute_error_for_line_given_points_np(b, m, points):
"""points are the data"""
x = np.array(points[:,0])
y = np.array(points[:,1])
return np.sum((y - (m * x + b)) ** 2) / len(points) ## divide by 1/N at the end
print ('error difference for the two methods:')
compute_error_for_line_given_points_np(0, 0, points) - compute_error_for_line_given_points(0, 0, points)
# # run time comparison
# In[66]:
get_ipython().magic(u'timeit compute_error_for_line_given_points_np(0, 0, points)')
# In[55]:
get_ipython().magic(u'timeit compute_error_for_line_given_points(0, 0, points)')
# In[94]:
def step_gradient_np(b_current, m_current, points, learningRate):
b_gradient = 0
m_gradient = 0
N = float(len(points))
for i in range(0, len(points)): # looping through the respective data pairs
x = points[i, 0]
y = points[i, 1]
# updating the gradient (how to update the parameter values in order to minimize overall error)
b_gradient += -(2/N) * (y - ((m_current * x) + b_current)) # derivates of loss function wrt to b
m_gradient += -(2/N) * x * (y - ((m_current * x) + b_current)) # derivates of loss function wrt to m
new_b = b_current - (learningRate * b_gradient) # updating the parameter value for next iteration
new_m = m_current - (learningRate * m_gradient)
return [new_b, new_m]
# In[80]:
def gradient_descent_runner_np(points, initial_b, initial_m, learning_rate, num_iterations):
b = initial_b # defined in run()
m = initial_m # defined in run()
for i in range(num_iterations):
b, m = step_gradient_np(b, m, np.array(points), learning_rate)
#print "At iteration {0}, b = {1} and m ={2}".format(i+1, b, m)
return [b, m]
# In[81]:
def run_with_np_method(learning_rate = 0.0001, num_iterations = 1000):
points = np.genfromtxt("data.csv", delimiter=",")
initial_b = 0 # initial y-intercept guess
initial_m = 0 # initial slope guess
print "Starting gradient descent at b = {0}, m = {1}, error = {2}".format(initial_b, initial_m,
compute_error_for_line_given_points_np(initial_b, initial_m, points)
)
print "Running..."
[b, m] = gradient_descent_runner_np(points, initial_b, initial_m, learning_rate, num_iterations)
print "After {0} iterations b = {1}, m = {2}, error = {3}".format(num_iterations, b, m,
compute_error_for_line_given_points_np(b, m, points)
)
# In[88]:
get_ipython().magic(u'timeit run()')
# In[102]:
get_ipython().magic(u'timeit run_with_np_method()')
# In[101]:
run_with_np_method()
# In[100]:
def step_gradient_np(b_current, m_current, points, learningRate):
b_gradient = 0
m_gradient = 0
N = float(len(points))
x = np.array(points[:,0])
y = np.array(points[:,1])
# updating the gradient (how to update the parameter values in order to minimize overall error)
b_gradient = np.sum(-(2/N) * (y - ((m_current * x) + b_current))) # derivates of loss function wrt to b
m_gradient = np.sum(-(2/N) * x * (y - ((m_current * x) + b_current))) # derivates of loss function wrt to m
new_b = b_current - (learningRate * b_gradient) # updating the parameter value for next iteration
new_m = m_current - (learningRate * m_gradient)
return [new_b, new_m]
# In[98]:
b_gradient = 0
m_gradient = 0
N = float(len(points))
x = np.array(points[:,0])
y = np.array(points[:,1])
# updating the gradient (how to update the parameter values in order to minimize overall error)
b_gradient += -(2/N) * (y - ((0 * x) + 0)) # derivates of loss function wrt to b
new_b = 0 - (0.00001 * b_gradient) # updating the parameter value for next iteration
# In[99]:
b_gradient
# In[ ]: