-
Notifications
You must be signed in to change notification settings - Fork 0
/
lowlevel.py
69 lines (46 loc) · 1.28 KB
/
lowlevel.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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
import torch as T
from torch.autograd import Variable
# Hyper params
lr = 0.25
momentum = .25
n_data = 20
epochs = 100
# Dataset (normalized)
# y = 2 * x + 1
data_x = T.tensor([x / n_data for x in range(n_data)], dtype=T.float)
data_y = T.tensor([2 * (x / n_data) + 1 for x in range(n_data)], dtype=T.float)
# Weights
w = Variable(T.tensor([.2, .1], dtype=T.float), requires_grad=True)
def forward(x):
global w
return x * w[0] + w[1]
def loss(pred, y):
global n_data
return 1 / n_data * (pred - y) ** 2
def test():
global data_x, data_y
mse = 0
for x, y in zip(data_x, data_y):
pred = forward(x)
mse += loss(pred, y)
return mse.item()
print(f'Init mse : {test():.4f}')
# Train
for epoch in range(epochs):
for x, y in zip(data_x, data_y):
# Feed forward
pred = forward(x)
error = loss(pred, y)
# Back prop
error.backward()
w.data -= lr * w.grad.data
# Momentum
w.grad.data *= momentum
# Without momentum : w.grad.data.zero_()
print(f'After train mse : {test():.4f}')
print('y pred')
# Evaluate
for x, y in zip(data_x, data_y):
pred = x * w[0] + w[1]
print(f'{y.item():.2f} {pred.item():.2f}')
print(f'Weights : {w[0].item():.2f} {w[1].item():.2f}')