-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgradient.py
More file actions
65 lines (46 loc) · 1.29 KB
/
Copy pathgradient.py
File metadata and controls
65 lines (46 loc) · 1.29 KB
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
import numpy as np
import matplotlib.pyplot as plt
import pandas as pd
X = []
y = []
def abline(slope, intercept):
Xi = np.array([-20,20])
plt.plot(Xi, Xi*slope + intercept, color = "black")
plt.pause(0.001)
plt.draw()
def gradient_descent():
n = len(X)
alpha = 0.0075
m = 0
b = 0
for i in range(0,100):
plt.clf()
plt.axis([-20,20,-20,20])
plt.scatter(X,y,color="red")
yguess = []
for j in range(0,n):
yguess.append(m * X[j] + b)
ynew = []
for j in range(0,n):
ynew.append((yguess[j]-y[j]) * X[j])
derivative1 = sum(ynew) / n
ynew = []
for j in range(0,n):
ynew.append(yguess[j] - y[j])
derivative0 = sum(ynew) / n
m = m - alpha * derivative1
b = b - alpha * derivative0
abline(m,b)
#abline(m,b)
fig = plt.figure()
ax = fig.add_subplot(111)
def onclick(event):
plt.clf()
print('button=%d, x=%d, y=%d, xdata=%f, ydata=%f' %
(event.button, event.x, event.y, event.xdata, event.ydata))
X.append(event.xdata)
y.append(event.ydata)
plt.scatter(X,y,color="red")
gradient_descent()
cid = fig.canvas.mpl_connect('button_press_event', onclick)
plt.show()