generated from github/welcome-to-github
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathRidgeReg.py
69 lines (53 loc) · 1.83 KB
/
RidgeReg.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
import numpy as np
class LinearRegression:
def __init__(self):
self.theta = None
def _cost(self, theta, X, y):
X = np.array(X)
y = np.array(y)
theta = np.array(theta)
return 1 / len(y) * sum([np.square(X.dot(theta) - y)])
def fit(self, X, y):
X = np.array(X)
y = np.array(y)
self.theta = np.linalg.inv(X.T.dot(X)).dot(X.T).dot(y)
return self
def predict(self, X):
X = np.array(X)
self.theta = np.array(self.theta)
predictions = []
for i in range(len(X)):
result = []
for j in range(len(self.theta)):
result.append(self.theta[j] * X[i][j])
predictions.append(sum(result))
return predictions
def score(self, X, y):
predictons = self.predict(X)
return sum(self._cost(self.theta, X, y)) / len(X)
class Ridge:
def __init__(self):
self.theta = None
def _cost(self, theta, X, y):
X = np.array(X)
y = np.array(y)
theta = np.array(theta)
return 1 / len(y) * sum([np.square(X.dot(theta) - y)])
def fit(self, X, y, lam):
X = np.array(X)
y = np.array(y)
self.theta = np.linalg.inv(X.T.dot(X) + lam * np.identity(len(X.T))).dot(X.T).dot(y)
return self
def predict(self, X):
X = np.array(X)
self.theta = np.array(self.theta)
predictions = []
for i in range(len(X)):
result = []
for j in range(len(self.theta)):
result.append(self.theta[j] * X[i][j])
predictions.append(sum(result))
return predictions
def score(self, X, y):
predictions = self.predict(X)
return sum(self._cost(self.theta, X, y)) / len(X)