| 1 |
|
| 2 |
import random |
| 3 |
import torch |
| 4 |
|
| 5 |
|
| 6 |
class DynamicNet(torch.nn.Module): |
| 7 |
def __init__(self, D_in, H, D_out): |
| 8 |
""" |
| 9 |
In the constructor we construct three nn.Linear instances that we will use |
| 10 |
in the forward pass. |
| 11 |
""" |
| 12 |
super(DynamicNet, self).__init__() |
| 13 |
self.input_linear = torch.nn.Linear(D_in, H) |
| 14 |
self.middle_linear = torch.nn.Linear(H, H) |
| 15 |
self.output_linear = torch.nn.Linear(H, D_out) |
| 16 |
|
| 17 |
def forward(self, x): |
| 18 |
""" |
| 19 |
For the forward pass of the model, we randomly choose either 0, 1, 2, or 3 |
| 20 |
and reuse the middle_linear Module that many times to compute hidden layer |
| 21 |
representations. |
| 22 |
|
| 23 |
Since each forward pass builds a dynamic computation graph, we can use normal |
| 24 |
Python control-flow operators like loops or conditional statements when |
| 25 |
defining the forward pass of the model. |
| 26 |
|
| 27 |
Here we also see that it is perfectly safe to reuse the same Module many |
| 28 |
times when defining a computational graph. This is a big improvement from Lua |
| 29 |
Torch, where each Module could be used only once. |
| 30 |
""" |
| 31 |
h_relu = self.input_linear(x).clamp(min=0) |
| 32 |
for _ in range(random.randint(0, 3)): |
| 33 |
h_relu = self.middle_linear(h_relu).clamp(min=0) |
| 34 |
y_pred = self.output_linear(h_relu) |
| 35 |
return y_pred |
| 36 |
|
| 37 |
|
| 38 |
|
| 39 |
|
| 40 |
N, D_in, H, D_out = 64, 1000, 100, 10 |
| 41 |
|
| 42 |
|
| 43 |
x = torch.randn(N, D_in) |
| 44 |
y = torch.randn(N, D_out) |
| 45 |
|
| 46 |
|
| 47 |
model = DynamicNet(D_in, H, D_out) |
| 48 |
|
| 49 |
|
| 50 |
|
| 51 |
criterion = torch.nn.MSELoss(reduction="sum") |
| 52 |
optimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9) |
| 53 |
for t in range(500): |
| 54 |
|
| 55 |
y_pred = model(x) |
| 56 |
|
| 57 |
|
| 58 |
loss = criterion(y_pred, y) |
| 59 |
if t % 100 == 99: |
| 60 |
print(t, loss.item()) |
| 61 |
|
| 62 |
|
| 63 |
optimizer.zero_grad() |
| 64 |
loss.backward() |
| 65 |
optimizer.step() |