PyTorch torch.nn.RNN function
PyTorch torch.nn Reference Manual
torch.nn.RNN is the basic recurrent neural network module in PyTorch.
It is the simplest recurrent layer, but it is prone to the vanishing gradient problem.
Function definition
torch.nn.RNN(input_size, hidden_size, num_layers=1, bias=True, batch_first=True, dropout=0, bidirectional=False)
Usage examples
Example 1: Basic usage
Example
import
torch
import
torch.
nn
as
nn
rnn
=
nn.
RNN
(
input_size
=
256
,
hidden_size
=
128
,
num_layers
=
2
,
batch_first
=
True
)
x
=
torch.
randn
(
4
,
10
,
256
)
output
,
hidden
=
rnn
(
x
)
(
"Input:"
,
x.
shape
)
(
"Output:"
,
output.
shape
)
(
"Hidden:"
,
hidden.
shape
)
Example 2: Multi-layer RNN
Example
import
torch
import
torch.
nn
as
nn
3-layer RNN with dropout
rnn
=
nn.
RNN
(
128
,
256
,
num_layers
=
3
,
dropout
=
0.3
,
batch_first
=
True
)
x
=
torch.
randn
(
2
,
50
,
128
)
out
,
h
=
rnn
(
x
)
(
"Input:"
,
x.
shape
)
(
"Output:"
,
out.
shape
)
(
"Hidden:"
,
h.
shape
)
(3, 2, 256)
Example 3: Nonlinear activation
Example
import
torch
import
torch.
nn
as
nn
tanh is used as the activation function by default
rnn
=
nn.
RNN
(
64
,
64
,
batch_first
=
True
)
x
=
torch.
randn
(
1
,
5
,
64
)
out
,
_
=
rnn
(
x
)
(
"Output shape:"
,
out.
shape
)
(
"RNN uses tanh activation by default"
)
Notes
Basic RNNs suffer from the vanishing gradient problem; LSTM or GRU is recommended for long sequences.
Use Cases
- Simple sequence tasks: Short sequences
- Teaching examples: Understanding RNN principles
- Rapid prototyping: A simple baseline