-
Notifications
You must be signed in to change notification settings - Fork 0
/
module.py
49 lines (44 loc) · 1.29 KB
/
module.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
import numpy as np
def gradient_descent(
X,
y,
theta_0,
cost,
cost_derivate,
alpha=0.01,
threshold=0.0001,
max_iter=10000,
lamda=0):
theta, i = theta_0, 0
costs = []
gradient_norms = []
while np.linalg.norm(cost_derivate(X, y, theta, lamda)) > threshold and i < max_iter:
theta -= alpha * cost_derivate(X, y, theta, lamda)
i += 1
costs.append(cost(X, y, theta, lamda))
gradient_norms.append(cost_derivate(X, y, theta, lamda))
return theta
def linear_cost(x, y, theta, lamda=0):
m, _ = x.shape
h = np.matmul(x, theta)
sq = (h - y)**2
res = sq.sum() / (2*m)
return res
def linear_cost_derivate(x, y ,theta, lamda=0):
h = np.matmul(x, theta)
m,_ = x.shape
return np.matmul((h-y).T, x).T / m
def linear_cost_regular(x, y, theta, lamda):
m, _ = x.shape
h = np.matmul(x, theta)
sq = (h - y)**2
res = sq.sum() / (2*m)
regularization = (lamda/2*m)*((theta**2).sum())
return res + regularization
def linear_cost_derivate_regular(x, y ,theta, lamda):
h = np.matmul(x, theta)
m,_ = x.shape
res =(np.matmul((h-y).T, x).T / m)
regularization = (lamda/m)*((theta).sum())
#print(res, regularization)
return res + regularization