-
Notifications
You must be signed in to change notification settings - Fork 105
/
Linear_Regression_with_Gradient_Descent.py
210 lines (189 loc) · 6.1 KB
/
Linear_Regression_with_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
'''
Y is the dependant variable and X is the independant variable
We are going to fit a line
Y = a0 + a1*x
using Gradient Descent minimizing the SSE.
This code will work for any variable with single attribute, i.e.
it is Linear Regression in 1 variable.
'''
import random
import matplotlib.pyplot as plt
import numpy as np
#Sum of Squares Error
def sse(n,a0,a1,x,y):
"""
Compute the sse sse sse.
Args:
n: (array): write your description
a0: (array): write your description
a1: (array): write your description
x: (array): write your description
y: (array): write your description
"""
s=0
mean=np.mean(y)
for i in range(n):
s+=(a0+a1*x[i]-mean)**2
return s/(2*n)
#Calculate the cost function
def cost(n,a0,a1,x,y,ch,p=2):
"""
Calculate the cost between two points.
Args:
n: (todo): write your description
a0: (todo): write your description
a1: (todo): write your description
x: (todo): write your description
y: (todo): write your description
ch: (todo): write your description
p: (todo): write your description
"""
s=0;
if ch=='sum-of-squares':
for i in range(n):
s+=(a0+a1*x[i]-y[i])**2
return s/(2*n)
if ch=='l-p norm':
for i in range(n):
s+=abs(a0+a1*x[i]-y[i])**p
return s**(1/p)
#Partial Differential with respect to a0
def dela0(n,a0,a1,x,y):
"""
Dela0 dela0.
Args:
n: (array): write your description
a0: (array): write your description
a1: (array): write your description
x: (array): write your description
y: (array): write your description
"""
s=0;
for i in range(n):
s+=(a0+a1*x[i]-y[i])
return s/n
#Partial Differential with respect to a1
def dela1(n,a0,a1,x,y):
"""
Dela1 dela1 dela1 dela
Args:
n: (array): write your description
a0: (array): write your description
a1: (array): write your description
x: (array): write your description
y: (array): write your description
"""
s=0;
for i in range(n):
s+=(a0+a1*x[i]-y[i])*x[i]
return s/n
def predict(x, y, alphas=np.linspace(0.001,1,10), it=1000):
"""
Predict the predicted )
Args:
x: (array): write your description
y: (array): write your description
alphas: (array): write your description
np: (array): write your description
linspace: (array): write your description
it: (array): write your description
"""
mx=max(x)
my=max(y)
# Normalize values in the range 0-1
for i in range(len(x)):
x[i]/=mx
y[i]/=my
coeff, r2, cos = grad_desc(x, y, alphas, it)
coeff, x, y = rescale(x, y, coeff, mx, my)
r2_alpha(r2, alphas)
plot_predict(x, y, coeff, r2, cos, it)
# Store all predictions for which R^2 is maximum in an array
a0=coeff[r2.index(max(r2))][0]
a1=coeff[r2.index(max(r2))][1]
pred=a0+x*a1
return pred
def grad_desc(x, y, alphas, it):
"""
Describe the objective function.
Args:
x: (todo): write your description
y: (todo): write your description
alphas: (todo): write your description
it: (todo): write your description
"""
r2=[]# Array to store calculated R^2 values
coeff=[] #Array to store Predicted Coefficients for Linear Regression
for alpha in alphas:
cos=[]
#Initialize random weights
a0=random.random()
a1=random.random()
for i in range(it):
# Reduce the coefficient by alpha times partial differential
temp0=a0-alpha*dela0(len(x),a0,a1,x,y)
temp1=a1-alpha*dela1(len(x),a0,a1,x,y)
a0=temp0
a1=temp1
#Add the cost for each iteration
cos.append(cost(len(x),a0,a1,x,y,ch='sum-of-squares'))
# Calculate and store the R^2 value for a particular learning rate alpha
r2.append(1-(cos[-1]/(cos[-1]+sse(len(x),a0,a1,x,y))))
#Store the predicted coefficients for regression
coeff.append([a0,a1])
return coeff, r2, cos
def r2_alpha(r2, alphas):
"""
Plot r2 alpha
Args:
r2: (todo): write your description
alphas: (array): write your description
"""
#Plot for R^2 vs alpha
plt.plot(alphas, r2)
plt.title('R^2 vs. Learning Rate')
#Max. value of R^2 over all values of alpha
print(max(r2))
#Value of alpha for maximum R^2
print(np.linspace(0.001,1,10)[r2.index(max(r2))])
def rescale(x, y, coeff, mx, my):
"""
Rescale x y - axis.
Args:
x: (todo): write your description
y: (todo): write your description
coeff: (todo): write your description
mx: (todo): write your description
my: (todo): write your description
"""
# Bring the data back to scale
for i in range(len(coeff)):
coeff[i][0]*=my
coeff[i][1]*=my/mx
for i in range(len(x)):
x[i]*=mx
y[i]*=my
return coeff, x, y
def plot_predict(x, y, coeff, r2, cos, it):
"""
Plots the r2d plot
Args:
x: (array): write your description
y: (array): write your description
coeff: (array): write your description
r2: (array): write your description
cos: (array): write your description
it: (array): write your description
"""
# Plot the training data, cost function and Predicted vs Actual values
fig1,ax=plt.subplots(1,2,figsize=(14,4))
ax[0].plot([x for x in range(it)],cos)
ax[0].set_title('Cost Function')
ax[0].set_xlabel('No. of Iterations')
ax[1].scatter(x,y,marker='x',color='r',label="Training Data")
ax[1].plot(np.arange(1,12),[coeff[r2.index(max(r2))][0]+coeff[r2.index(max(r2))][1]*x for x in np.arange(1,12)],label="Linear Regression")
plt.legend()
ax[1].set_title('Predicted vs Actual')
plt.xlabel("Experience in Years")
plt.ylabel("Salary")
plt.show()