-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathautograd2d.py
More file actions
96 lines (73 loc) · 2.08 KB
/
Copy pathautograd2d.py
File metadata and controls
96 lines (73 loc) · 2.08 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
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
import pydynet as pdn
import numpy as np
import matplotlib.pyplot as plt
np.random.seed(42)
device = f'cuda:{pdn.cuda.device_count() - 1}' if pdn.cuda.is_available(
) else 'cpu'
x = np.random.randn(2)
A = pdn.Tensor([
[3, 1.],
[1, 2.],
]).to(device)
b = pdn.Tensor([-1., 1]).to(device)
def auto_grad(x, lr: float, n_iter: float):
Xs, ys = [], []
x = pdn.Tensor(x, requires_grad=True, device=device)
for _ in range(n_iter):
obj = x @ A @ x / 2 + b @ x
obj.backward()
Xs.append(x.numpy())
ys.append(obj.item())
with x.device:
x.data -= lr * x.grad
x.zero_grad()
Xs, ys = np.array(Xs), np.array(ys)
return Xs[:, 0], Xs[:, 1], ys
def manual_grad(x, lr: float, n_iter: float):
Xs, ys = [], []
for _ in range(n_iter):
obj = x @ A @ x / 2 + b @ x
Xs.append(x.copy())
ys.append(obj.item())
grad = A.numpy() @ x + b.numpy()
x -= lr * grad
Xs, ys = np.array(Xs), np.array(ys)
return Xs[:, 0], Xs[:, 1], ys
plt.rcParams['font.sans-serif'] = ['Times New Roman']
plt.rcParams['mathtext.fontset'] = 'stix'
fig = plt.figure(figsize=(8, 4))
ax1 = fig.add_subplot(1, 2, 1, projection='3d')
ax1.plot3D(
*auto_grad(x, .1, 30),
color='red',
lw=0.7,
label=r'$f(x)=\frac{1}{2}x^\top Ax+b^\top x$',
marker='^',
markersize=6,
)
ax1.tick_params(direction='in')
ax1.set_xlim(.45, .60)
ax1.set_ylim(-.8, 0)
ax1.set_zlim(-.8, -.3)
ax1.set_xticks([.45, .5, .55, .6])
ax1.set_yticks([-.8, -.6, -.4, -.2, 0])
plt.title('Gradient descent by AutoGrad')
plt.legend(prop={'size': 11})
ax1 = fig.add_subplot(1, 2, 2, projection='3d')
ax1.plot3D(
*manual_grad(x, .1, 30),
color='blue',
lw=0.7,
label=r'$f(x)=\frac{1}{2}x^\top Ax+b^\top x$',
marker='^',
markersize=6,
)
ax1.tick_params(direction='in')
ax1.set_xlim(.45, .60)
ax1.set_ylim(-.8, 0)
ax1.set_zlim(-.8, -.3)
ax1.set_xticks([.45, .5, .55, .6])
ax1.set_yticks([-.8, -.6, -.4, -.2, 0])
plt.title('Gradient descent by Manual calculation')
plt.legend(prop={'size': 11})
plt.savefig("imgs/ad2d.png")