-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathlinear_regression.py
98 lines (78 loc) · 3.1 KB
/
linear_regression.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
import numpy as np
from numpy.linalg import inv
from sklearn.datasets import load_boston
def squared_loss(y, pred):
return np.square(pred - y).mean() / 2
def squared_loss_gradient(y, pred):
return pred - y
class LinearRegression(object):
def __init__(self):
self.learning_rate = 0.1
self.embedding_dim = 1
self.lmbda = 0.001 # regularization coefficient
self.reg = 2
self.eps = 1e-12
self.optimization = False
def fit(self, x, y):
if self.optimization:
self.optimize(x, y)
else:
self.matrix_solver(x, y)
def optimize(self, x, y):
n_dim = x.shape[1]
self.b = 0
self.w = np.random.randn(n_dim)
self.mom_w, self.cache_w = np.zeros(n_dim), np.zeros(n_dim)
self.mom_b, self.cache_b = 0, 0
for i in range(5000):
grad = squared_loss_gradient(y, self.predict(x))
self.adam(grad.dot(x), grad.sum(), i + 1)
self.regularization()
if i % 100 == 0:
print('loss {}'.format(squared_loss(self.predict(x), y)))
def matrix_solver(self, x, y):
n_dim = x.shape[1]
ext_x = np.c_[x, np.ones((x.shape[0], 1))]
inv_matrix = inv(np.matmul(ext_x.T, ext_x) +
self.lmbda * np.identity(n_dim + 1))
ext_w = np.matmul(np.matmul(inv_matrix, ext_x.T), y.reshape(-1, 1))
self.w = ext_w[:-1].flatten()
self.b = ext_w[-1]
def sgd(self, grad_w, grad_b): # use a very small learning rate for sgd, e.g., 1e-8
self.w -= self.learning_rate * grad_w
self.b -= self.learning_rate * grad_b
def adam(self, grad_w, grad_b, i):
beta1 = 0.9
beta2 = 0.999
alpha = self.learning_rate
self.mom_w = beta1 * self.mom_w + (1 - beta1) * grad_w
self.cache_w = beta2 * self.cache_w + (1 - beta2) * np.square(grad_w)
self.w -= alpha * self.mom_w / \
(1 - beta1**i) / (np.sqrt(self.cache_w / (1 - beta2**i)) + self.eps)
self.mom_b = beta1 * self.mom_b + (1 - beta1) * grad_b
self.cache_b = beta2 * self.cache_b + (1 - beta2) * np.square(grad_b)
self.b -= alpha * self.mom_b / \
(1 - beta1**i) / (np.sqrt(self.cache_b / (1 - beta2**i)) + self.eps)
def regularization(self):
if(self.reg == 1):
self.w -= self.lmbda * np.sign(self.w)
self.b -= self.lmbda * np.sign(self.b)
elif(self.reg == 2):
self.w -= self.lmbda * self.w
self.b -= self.lmbda * self.b
def predict(self, x):
return self.b + x.dot(self.w)
def main():
data = load_boston()
test_ratio = 0.2
test_split = np.random.uniform(0, 1, len(data.data))
train_x = data.data[test_split >= test_ratio]
test_x = data.data[test_split < test_ratio]
train_y = data.target[test_split >= test_ratio]
test_y = data.target[test_split < test_ratio]
rr = LinearRegression()
rr.fit(train_x, train_y)
print(squared_loss(rr.predict(train_x), train_y))
print(squared_loss(rr.predict(test_x), test_y))
if __name__ == "__main__":
main()