forked from ShivamDubey7/Competitive-Programming-Algos
-
Notifications
You must be signed in to change notification settings - Fork 315
/
Gradient Descent
33 lines (33 loc) · 958 Bytes
/
Gradient Descent
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
import numpy as np
def step_gradient(points,learning_rate,m,c):
m_slope,c_slope=0,0
M=len(points)
for i in range(M):
x=points[i,0]
y=points[i,1]
m_slope+=(-2/M)*(y-m*x-c)*x #To calculate slope.
c_slope+=(-2/M)*(y-m*x-c)
new_m=m-learning_rate*m_slope
new_c=c-learning_rate*c_slope
return new_m,new_c
def gd(points,learning_rate,num_iterations):
m,c=0,0
for i in range(num_iterations):
m,c=step_gradient(points,learning_rate,m,c)
print(i,"CostL",cost(points,m,c))
return m,c
def cost(points,m,c):
total_cost=0
M=len(points)
for i in range(M):
x=points[i,0]
y=points[i,1]
total_cost+=(1/M)*((y-m*x-c)**2)
return total_cost
def run():
data=np.loadtxt("D:\Machine Learning\data.csv",delimiter=",")
learning_rate=0.0001
num_iterations=100
m,c=gd(data,learning_rate,num_iterations)
print(m,c)
run()