Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PyTorch torch.nn.LSTM function

PyTorch torch.nn.LSTM function

PyTorch torch.nn Reference Manual 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/Output

Inputs:

Output:


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

)

print

(

"Input shape:"

,

input_tensor.

shape

)

print

(

"Output shape:"

,

output.

shape

)

     

(4, 10, 512)

print

(

"Hidden state shape:"

,

h_n.

shape

)

   

(2, 4, 512)

print

(

"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

)

print

(

"Bidirectional LSTM output shape:"

,

output.

shape

)

 

(4, 10, 512) = 256*2

print

(

"Hidden state shape:"

,

h_n.

shape

)

           

(4, 4, 256) = 2 layers * 2 directions

print

(

"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

)

)

print

(

"Done using a custom initial state"

)

print

(

"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

)

print

(

"Model structure:"

)

print

(

model

)

print

(

"nInput shape:"

,

input_ids.

shape

)

print

(

"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

)

print

(

"4-layer LSTM output shape:"

,

output.

shape

)

print

(

"Hidden state shape (4 layers):"

,

h_n.

shape

)

print

(

"Cell state shape (4 layers):"

,

c_n.

shape

)


LSTM Gate Concepts

LSTM controls the flow of information through three gates:


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:

Tip: When using bidirectional=True, the output dimension becomes hidden_size * 2.


PyTorch torch.nn Reference Manual PyTorch torch.nn Reference Manual