Skip to content

Commit d8d8681

Browse files
committed
Build e5d1b46
1 parent 9c8fef3 commit d8d8681

14 files changed

+405
-405
lines changed

_downloads/dynamic_net.ipynb

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,54 +1,54 @@
11
{
2+
"nbformat": 4,
3+
"nbformat_minor": 0,
24
"metadata": {
3-
"kernelspec": {
4-
"name": "python3",
5-
"language": "python",
6-
"display_name": "Python 3"
7-
},
85
"language_info": {
9-
"version": "3.5.2",
106
"file_extension": ".py",
7+
"version": "3.5.2",
8+
"name": "python",
9+
"mimetype": "text/x-python",
10+
"pygments_lexer": "ipython3",
1111
"nbconvert_exporter": "python",
1212
"codemirror_mode": {
13-
"name": "ipython",
14-
"version": 3
15-
},
16-
"mimetype": "text/x-python",
17-
"name": "python",
18-
"pygments_lexer": "ipython3"
13+
"version": 3,
14+
"name": "ipython"
15+
}
16+
},
17+
"kernelspec": {
18+
"name": "python3",
19+
"language": "python",
20+
"display_name": "Python 3"
1921
}
2022
},
21-
"nbformat": 4,
2223
"cells": [
2324
{
25+
"source": [
26+
"%matplotlib inline"
27+
],
28+
"execution_count": null,
2429
"cell_type": "code",
2530
"metadata": {
2631
"collapsed": false
2732
},
28-
"outputs": [],
29-
"execution_count": null,
30-
"source": [
31-
"%matplotlib inline"
32-
]
33+
"outputs": []
3334
},
3435
{
35-
"cell_type": "markdown",
36-
"metadata": {},
3736
"source": [
3837
"\nPyTorch: Control Flow + Weight Sharing\n--------------------------------------\n\nTo showcase the power of PyTorch dynamic graphs, we will implement a very strange\nmodel: a fully-connected ReLU network that on each forward pass randomly chooses\na number between 1 and 4 and has that many hidden layers, reusing the same\nweights multiple times to compute the innermost hidden layers.\n\n"
39-
]
38+
],
39+
"cell_type": "markdown",
40+
"metadata": {}
4041
},
4142
{
43+
"source": [
44+
"import random\nimport torch\nfrom torch.autograd import Variable\n\nclass DynamicNet(torch.nn.Module):\n def __init__(self, D_in, H, D_out):\n \"\"\"\n In the constructor we construct three nn.Linear instances that we will use\n in the forward pass.\n \"\"\"\n super(DynamicNet, self).__init__()\n self.input_linear = torch.nn.Linear(D_in, H)\n self.middle_linear = torch.nn.Linear(H, H)\n self.output_linear = torch.nn.Linear(H, D_out)\n\n def forward(self, x):\n \"\"\"\n For the forward pass of the model, we randomly choose either 0, 1, 2, or 3\n and reuse the middle_linear Module that many times to compute hidden layer\n representations.\n\n Since each forward pass builds a dynamic computation graph, we can use normal\n Python control-flow operators like loops or conditional statements when\n defining the forward pass of the model.\n\n Here we also see that it is perfectly safe to reuse the same Module many\n times when defining a computational graph. This is a big improvement from Lua\n Torch, where each Module could be used only once.\n \"\"\"\n h_relu = self.input_linear(x).clamp(min=0)\n for _ in range(random.randint(0, 3)):\n h_relu = self.middle_linear(h_relu).clamp(min=0)\n y_pred = self.output_linear(h_relu)\n return y_pred\n\n\n# N is batch size; D_in is input dimension;\n# H is hidden dimension; D_out is output dimension.\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# Create random Tensors to hold inputs and outputs, and wrap them in Variables\nx = Variable(torch.randn(N, D_in))\ny = Variable(torch.randn(N, D_out), requires_grad=False)\n\n# Construct our model by instantiating the class defined above\nmodel = DynamicNet(D_in, H, D_out)\n\n# Construct our loss function and an Optimizer. Training this strange model with\n# vanilla stochastic gradient descent is tough, so we use momentum\ncriterion = torch.nn.MSELoss(size_average=False)\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)\nfor t in range(500):\n # Forward pass: Compute predicted y by passing x to the model\n y_pred = model(x)\n\n # Compute and print loss\n loss = criterion(y_pred, y)\n print(t, loss.data[0])\n\n # Zero gradients, perform a backward pass, and update the weights.\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()"
45+
],
46+
"execution_count": null,
4247
"cell_type": "code",
4348
"metadata": {
4449
"collapsed": false
4550
},
46-
"outputs": [],
47-
"execution_count": null,
48-
"source": [
49-
"import random\nimport torch\nfrom torch.autograd import Variable\n\nclass DynamicNet(torch.nn.Module):\n def __init__(self, D_in, H, D_out):\n \"\"\"\n In the constructor we construct three nn.Linear instances that we will use\n in the forward pass.\n \"\"\"\n super(DynamicNet, self).__init__()\n self.input_linear = torch.nn.Linear(D_in, H)\n self.middle_linear = torch.nn.Linear(H, H)\n self.output_linear = torch.nn.Linear(H, D_out)\n\n def forward(self, x):\n \"\"\"\n For the forward pass of the model, we randomly choose either 0, 1, 2, or 3\n and reuse the middle_linear Module that many times to compute hidden layer\n representations.\n\n Since each forward pass builds a dynamic computation graph, we can use normal\n Python control-flow operators like loops or conditional statements when\n defining the forward pass of the model.\n\n Here we also see that it is perfectly safe to reuse the same Module many\n times when defining a computational graph. This is a big improvement from Lua\n Torch, where each Module could be used only once.\n \"\"\"\n h_relu = self.input_linear(x).clamp(min=0)\n for _ in range(random.randint(0, 3)):\n h_relu = self.middle_linear(h_relu).clamp(min=0)\n y_pred = self.output_linear(h_relu)\n return y_pred\n\n\n# N is batch size; D_in is input dimension;\n# H is hidden dimension; D_out is output dimension.\nN, D_in, H, D_out = 64, 1000, 100, 10\n\n# Create random Tensors to hold inputs and outputs, and wrap them in Variables\nx = Variable(torch.randn(N, D_in))\ny = Variable(torch.randn(N, D_out), requires_grad=False)\n\n# Construct our model by instantiating the class defined above\nmodel = DynamicNet(D_in, H, D_out)\n\n# Construct our loss function and an Optimizer. Training this strange model with\n# vanilla stochastic gradient descent is tough, so we use momentum\ncriterion = torch.nn.MSELoss(size_average=False)\noptimizer = torch.optim.SGD(model.parameters(), lr=1e-4, momentum=0.9)\nfor t in range(500):\n # Forward pass: Compute predicted y by passing x to the model\n y_pred = model(x)\n\n # Compute and print loss\n loss = criterion(y_pred, y)\n print(t, loss.data[0])\n\n # Zero gradients, perform a backward pass, and update the weights.\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()"
50-
]
51+
"outputs": []
5152
}
52-
],
53-
"nbformat_minor": 0
53+
]
5454
}

0 commit comments

Comments
 (0)