Skip to content

Commit 620ce53

Browse files
matricize regressor also
1 parent e73e810 commit 620ce53

File tree

2 files changed

+9
-11
lines changed

2 files changed

+9
-11
lines changed

linear_regression.py

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,11 @@ def fit(self, X, y):
1212
self.beta = np.dot( np.dot( np.linalg.inv(np.dot(X.T,X)), X.T ), y )
1313

1414

15-
def predict(self, x):
15+
def predict(self, X):
1616
# prepend 1, dot product with beta
17-
return np.inner(self.beta, np.concatenate([[1], x]))
17+
N = len(X)
18+
X = np.concatenate((np.array([[1]*N]).T, X), axis=1)
19+
return np.inner(self.beta, X)
1820

1921

2022
def test():
@@ -38,7 +40,7 @@ def test():
3840

3941
# predict
4042
x = (100, 100)
41-
h = lr.predict(x)
43+
h = lr.predict(np.array([x]))
4244
y = 5*x[0] - 2*x[1] + 3
4345
print "Extrapolated prediction: %.2f\nActual: %.2f" % (h, y)
4446

regressor.py

Lines changed: 4 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -3,12 +3,8 @@
33

44
class Regressor(object):
55
def score(self, X, y):
6-
meany = np.mean(y)
7-
SStot = 0
8-
SSres = 0
9-
for xi, yi in zip(X, y):
10-
res = yi - self.predict(xi)
11-
tot = yi - meany
12-
SSres += res*res
13-
SStot += tot*tot
6+
SSres = y - self.predict(X)
7+
SSres = np.dot(SSres.T, SSres)
8+
SStot = y - np.mean(y)
9+
SStot = np.dot(SStot.T, SStot)
1410
return 1 - SSres/SStot

0 commit comments

Comments
 (0)