PyTorch torch.nn.LSTM function
PyTorch torch.nn Reference Manual
torch.nn.LSTM is a module in PyTorch for long short-term memory networks.
LSTM is a special kind of recurrent neural network that can learn long-term dependencies and is widely used for sequence modeling tasks.
Function definition
torch.nn.LSTM(input_size, hidden_size, num_layers=1, bias=True, batch_first=True, dropout=0, bidirectional=False)
Parameter Description:
input_size(int): input feature dimension.hidden_size(int): hidden state dimension.num_layers(int): number of LSTM layers. Default is 1.bias(bool): whether to use bias. Default is True.batch_first(bool): if True, input and output have shape (batch, seq, feature). Default is True.dropout(float): dropout used in layers other than the last. Default is 0.bidirectional(bool): whether to use a bidirectional LSTM. Default is False.
Input/Output
Inputs:
input: a tensor of shape (batch, seq_len, input_size)h_0: initial hidden state, of shape (num_layers * num_directions, batch, hidden_size)c_0: initial cell state, of shape (num_layers * num_directions, batch, hidden_size)
Output:
output: output of the last hidden layer, of shape (batch, seq_len, num_directions * hidden_size)h_n: the final hidden state of all layersc_n: the final cell state of all layers
Usage examples
Example 1: Basic usage
Creating and using an LSTM:
Example
import
torch
import
torch.
nn
as
nn
Create an LSTM: input dimension 256, hidden dimension 512, 2 layers
lstm
=
nn.
LSTM
(
input_size
=
256
,
hidden_size
=
512
,
num_layers
=
2
,
batch_first
=
True
)
Create input: batch=4, sequence length=10, input dimension=256
input_tensor
=
torch.
randn
(
4
,
10
,
256
)
Forward propagation
output
,
(
h_n
,
c_n
)
=
lstm
(
input_tensor
)
(
"Input shape:"
,
input_tensor.
shape
)
(
"Output shape:"
,
output.
shape
)
(4, 10, 512)
(
"Hidden state shape:"
,
h_n.
shape
)
(2, 4, 512)
(
"Cell state shape:"
,
c_n.
shape
)
(2, 4, 512)
Example 2: Bidirectional LSTM
Using a bidirectional LSTM to capture context in both directions:
Example
import
torch
import
torch.
nn
as
nn
Bidirectional LSTM
bilstm
=
nn.
LSTM
(
input_size
=
256
,
hidden_size
=
256
,
num_layers
=
2
,
batch_first
=
True
,
bidirectional
=
True
)
input_tensor
=
torch.
randn
(
4
,
10
,
256
)
output
,
(
h_n
,
c_n
)
=
bilstm
(
input_tensor
)
(
"Bidirectional LSTM output shape:"
,
output.
shape
)
(4, 10, 512) = 256*2
(
"Hidden state shape:"
,
h_n.
shape
)
(4, 4, 256) = 2 layers * 2 directions
(
"Last layer hidden state:"
,
h_n
[
2
:
,
:
,
:
]
.
shape
)
Forward and backward directions
Example 3: Initializing the hidden state
Manually initializing the hidden state:
Example
import
torch
import
torch.
nn
as
nn
lstm
=
nn.
LSTM
(
input_size
=
256
,
hidden_size
=
512
,
batch_first
=
True
)
Manually create the initial hidden state
batch_size
=
4
num_layers
=
2
hidden_size
=
512
h_0
=
torch.
zeros
(
num_layers
,
batch_size
,
hidden_size
)
c_0
=
torch.
zeros
(
num_layers
,
batch_size
,
hidden_size
)
Pass in the initial state
input_tensor
=
torch.
randn
(
4
,
10
,
256
)
output
,
(
h_n
,
c_n
)
=
lstm
(
input_tensor
,
(
h_0
,
c_0
)
)
(
"Done using a custom initial state"
)
(
"Output shape:"
,
output.
shape
)
Example 4: A complete sentiment classification model
LSTM-based text classification:
Example
import
torch
import
torch.
nn
as
nn
class
LSTMClassifier
(
nn.
Module
)
:
def
init
(
self
,
vocab_size
,
embed_dim
,
hidden_dim
,
num_classes
=
2
)
:
super
(
LSTMClassifier
,
self
)
.
init
(
)
Embedding layer
self
.
embedding
=
nn.
Embedding
(
vocab_size
,
embed_dim
,
padding_idx
=
0
)
LSTM layer
self
.
lstm
=
nn.
LSTM
(
input_size
=
embed_dim
,
hidden_size
=
hidden_dim
,
num_layers
=
2
,
batch_first
=
True
,
bidirectional
=
True
,
dropout
=
0.3
)
Fully connected classification layer
self
.
fc
=
nn.
Linear
(
hidden_dim *
2
,
num_classes
)
def
forward
(
self
,
x
)
:
x: (batch, seq_len)
embedded
=
self
.
embedding
(
x
)
(batch, seq_len, embed_dim)
LSTM output
output
,
(
hidden
,
cell
)
=
self
.
lstm
(
embedded
)
Concatenate the hidden states of the last layer from both directions
hidden: (4, batch, hidden_dim) - 2 layers * 2 directions
hidden
=
torch.
cat
(
[
hidden
[
2
]
,
hidden
[
1
]
]
,
dim
=
1
)
(batch, hidden_dim*2)
Classification
logits
=
self
.
fc
(
hidden
)
return
logits
Instantiate the model
vocab_size
=
10000
model
=
LSTMClassifier
(
vocab_size
=
vocab_size
,
embed_dim
=
128
,
hidden_dim
=
128
,
num_classes
=
2
)
Test input: batch=8, sequence length=50
input_ids
=
torch.
randint
(
1
,
vocab_size
,
(
8
,
50
)
)
output
=
model
(
input_ids
)
(
"Model structure:"
)
(
model
)
(
"nInput shape:"
,
input_ids.
shape
)
(
"Output shape:"
,
output.
shape
)
(8, 2)
Example 5: Stacked multi-layer LSTM
A deep LSTM network:
Example
import
torch
import
torch.
nn
as
nn
4 stacked LSTM layers with dropout
deep_lstm
=
nn.
LSTM
(
input_size
=
256
,
hidden_size
=
512
,
num_layers
=
4
,
batch_first
=
True
,
dropout
=
0.4
Dropout between layers
)
input_tensor
=
torch.
randn
(
2
,
20
,
256
)
output
,
(
h_n
,
c_n
)
=
deep_lstm
(
input_tensor
)
(
"4-layer LSTM output shape:"
,
output.
shape
)
(
"Hidden state shape (4 layers):"
,
h_n.
shape
)
(
"Cell state shape (4 layers):"
,
c_n.
shape
)
LSTM Gate Concepts
LSTM controls the flow of information through three gates:
- Forget Gate: Determines how much information from the previous time step to keep
- Input Gate: Determines how much new information to add
- Output Gate: Determines how much information to output
Common questions
Q1: What does batch_first=True mean?
The first dimension of the input and output tensors is batch_size. If False, the first dimension is the sequence length.
Q2: When should a bidirectional LSTM be used?
Tasks that need bidirectional context, such as sequence labeling and sentiment analysis. Machine translation often uses an encoder-decoder architecture.
Q3: How to choose the hidden layer size?
Usually 128-512, adjusted based on task complexity and data volume. Too small causes underfitting; too large causes overfitting.
Use Cases
nn.LSTM Main application scenarios include:
- Natural Language Processing: Text classification, named entity recognition
- Time Series Forecasting: Stock prediction, speech recognition
- Sequence-to-sequence tasks: Machine translation, text generation
Tip: When using bidirectional=True, the output dimension becomes hidden_size * 2.