-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathpolynomial_regression.py
More file actions
216 lines (161 loc) · 6.72 KB
/
polynomial_regression.py
File metadata and controls
216 lines (161 loc) · 6.72 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
# -*- coding: utf-8 -*-
"""
Created on Wed Jun 7 14:17:38 2017
@author: picku
"""
import numpy as np
from scipy import linalg
from collections import OrderedDict
import matplotlib.pyplot as plt
from matplotlib import style
style.use('ggplot')
class PolynomialRegression(object):
"""PolynomialRegression
Parameters
------------
x_pts : 1-d numpy array, shape = [n_samples,]
y_pts : 1-d numpy array, shape = [n_samples,]
Attributes
------------
theta : 1-d numpy array, shape = [polynomial order + 1,]
Ceofficients of fitted polynomial, with theta[0] corresponding
to the intercept term
method : str , values = 'normal_equation' | 'gradient_descent'
Method used for finding optimal values of theta
If gradient descent method is chosen:
costs : 1-d numpy array,
Cost function values for every iteration of gradient descent
numIters: int
Number of iterations of gradient descent to be performed
References
------------
https://en.wikipedia.org/wiki/Polynomial_regression
"""
def __init__(self, x, y):
self.x = x
self.y = y
def standardize(self,data):
""" Peform feature scaling
Parameters:
------------
data : numpy-array, shape = [n_samples,]
Returns:
---------
Standardized data
"""
return (data - np.mean(data))/(np.max(data) - np.min(data))
def hypothesis(self, theta, x):
""" Compute hypothesis, h, where
h(x) = theta_0*(x_1**0) + theta_1*(x_1**1) + ...+ theta_n*(x_1 ** n)
Parameters:
------------
theta : numpy-array, shape = [polynomial order + 1,]
x : numpy-array, shape = [n_samples,]
Returns:
---------
h(x) given theta values and the training data
"""
h = theta[0]
for i in np.arange(1, len(theta)):
h += theta[i]*x ** i
return h
def computeCost(self, x, y, theta):
""" Compute value of cost function J
Parameters:
------------
x : numpy array, shape = [n_samples,]
y : numpy array, shape = [n_samples,]
Returns:
---------
Value of cost function J at value theta given the training data
"""
m = len(y)
h = self.hypothesis(theta, x)
errors = h-y
return (1/(2*m))*np.sum(errors**2)
def fit(self, method = 'normal_equation', order = 1, tol = 10**-3, numIters = 20, learningRate = 0.01):
"""Fit theta to the training data
Parameters
-----------
method: string, values = 'normal_equation' | 'gradient_descent'
Indicates method for which polynomial regression will be performed
order: int, optional
Order of polynomial fit. Defaults to 1 (linear fit)
numIters: int, optional
Number of iterations of gradient descent to be performed
learningRate: float, optional
tol : float, optional
Value indicating the cost value (J(theta)) at which
gradient descent should terminated. Defaults to 10 ** -3
Returns:
-----------
self : object
"""
if method == 'normal_equation':
d = {}
d['x' + str(0)] = np.ones([1,len(x_pts)])[0]
for i in np.arange(1, order+1):
d['x' + str(i)] = self.x ** (i)
d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
X = np.column_stack(d.values())
theta = np.matmul(np.matmul(linalg.pinv(np.matmul(np.transpose(X),X)), np.transpose(X)), self.y)
elif method == 'gradient_descent':
d = {}
d['x' + str(0)] = np.ones([1,len(x_pts)])[0]
for i in np.arange(1, order+1):
d['x' + str(i)] = self.standardize(self.x ** (i))
d = OrderedDict(sorted(d.items(), key=lambda t: t[0]))
X = np.column_stack(d.values())
m = len(self.x)
theta = np.zeros(order + 1)
costs = []
for i in range(numIters):
h = self.hypothesis(theta, self.x)
errors = h-self.y
theta += -learningRate * (1/m)*np.dot(errors, X)
cost = self.computeCost(self.x, self.y, theta)
costs.append(cost)
#tolerance check
if cost < tol:
break
self.costs = costs
self.numIters = numIters
self.method = method
self.theta = theta
return self
def plot_predictedPolyLine(self):
"""Plot predicted polynomial line using values of theta found
using normal equation or gradient descent method
Returns
-----------
matploblib figure
"""
plt.figure()
plt.scatter(self.x, self.y, s = 30, c = 'b')
line = self.theta[0] #y-intercept
label_holder = []
label_holder.append('%.*f' % (2, self.theta[0]))
for i in np.arange(1, len(self.theta)):
line += self.theta[i] * self.x ** i
label_holder.append(' + ' +'%.*f' % (2, self.theta[i]) + r'$x^' + str(i) + '$')
plt.plot(self.x, line, label = ''.join(label_holder))
plt.title('Polynomial Fit: Order ' + str(len(self.theta)-1))
plt.xlabel('x')
plt.ylabel('y')
plt.legend(loc = 'best')
def plotCost(self):
"""Plot number of gradient descent iterations verus cost function, J,
values at values of theta
Returns
-----------
matploblib figure
"""
if self.method == 'gradient_descent':
plt.figure()
plt.plot(np.arange(1, self.numIters+1), self.costs, label = r'$J(\theta)$')
plt.xlabel('Iterations')
plt.ylabel(r'$J(\theta)$')
plt.title('Cost vs Iterations of Gradient Descent')
plt.legend(loc = 'best')
else:
print('plotCost method can only be called when using gradient descent method')