-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path00_baby_steps.py
54 lines (43 loc) · 1.19 KB
/
00_baby_steps.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
import numpy as np
import torch
# Input (temp, rainfall, humidity)
inputs = np.array([[73, 67, 43],
[91, 88, 64],
[87, 134, 58],
[102, 43, 37],
[69, 96, 70]], dtype='float32')
# Targets (apples, oranges)
targets = np.array([[56, 70],
[81, 101],
[119, 133],
[22, 37],
[103, 119]], dtype='float32')
# Convert inputs and targets to tensors
inputs = torch.from_numpy(inputs)
targets = torch.from_numpy(targets)
print('inputs', inputs)
print('targets', targets)
# Weights and biases
w = torch.randn(2, 3, requires_grad=True)
b = torch.randn(2, requires_grad=True)
print('w', w)
print('b', b)
def model(x):
return x @ w.t() + b
# Generate predictions
preds = model(inputs)
print('preds', preds)
# Compare with targets
print('targets', targets)
# MSE loss
def mse(t1, t2):
diff = t1 - t2
return torch.sum(diff * diff) / diff.numel()
# Compute loss
loss = mse(preds, targets)
print('loss', loss)
# Compute gradients
loss.backward()
# Gradients for weights
print('w', w)
print('w.grad', w.grad)