-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathgradient_descent.py
More file actions
28 lines (22 loc) · 872 Bytes
/
gradient_descent.py
File metadata and controls
28 lines (22 loc) · 872 Bytes
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
import numpy as np
train_x = np.array(([1,1],[2,1]))
train_y = np.array(([1],[3]))
rate = 0.01
def cost_function(x, y, theta):
'''caculate the cost of this model'''
cost_vecter = np.dot(x, theta) - y
return np.dot(np.transpose(cost_vecter), cost_vecter)*(1/2)
def gradient_function(x, y, theta):
'''caculate the gradient of this theta'''
diffrence = np.dot(x, theta) - y
return (1/2)*np.dot(np.transpose(x), diffrence)
def gradient_descent(x, y, theta):
'''the main function of gradient descent'''
theta = np.array(([1],[1]))
gradient = gradient_function(x, y, theta)
while np.all(np.absolute(gradient) >= 1e-5):
theta = theta - rate*gradient
gradient = gradient_function(x, y, theta)
return theta
print(gradient_descent(train_x, train_y, rate))
# print(cost_function(train_x,train_y,np.array(([1],[1]))))