PyTorch: Control Flow + Weight Sharing
beginner/examples_nn/dynamic_net
random
import
torch
import
math
class
DynamicNet
(
):
def
__init__
(
self
):
"""
In the constructor we instantiate five parameters and assign them as members.
"""
super
()
.
__init__
()
self
.
a
=
torch
.
nn
.
Parameter
(
(()))
self
.
b
=
torch
.
nn
.
Parameter
(
(()))
self
.
c
=
torch
.
nn
.
Parameter
(
(()))
self
.
d
=
torch
.
nn
.
Parameter
(
(()))
self
.
e
=
torch
.
nn
.
Parameter
(
(()))
def
forward
(
self
,
x
):
"""
For the forward pass of the model, we randomly choose either 4, 5
and reuse the e parameter to compute the contribution of these orders.
Since each forward pass builds a dynamic computation graph, we can use normal
Python control-flow operators like loops or conditional statements when
defining the forward pass of the model.
Here we also see that it is perfectly safe to reuse the same parameter many
times when defining a computational graph.
"""
y
=
self
.
a
+
self
.
b
*
x
+
self
.
c
*
x
**
2
+
self
.
d
*
x
**
3
for
exp
in
range
(
4
,
random
.
randint
(
4
,
6
)):
y
=
y
+
self
.
e
*
x
**
exp
return
y
def
string
(
self
):
"""
Just like any class in Python, you can also define custom method on PyTorch modules
"""
return
f
'y =
{
self
.
a
.
item
()
}
+
{
self
.
b
.
item
()
}
x +
{
self
.
c
.
item
()
}
x^2 +
{
self
.
d
.
item
()
}
x^3 +
{
self
.
e
.
item
()
}
x^4 ? +
{
self
.
e
.
item
()
}
x^5 ?'
x
=
(
-
math
.
pi
,
math
.
pi
,
2000
)
y
=
(
x
)
model
=
DynamicNet
()
criterion
=
(
reduction
=
'sum'
)
optimizer
=
(
model
.
parameters
(),
lr
=
1e-8
,
momentum
=
0.9
)
for
t
in
range
(
30000
):
y_pred
=
model
(
x
)
loss
=
criterion
(
y_pred
,
y
)
if
t
%
2000
==
1999
:
print
(
t
,
loss
.
item
())
optimizer
.
zero_grad
()
loss
.
backward
()
optimizer
.
step
()
print
(
f
'Result:
{
model
.
string
()
}
'
)