PyTorch LSTM / GRU
Recurrent Neural Networks (RNNs) face the vanishing gradient problem when processing sequential data, making it difficult to learn long-range dependencies.
Long Short-Term Memory (LSTM) networks and Gated Recurrent Units (GRU) solve this problem by introducing gating mechanisms, and are core models for sequential tasks such as time series, natural language, and speech.
1. Limitations of RNNs and Gating Mechanisms
A standard RNN combines the current input with the previous hidden state at each time step to compute a new hidden state:
[h_t = \tanh(W_h \cdot h_{t-1} + W_x \cdot x_t + b)]
This structure has two core problems:
Vanishing gradients: during backpropagation the gradient must be multiplied step by step by the weight matrix; for long sequences the gradient decays exponentially, so parameters at early time steps barely update and the model cannot learn long-range dependencies.
Exploding gradients: when the largest eigenvalue of the weight matrix is greater than 1, the gradient grows exponentially during backpropagation, making training unstable (usually mitigated by gradient clipping).
The core idea of gating is to introduce learnable "switches", letting the network decide on its own: at the current time step, which information should be remembered, which should be forgotten, and which new information should be written to memory.
LSTM uses three gates (forget gate, input gate, output gate) plus a separate cell state; GRU simplifies the structure to two gates (reset gate, update gate), with fewer parameters and faster training.
2. LSTM Principles
2.1 Core Structure and the Three Gates
LSTM maintains two state vectors passed between time steps:
- Cell State (c_t): the carrier of long-term memory, where information can flow almost losslessly
- Hidden State (h_t): short-term memory, also the output of the current time step
All three gates are linear transformations with Sigmoid activation, outputting values between 0 and 1, acting as "valves":
遗忘门(Forget Gate):决定从细胞状态中丢弃哪些信息
输入门(Input Gate):决定将哪些新信息写入细胞状态
输出门(Output Gate):决定基于细胞状态输出什么
2.2 Forward Calculation Formulas
[ \begin{aligned} \text{Input:} & x_t \text{(current time step input)}, h_{t-1} \text{(previous hidden state)}, c_{t-1} \text{(previous cell state)} \ \text{Forget gate:} & f_t = \sigma(W_f \cdot [h_{t-1}, x_t] + b_f) \ \text{Input gate:} & i_t = \sigma(W_i \cdot [h_{t-1}, x_t] + b_i) \ \text{Candidate:} & \tilde{g}t = \tanh(W_g \cdot [h_{t-1}, x_t] + b_g) \ \text{Output gate:} & o_t = \sigma(W_o \cdot [h_{t-1}, x_t] + b_o) \ \text{Update cell state:} & c_t = f_t \odot c{t-1} + i_t \odot \tilde{g}_t \ \text{Update hidden state:} & h_t = o_t \odot \tanh(c_t) \end{aligned} ] where (\odot) denotes element-wise multiplication (Hadamard product), and (\sigma) denotes the Sigmoid function.
Interpretation of the computation:
f_t ⊙ c_{t-1}: the forget gate decides how much historical memory to keep; close to 0 means forget, close to 1 means keepi_t ⊙ g_t: the input gate decides how much new information to write,g_tis the candidate new contento_t ⊙ tanh(c_t): the output gate decides what to extract from the cell state as the hidden state output
3. GRU Principles
3.1 Core Structure and the Two Gates
GRU merges LSTM's forget and input gates into an update gate, removes the separate cell state, and keeps only the hidden state, resulting in a simpler structure.
重置门(Reset Gate):决定忽略多少历史状态来计算候选隐藏状态
更新门(Update Gate):决定保留多少历史状态,写入多少新状态
3.2 Forward Calculation Formulas
[ \begin{aligned} \text{Input:} & x_t \text{(current time step input)}, h_{t-1} \text{(previous hidden state)} \ \text{Reset gate:} & r_t = \sigma(W_r \cdot [h_{t-1}, x_t] + b_r) \ \text{Update gate:} & z_t = \sigma(W_z \cdot [h_{t-1}, x_t] + b_z) \ \text{Candidate:} & \tilde{h}t = \tanh(W_h \cdot [r_t \odot h_{t-1}, x_t] + b_h) \ \text{Update hidden state:} & h_t = (1 - z_t) \odot h{t-1} + z_t \odot \tilde{h}_t \end{aligned} ]
Interpretation of the computation:
- Reset Gate
r_twhen close to 0, the candidate stateh̃_tbarely depends on history, equivalent to starting over - Update Gate
z_twhen close to 1, the new state relies more on the candidate value; when close to 0, more of the historical state is retained - GRU has no separate cell state and about 75% of LSTM's parameters
4. LSTM in PyTorch
This section details the parameters of nn.LSTM, input/output shapes, and hidden state initialization methods.
4.1 nn.LSTM Parameter Details
Example
import
torch
import
torch.
nn
as
nn
lstm
=
nn.
LSTM
(
input_size
=
64
,
Dimension of the input vector at each time step
hidden_size
=
128
,
Dimension of the hidden state (and cell state)
num_layers
=
2
,
Number of stacked layers, default is 1
bias
=
True
,
Whether to use bias terms, default True
batch_first
=
False
,
Whether batch is the first dimension in input/output shape, default False
dropout
=
0.0
,
Inter-layer dropout probability (only effective when num_layers > 1)
bidirectional
=
False
,
Whether to use a bidirectional LSTM, default False
proj_size
=
0
,
Projection layer dimension (LSTM with projection), default 0 means unused
)
Check the number of parameters
total_params
=
sum
(
p.
numel
(
)
for
p
in
lstm.
parameters
(
)
)
(
f
"LSTM parameter count: {total_params:,}"
)
approximately 197,632 when input_size=64, hidden_size=128, num_layers=2
Parameter count estimation formula (single layer, unidirectional):
[ \begin{aligned} \text{Parameters per layer} & = 4 \times (hidden_size \times input_size + hidden_size \times hidden_size + hidden_size) \ & = 4 \times hidden_size \times (input_size + hidden_size + 1) \end{aligned} ] where 4 corresponds to the four weight matrices: forget gate, input gate, candidate, output gate.
4.2 Input and Output Shapes
This is the most error-prone part of using LSTM and needs special attention batch_first the effect of the parameter.
Example
import
torch
import
torch.
nn
as
nn
-- batch_first=False (default) ------------------------
lstm
=
nn.
LSTM
(
input_size
=
32
,
hidden_size
=
64
,
batch_first
=
False
)
Input shape: (seq_len, batch_size, input_size)
seq_len
,
batch_size
,
input_size
=
10
,
4
,
32
x
=
torch.
randn
(
seq_len
,
batch_size
,
input_size
)
output
,
(
h_n
,
c_n
)
=
lstm
(
x
)
(
f
"output shape: {output.shape}"
)
torch.Size([10, 4, 64]) → (seq_len, batch_size, hidden_size)
Hidden state output at each time step
(
f
"h_n shape: {h_n.shape}"
)
torch.Size([1, 4, 64]) → (num_layers * num_directions, batch_size, hidden_size)
Hidden state of the last time step
(
f
"c_n shape: {c_n.shape}"
)
torch.Size([1, 4, 64]) -> same as h_n, cell state of the last time step
-- batch_first=True (recommended, more intuitive) ----
lstm_bf
=
nn.
LSTM
(
input_size
=
32
,
hidden_size
=
64
,
batch_first
=
True
)
Input shape: (batch_size, seq_len, input_size)
x
=
torch.
randn
(
batch_size
,
seq_len
,
input_size
)
output
,
(
h_n
,
c_n
)
=
lstm_bf
(
x
)
(
f
"output shape: {output.shape}"
)
torch.Size([4, 10, 64]) → (batch_size, seq_len, hidden_size)
(
f
"h_n shape: {h_n.shape}"
)
torch.Size([1, 4, 64]) → (num_layers, batch_size, hidden_size)
Note: the shape of h_n is not affected by batch_first
-- Output shapes of multi-layer bidirectional LSTM -----
lstm_bd
=
nn.
LSTM
(
input_size
=
32
,
hidden_size
=
64
,
num_layers
=
3
,
bidirectional
=
True
,
batch_first
=
True
)
x
=
torch.
randn
(
batch_size
,
seq_len
,
input_size
)
output
,
(
h_n
,
c_n
)
=
lstm_bd
(
x
)
(
f
"output shape: {output.shape}"
)
torch.Size([4, 10, 128])
hidden_size x 2 = 128 because of bidirectional concatenation
(
f
"h_n shape: {h_n.shape}"
)
torch.Size([6, 4, 64])
num_layers × num_directions = 3 × 2 = 6
Output shape summary:
| Variables | batch_first=False | batch_first=True |
|---|---|---|
output |
(seq_len, N, H * D) |
(N, seq_len, H * D) |
h_n |
(L * D, N, H) |
(L * D, N, H) |
c_n |
(L * D, N, H) |
(L * D, N, H) |
\(N\) = batch_size, \(H\) = hidden_size, \(L\) = num_layers, \(D\) = 2 (bidirectional) or 1 (unidirectional)
4.3 Hidden State Initialization
Example
import
torch
import
torch.
nn
as
nn
lstm
=
nn.
LSTM
(
input_size
=
32
,
hidden_size
=
64
,
num_layers
=
2
,
batch_first
=
True
)
batch_size
=
8
device
=
torch.
device
(
"cuda"
if
torch.
cuda
.
is_available
(
)
else
"cpu"
)
lstm
=
lstm.
to
(
device
)
Method 1: do not pass an initial state; PyTorch automatically uses all-zero initialization
x
=
torch.
randn
(
batch_size
,
10
,
32
)
.
to
(
device
)
output
,
(
h_n
,
c_n
)
=
lstm
(
x
)
Method 2: manually initialize to all zeros (equivalent to Method 1, but makes the intent explicit)
num_layers
,
num_directions
=
2
,
1
h_0
=
torch.
zeros
(
num_layers * num_directions
,
batch_size
,
64
)
.
to
(
device
)
c_0
=
torch.
zeros
(
num_layers * num_directions
,
batch_size
,
64
)
.
to
(
device
)
output
,
(
h_n
,
c_n
)
=
lstm
(
x
,
(
h_0
,
c_0
)
)
Method 3: stateful mode -- passing state across batches
Suitable for slicing very long sequences (language models, long text generation, etc.)
Need to call detach() to cut off the computation graph from the previous batch and prevent GPU memory leaks
h
,
c
=
h_0
,
c_0
for
batch_x
in
data_loader:
batch_x
=
batch_x.
to
(
device
)
output
,
(
h
,
c
)
=
lstm
(
batch_x
,
(
h
,
c
)
)
h
=
h.
detach
(
)
Cut off gradients, keep only the values
c
=
c.
detach
(
)
Method 4: use Xavier or normal distribution initialization (faster convergence in some scenarios)
def
init_hidden
(
lstm_module
,
batch_size
,
device
)
:
num_layers
=
lstm_module.
num_layers
hidden_size
=
lstm_module.
hidden_size
directions
=
2
if
lstm_module.
bidirectional
else
1
h
=
torch.
zeros
(
num_layers * directions
,
batch_size
,
hidden_size
,
device
=
device
)
c
=
torch.
zeros
(
num_layers * directions
,
batch_size
,
hidden_size
,
device
=
device
)
nn.
init
.
orthogonal_
(
h
)
Orthogonal initialization helps stabilize training
return
h
,
c
5. GRU in PyTorch
GRU's interface is almost identical to LSTM's, with the main difference being the absence of a cell state c.
5.1 nn.GRU Parameter Details
Example
import
torch.
nn
as
nn
gru
=
nn.
GRU
(
input_size
=
64
,
hidden_size
=
128
,
num_layers
=
2
,
bias
=
True
,
batch_first
=
True
,
Recommended to set to True
dropout
=
0.3
,
Inter-layer dropout
bidirectional
=
False
,
)
5.2 Basic Usage Example
Example
import
torch
import
torch.
nn
as
nn
gru
=
nn.
GRU
(
input_size
=
32
,
hidden_size
=
64
,
batch_first
=
True
)
batch_size
,
seq_len
=
8
,
10
x
=
torch.
randn
(
batch_size
,
seq_len
,
32
)
GRU returns only output and h_n, no c_n
output
,
h_n
=
gru
(
x
)
(
f
"output shape: {output.shape}"
)
torch.Size([8, 10, 64]) → (batch_size, seq_len, hidden_size)
(
f
"h_n shape: {h_n.shape}"
)
torch.Size([1, 8, 64]) → (num_layers, batch_size, hidden_size)
Take the output of the last time step (for tasks such as classification)
last_hidden
=
output
[
:
,
1
,
:
]
(batch_size, hidden_size)
Or equivalently:
last_hidden
=
h_n.
squeeze
(
0
)
(batch_size, hidden_size)
6. Variants of LSTM and GRU
This section introduces bidirectional, multi-layer stacked, and multi-layer structures with Dropout.
6.1 Bidirectional LSTM / GRU
Bidirectional models process information from both the forward and reverse directions of a sequence; the output at each time step contains past and future context, making them suitable for tasks requiring global context such as text classification and named entity recognition.
Example
import
torch
import
torch.
nn
as
nn
Bidirectional LSTM
bilstm
=
nn.
LSTM
(
input_size
=
32
,
hidden_size
=
64
,
num_layers
=
2
,
batch_first
=
True
,
bidirectional
=
True
,
Enable bidirectional
)
x
=
torch.
randn
(
8
,
10
,
32
)
output
,
(
h_n
,
c_n
)
=
bilstm
(
x
)
(
f
"output shape: {output.shape}"
)
torch.Size([8, 10, 128])
64 dimensions forward + 64 dimensions backward = 128 dimensions
(
f
"h_n shape: {h_n.shape}"
)
torch.Size([4, 8, 64])
num_layers(2) × num_directions(2) = 4
Separate the forward and backward final hidden states
Order of h_n: [forward layer0, backward layer0, forward layer1, backward layer1]
h_forward
=
h_n
[
2
,
:
,
:
]
(batch_size, hidden_size) forward final layer
h_backward
=
h_n
[
1
,
:
,
:
]
(batch_size, hidden_size) backward final layer
h_combined
=
torch.
cat
(
[
h_forward
,
h_backward
]
,
dim
=
1
)
(batch_size, 128)
Bidirectional GRU is used in exactly the same way
bigru
=
nn.
GRU
(
input_size
=
32
,
hidden_size
=
64
,
num_layers
=
2
,
batch_first
=
True
,
bidirectional
=
True
)
output
,
h_n
=
bigru
(
x
)
6.2 Multi-layer Stacking
Example
import
torch
import
torch.
nn
as
nn
3-layer stacked LSTM
deep_lstm
=
nn.
LSTM
(
input_size
=
32
,
hidden_size
=
128
,
num_layers
=
3
,
Stack 3 layers
batch_first
=
True
,
)
x
=
torch.
randn
(
8
,
20
,
32
)
output
,
(
h_n
,
c_n
)
=
deep_lstm
(
x
)
(
f
"output shape: {output.shape}"
)
torch.Size([8, 20, 128]) contains only the top layer's output
(
f
"h_n shape: {h_n.shape}"
)
torch.Size([3, 8, 128]) contains the final hidden state of each layer
Get the final hidden state of each layer
h_layer1
=
h_n
[
0
]
(batch_size, hidden_size) first layer
h_layer2
=
h_n
[
1
]
(batch_size, hidden_size) second layer
h_layer3
=
h_n
[
2
]
(batch_size, hidden_size) third layer (top layer)
6.3 Multi-layer Structures with Dropout
nn.LSTM The built-in dropout The parameter only applies between layers, not to the output of the last layer. To add Dropout after the last layer as well, you need to add it manually:
Example
import
torch
import
torch.
nn
as
nn
class
StackedLSTM
(
nn.
Module
)
:
"""
Multi-layer LSTM + inter-layer Dropout + output Dropout
"""
def
init
(
self
,
input_size
,
hidden_size
,
num_layers
,
num_classes
,
dropout
=
0.3
)
:
super
(
)
.
init
(
)
self
.
lstm
=
nn.
LSTM
(
input_size
=
input_size
,
hidden_size
=
hidden_size
,
num_layers
=
num_layers
,
batch_first
=
True
,
dropout
=
dropout
if
num_layers
1
else
0.0
,
dropout has no effect when num_layers=1; set it to 0 to avoid warnings
)
self
.
dropout
=
nn.
Dropout
(
dropout
)
Dropout after the last layer
self
.
fc
=
nn.
Linear
(
hidden_size
,
num_classes
)
def
forward
(
self
,
x
)
:
output
,
(
h_n
,
c_n
)
=
self
.
lstm
(
x
)
Take the hidden state of the last time step
last_output
=
output
[
:
,
1
,
:
]
(batch_size, hidden_size)
last_output
=
self
.
dropout
(
last_output
)
return
self
.
fc
(
last_output
)
model
=
StackedLSTM
(
input_size
=
64
,
hidden_size
=
128
,
num_layers
=
3
,
num_classes
=
5
,
dropout
=
0.3
)
x
=
torch.
randn
(
16
,
20
,
64
)
(
model
(
x
)
.
shape
)
torch.Size([16, 5])
7. Handling Variable-Length Sequences
In real tasks, sequences within the same batch usually have different lengths. PyTorch provides pack_padded_sequence and pad_packed_sequence to handle this, avoiding useless computation by LSTM on padding positions.
7.1 pack_padded_sequence
Example
import
torch
import
torch.
nn
as
nn
from
torch.
nn
.
utils
.
rnn
import
pack_padded_sequence
,
pad_packed_sequence
,
pad_sequence
Simulate variable-length sequences in a batch (sorted, from longest to shortest)
seq1
=
torch.
randn
(
5
,
32
)
Sequence length 5
seq2
=
torch.
randn
(
3
,
32
)
Sequence length 3
seq3
=
torch.
randn
(
2
,
32
)
Sequence length 2
pad_sequence automatically pads with zeros, aligning to the longest sequence
with batch_first=True the output shape is (batch_size, max_seq_len, input_size)
padded
=
pad_sequence
(
[
seq1
,
seq2
,
seq3
]
,
batch_first
=
True
,
padding_value
=
0.0
)
lengths
=
torch.
tensor
(
[
5
,
3
,
2
]
)
(
f
"shape after padding: {padded.shape}"
)
torch.Size([3, 5, 32])
pack_padded_sequence: compress padding and tell LSTM the true lengths
packed
=
pack_padded_sequence
(
padded
,
lengths
=
lengths
,
batch_first
=
True
,
enforce_sorted
=
True
,
Sequences must be sorted in descending order of length
enforce_sorted=False # allow any order (internally sorted automatically), recommended to set False
)
(
type
(
packed
)
)
7.2 pad_packed_sequence
Example
lstm
=
nn.
LSTM
(
input_size
=
32
,
hidden_size
=
64
,
batch_first
=
True
)
Pass the PackedSequence into LSTM
packed_output
,
(
h_n
,
c_n
)
=
lstm
(
packed
)
pad_packed_sequence: restore to a zero-padded tensor
output
,
output_lengths
=
pad_packed_sequence
(
packed_output
,
batch_first
=
True
)
(
f
"output shape after restoration: {output.shape}"
)
torch.Size([3, 5, 64]) → (batch_size, max_seq_len, hidden_size)
Outputs at padding positions are 0
(
f
"actual lengths of each sequence: {output_lengths}"
)
tensor([5, 3, 2])
7.3 Complete Variable-Length Sequence Processing Flow
Example
import
torch
import
torch.
nn
as
nn
from
torch.
nn
.
utils
.
rnn
import
pack_padded_sequence
,
pad_packed_sequence
class
LSTMClassifier
(
nn.
Module
)
:
def
init
(
self
,
vocab_size
,
embed_dim
,
hidden_size
,
num_classes
,
padding_idx
=
0
)
:
super
(
)
.
init
(
)
self
.
embedding
=
nn.
Embedding
(
vocab_size
,
embed_dim
,
padding_idx
=
padding_idx
)
self
.
lstm
=
nn.
LSTM
(
embed_dim
,
hidden_size
,
batch_first
=
True
)
self
.
fc
=
nn.
Linear
(
hidden_size
,
num_classes
)
def
forward
(
self
,
x
,
lengths
)
:
x: (batch_size, max_seq_len) -- word indices
embedded
=
self
.
embedding
(
x
)
(batch_size, max_seq_len, embed_dim)
package
packed
=
pack_padded_sequence
(
embedded
,
lengths.
cpu
(
)
,
batch_first
=
True
,
enforce_sorted
=
False
)
LSTM forward pass (skip padding positions)
packed_output
,
(
h_n
,
c_n
)
=
self
.
lstm
(
packed
)
Method 1: use the last layer's h_n as the sequence representation
last_hidden
=
h_n.
squeeze
(
0
)
(batch_size, hidden_size)
Method 2: after unpacking, take the output at the true last position of each sequence (equivalent to Method 1)
output, _ = pad_packed_sequence(packed_output, batch_first=True)
last_hidden = output[range(len(lengths)), lengths - 1, :]
return
self
.
fc
(
last_hidden
)
model
=
LSTMClassifier
(
vocab_size
=
10000
,
embed_dim
=
128
,
hidden_size
=
256
,
num_classes
=
5
)
Simulate a batch
batch_tokens
=
torch.
randint
(
1
,
10000
,
(
8
,
30
)
)
(batch_size=8, max_len=30)
batch_lengths
=
torch.
randint
(
5
,
31
,
(
8
,
)
)
True length of each sequence
output
=
model
(
batch_tokens
,
batch_lengths
)
(
output.
shape
)
torch.Size([8, 5])
8. Complete Practical Example: Text Sentiment Classification
Using IMDB movie review sentiment binary classification as an example, this shows the complete flow of processing text with a bidirectional LSTM:
Example
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
from
torch.
utils
.
data
import
Dataset
,
DataLoader
from
torch.
nn
.
utils
.
rnn
import
pack_padded_sequence
,
pad_sequence
from
torch.
optim
.
lr_scheduler
import
ReduceLROnPlateau
device
=
torch.
device
(
"cuda"
if
torch.
cuda
.
is_available
(
)
else
"cpu"
)
---- Model Definition -------------------------------------
class
BiLSTMClassifier
(
nn.
Module
)
:
"""
Bidirectional LSTM text classification model
Structure: Embedding -> BiLSTM -> Dropout -> FC
"""
def
init
(
self
,
vocab_size
,
embed_dim
,
hidden_size
,
num_layers
,
num_classes
,
dropout
=
0.5
,
padding_idx
=
0
)
:
super
(
)
.
init
(
)
self
.
embedding
=
nn.
Embedding
(
vocab_size
,
embed_dim
,
padding_idx
=
padding_idx
)
When using pre-trained word vectors:
self.embedding = nn.Embedding.from_pretrained(pretrained_vectors)
self
.
lstm
=
nn.
LSTM
(
input_size
=
embed_dim
,
hidden_size
=
hidden_size
,
num_layers
=
num_layers
,
batch_first
=
True
,
dropout
=
dropout
if
num_layers
1
else
0.0
,
bidirectional
=
True
,
)
self
.
dropout
=
nn.
Dropout
(
dropout
)
Bidirectional LSTM: concatenate the forward and backward final hidden states
self
.
fc
=
nn.
Linear
(
hidden_size *
2
,
num_classes
)
def
forward
(
self
,
x
,
lengths
)
:
x: (batch_size, max_seq_len)
embedded
=
self
.
dropout
(
self
.
embedding
(
x
)
)
packed
=
pack_padded_sequence
(
embedded
,
lengths.
cpu
(
)
,
batch_first
=
True
,
enforce_sorted
=
False
)
packed_output
,
(
h_n
,
c_n
)
=
self
.
lstm
(
packed
)
h_n: (num_layers * 2, batch_size, hidden_size)
Take the forward and backward hidden states of the last layer and concatenate them
h_forward
=
h_n
[
2
,
:
,
:
]
(batch_size, hidden_size)
h_backward
=
h_n
[
1
,
:
,
:
]
(batch_size, hidden_size)
h_combined
=
torch.
cat
(
[
h_forward
,
h_backward
]
,
dim
=
1
)
(batch_size, hidden_size * 2)
out
=
self
.
dropout
(
h_combined
)
return
self
.
fc
(
out
)
-- Custom Dataset ---------------------------------
class
TextDataset
(
Dataset
)
:
def
init
(
self
,
texts
,
labels
,
vocab
,
max_len
=
200
)
:
self
.
data
=
texts
self
.
labels
=
labels
self
.
vocab
=
vocab
self
.
max_len
=
max_len
def
len
(
self
)
:
return
len
(
self
.
data
)
def
getitem
(
self
,
idx
)
:
tokens
=
self
.
data
[
idx
]
[
:
self
.
max_len
]
ids
=
[
self
.
vocab
.
get
(
t
,
1
)
for
t
in
tokens
]
1 =
return
torch.
tensor
(
ids
,
dtype
=
torch.
long
)
,
torch.
tensor
(
self
.
labels
[
idx
]
)
def
collate_fn
(
batch
)
:
"""Custom collate: pad variable-length sequences and record true lengths"""
sequences
,
labels
=
zip
(
*batch
)
lengths
=
torch.
tensor
(
[
len
(
s
)
for
s
in
sequences
]
)
padded
=
pad_sequence
(
sequences
,
batch_first
=
True
,
padding_value
=
0
)
labels
=
torch.
stack
(
labels
)
return
padded
,
lengths
,
labels
-- Training and evaluation functions ---------------
def
train_epoch
(
model
,
loader
,
optimizer
,
criterion
)
:
model.
train
(
)
total_loss
,
correct
=
0.0
,
0
for
texts
,
lengths
,
labels
in
loader:
texts
,
labels
=
texts.
to
(
device
)
,
labels.
to
(
device
)
optimizer.
zero_grad
(
)
outputs
=
model
(
texts
,
lengths
)
loss
=
criterion
(
outputs
,
labels
)
loss.
backward
(
)
Gradient clipping: prevent RNN gradient explosion
nn.
utils
.
clip_grad_norm_
(
model.
parameters
(
)
,
max_norm
=
1.0
)
optimizer.
step
(
)
total_loss +
=
loss.
item
(
)
len
(
labels
)
correct +
=
(
outputs.
argmax
(
1
)
==
labels
)
.
sum
(
)
.
item
(
)
n
=
len
(
loader.
dataset
)
return
total_loss / n
,
correct / n
def
eval_epoch
(
model
,
loader
,
criterion
)
:
model.
eval
(
)
total_loss
,
correct
=
0.0
,
0
with
torch.
no_grad
(
)
:
for
texts
,
lengths
,
labels
in
loader:
texts
,
labels
=
texts.
to
(
device
)
,
labels.
to
(
device
)
outputs
=
model
(
texts
,
lengths
)
loss
=
criterion
(
outputs
,
labels
)
total_loss +
=
loss.
item
(
)
len
(
labels
)
correct +
=
(
outputs.
argmax
(
1
)
==
labels
)
.
sum
(
)
.
item
(
)
n
=
len
(
loader.
dataset
)
return
total_loss / n
,
correct / n
---- Initialization and Training ----
VOCAB_SIZE
=
50000
EMBED_DIM
=
128
HIDDEN_SIZE
=
256
NUM_LAYERS
=
2
NUM_CLASSES
=
2
DROPOUT
=
0.5
EPOCHS
=
15
model
=
BiLSTMClassifier
(
VOCAB_SIZE
,
EMBED_DIM
,
HIDDEN_SIZE
,
NUM_LAYERS
,
NUM_CLASSES
,
DROPOUT
)
.
to
(
device
)
criterion
=
nn.
CrossEntropyLoss
(
)
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
1e-3
)
scheduler
=
ReduceLROnPlateau
(
optimizer
,
mode
=
"max"
,
patience
=
3
,
factor
=
0.5
)
best_acc
=
0.0
for
epoch
in
range
(
1
,
EPOCHS +
1
)
:
train_loss
,
train_acc
=
train_epoch
(
model
,
train_loader
,
optimizer
,
criterion
)
val_loss
,
val_acc
=
eval_epoch
(
model
,
val_loader
,
criterion
)
scheduler.
step
(
val_acc
)
(
f
"Epoch {epoch:2d}/{EPOCHS} | "
f
"Train Loss: {train_loss:.4f}, Acc: {train_acc:.4f} | "
f
"Val Loss: {val_loss:.4f}, Acc: {val_acc:.4f}"
)
if
val_acc
best_acc:
best_acc
=
val_acc
torch.
save
(
model.
state_dict
(
)
,
"best_bilstm.pth"
)
(
f
" -> save best model, Val Acc: {best_acc:.4f}"
)
9. Complete Practical Example: Time Series Prediction
Using multi-step time series prediction as an example, use LSTM to predict values for the next N steps:
Example
import
torch
import
torch.
nn
as
nn
import
torch.
optim
as
optim
import
numpy
as
np
from
torch.
utils
.
data
import
Dataset
,
DataLoader
device
=
torch.
device
(
"cuda"
if
torch.
cuda
.
is_available
(
)
else
"cpu"
)
-- Sliding window Dataset --------------------------
class
TimeSeriesDataset
(
Dataset
)
:
"""
Sliding window slicing of the time series
Input: past input_len steps
Target: future output_len steps
"""
def
init
(
self
,
series
,
input_len
,
output_len
)
:
self
.
data
=
torch.
tensor
(
series
,
dtype
=
torch.
float32
)
self
.
input_len
=
input_len
self
.
output_len
=
output_len
def
len
(
self
)
:
return
len
(
self
.
data
)
self
.
input_len
self
.
output_len
1
def
getitem
(
self
,
idx
)
:
x
=
self
.
data
[
idx : idx +
self
.
input_len
]
y
=
self
.
data
[
idx +
self
.
input_len
: idx +
self
.
input_len
self
.
output_len
]
return
x.
unsqueeze
(
1
)
,
y
x: (input_len, 1), y: (output_len,)
---- Model Definition -------------------------------------
class
LSTMForecaster
(
nn.
Module
)
:
"""
Multi-step time series prediction model
Structure: LSTM -> Dropout -> FC
"""
def
init
(
self
,
input_size
,
hidden_size
,
num_layers
,
output_len
,
dropout
=
0.2
)
:
super
(
)
.
init
(
)
self
.
lstm
=
nn.
LSTM
(
input_size
=
input_size
,
hidden_size
=
hidden_size
,
num_layers
=
num_layers
,
batch_first
=
True
,
dropout
=
dropout
if
num_layers
1
else
0.0
,
)
self
.
dropout
=
nn.
Dropout
(
dropout
)
self
.
fc
=
nn.
Linear
(
hidden_size
,
output_len
)
def
forward
(
self
,
x
)
:
x: (batch_size, input_len, input_size)
output
,
(
h_n
,
c_n
)
=
self
.
lstm
(
x
)
Take the output of the last time step
last
=
output
[
:
,
1
,
:
]
(batch_size, hidden_size)
last
=
self
.
dropout
(
last
)
return
self
.
fc
(
last
)
(batch_size, output_len)
-- Data preparation (using a sine wave as example) --
t
=
np.
linspace
(
0
,
200
,
10000
)
series
=
np.
sin
(
t
)
0.1
- np.
random
.
randn
(
len
(
t
)
)
INPUT_LEN
=
60
Use the past 60 steps
OUTPUT_LEN
=
10
Predict the next 10 steps
split
=
int
(
len
(
series
)
0.8
)
train_data
=
series
[
:split
]
val_data
=
series
[
split:
]
train_dataset
=
TimeSeriesDataset
(
train_data
,
INPUT_LEN
,
OUTPUT_LEN
)
val_dataset
=
TimeSeriesDataset
(
val_data
,
INPUT_LEN
,
OUTPUT_LEN
)
train_loader
=
DataLoader
(
train_dataset
,
batch_size
=
64
,
shuffle
=
True
)
val_loader
=
DataLoader
(
val_dataset
,
batch_size
=
64
,
shuffle
=
False
)
-- Training ----------------------------------------
model
=
LSTMForecaster
(
input_size
=
1
,
hidden_size
=
128
,
num_layers
=
2
,
output_len
=
OUTPUT_LEN
)
.
to
(
device
)
criterion
=
nn.
MSELoss
(
)
optimizer
=
optim.
Adam
(
model.
parameters
(
)
,
lr
=
1e-3
)
def
train_epoch_ts
(
model
,
loader
,
optimizer
,
criterion
)
:
model.
train
(
)
total_loss
=
0.0
for
x
,
y
in
loader:
x
,
y
=
x.
to
(
device
)
,
y.
to
(
device
)
optimizer.
zero_grad
(
)
pred
=
model
(
x
)
loss
=
criterion
(
pred
,
y
)
loss.
backward
(
)
nn.
utils
.
clip_grad_norm_
(
model.
parameters
(
)
,
max_norm
=
1.0
)
optimizer.
step
(
)
total_loss +
=
loss.
item
(
)
- x.
size
(
0
)
return
total_loss /
len
(
loader.
dataset
)
def
eval_epoch_ts
(
model
,
loader
,
criterion
)
:
model.
eval
(
)
total_loss
=
0.0
with
torch.
no_grad
(
)
:
for
x
,
y
in
loader:
x
,
y
=
x.
to
(
device
)
,
y.
to
(
device
)
pred
=
model
(
x
)
total_loss +
=
criterion
(
pred
,
y
)
.
item
(
)
- x.
size
(
0
)
return
total_loss /
len
(
loader.
dataset
)
for
epoch
in
range
(
1
,
31
)
:
train_loss
=
train_epoch_ts
(
model
,
train_loader
,
optimizer
,
criterion
)
val_loss
=
eval_epoch_ts
(
model
,
val_loader
,
criterion
)
(
f
"Epoch {epoch:2d}/30 | Train MSE: {train_loss:.6f} | Val MSE: {val_loss:.6f}"
)
-- Multi-step recursive prediction (alternative strategy) --
def
recursive_forecast
(
model
,
init_sequence
,
steps
,
device
)
:
"""
Recursive prediction: predict one step at a time, append the predicted value to the sequence, then predict the next step
Suitable for single-step prediction models with output_len=1
"""
model.
eval
(
)
sequence
=
list
(
init_sequence
)
predictions
=
[
]
with
torch.
inference_mode
(
)
:
for
_
in
range
(
steps
)
:
x
=
torch.
tensor
(
sequence
[
-INPUT_LEN:
]
,
dtype
=
torch.
float32
)
x
=
x.
unsqueeze
(
0
)
.
unsqueeze
(
1
)
.
to
(
device
)
(1, input_len, 1)
pred
=
model
(
x
)
.
item
(
)
predictions.
append
(
pred
)
sequence.
append
(
pred
)
return
predictions
10. LSTM vs GRU: Comparison and Selection
This section compares the structural differences between LSTM and GRU and provides selection advice.
Structural Comparison
| Comparison Item | LSTM | GRU |
|---|---|---|
| Number of gates | 3 (forget, input, output) | 2 (reset, update) |
| State vectors | Cell state + hidden state | Only hidden state |
| Parameter count (same hidden_size) | Baseline | about 75% |
| Training Speed | Slower | Faster |
| Performance on long sequences | usually better | comparable |
| Performance on short sequences | similar | similar |
| Implementation complexity | Higher | Lower |
Selection recommendations
数据量小、训练资源有限
-> 优先选 GRU,参数少,不容易过拟合,训练快
序列较长(> 100 步)、长距离依赖重要
-> 优先选 LSTM,细胞状态更擅长保留远期信息
需要快速实验和基线对比
-> 先用 GRU,效果差再换 LSTM
任务对准确率要求极高,有充足数据
-> 两者都试,结合交叉验证选择
2020 年后的新项目
-> 考虑 Transformer 架构(BERT、GPT),在大数据量下通常优于 LSTM/GRU
LSTM/GRU 仍在边缘设备、低延迟推理、数据量较小的场景中有优势
Common Issues Quick Reference
| Problem | Reason | Solution |
|---|---|---|
| Training loss not decreasing | Learning rate too large or gradient explosion | Lower the learning rate; add gradient clipping clip_grad_norm_ |
| Validation loss much higher than training loss | Overfitting | Increase Dropout; reduce the number of layers or hidden_size |
| Poor predictions at the end of sequences | Vanishing Gradient | Increase the number of layers; use a bidirectional structure; consider attention mechanisms |
| Excessive GPU memory usage | Sequences too long or batch too large | Reduce seq_len or batch_size; use gradient checkpointing |
| Abnormal loss in stateful training | State passed across batches not detached | Call after each batch h.detach_() |
| Wrong concatenation dimension in bidirectional LSTM | Misunderstanding h_n index order | Using h_n[-2](forward) and h_n[-1](backward) |
| PackedSequence errors | Sequence lengths not sorted in descending order | Settings enforce_sorted=False |
| batch_first confusion | Forgetting to set it consistently | Recommended to use consistently throughout batch_first=True |