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

PyTorch Recurrent Neural Networks

PyTorch Recurrent Neural Networks (RNN)

Recurrent Neural Networks (RNN) are a class of neural network architectures designed for processing sequential data. They can capture dynamic information in time series or ordered data and handle sequential data such as text, time series, or audio.

RNNs are widely used in tasks such as natural language processing (NLP), speech recognition, and time-series forecasting.

The key feature of an RNN is its ability to maintain a hidden state, allowing the network to remember information from previous time steps, which is crucial for processing sequential data.

Basic structure of an RNN

In a traditional feedforward neural network, data flows from the input layer to the output layer, whereas in an RNN, data not only flows through the network layers but also propagates to the current hidden state at each time step, thereby carrying previous information to the next time step.

Hidden State: An RNN uses the hidden state to remember information in the sequence.

The hidden state is computed from the previous time step's hidden state and the current input together.

The structure of a recurrent unit is as follows:

Formula:

[ h_t = f(W_{hh}h_{t-1} + W_{xh}x_t + b_h) ]

Output: The output of an RNN depends not only on the current input but also on the history of the hidden state.

Formula:

[ y_t = W_{hy}h_t + b_y ]

How RNNs process sequential data

The unfolded view of a Recurrent Neural Network (RNN) processing sequential data is as follows:

An RNN is a neural network for processing sequential data. It processes each element of a sequence through recurrent connections and passes information at each time step. The following explains each part of the figure:

- `U`: the weight matrix from input to hidden state, used to convert the input `Xt` into part of the hidden state. - `W`: the weight matrix from hidden state to hidden state, used to convert the previous time step's hidden state `ht-1` into part of the current time step's hidden state. - `V`: the weight matrix from hidden state to output, used to convert the hidden state `ht` into the output `Yt`.

RNN basics in PyTorch

In PyTorch, RNNs can be used to build complex sequence models.

PyTorch provides several RNN modules, including:

When using the RNN class, you need to specify the input dimension, the hidden layer dimension, and other hyperparameters.

PyTorch example: implementing a simple RNN

The following is a simple PyTorch implementation example that uses an RNN model to process sequential data and perform classification.

1. Import the necessary libraries

Example

import

torch

import

torch.

nn

as

nn

import

torch.

optim

as

optim

from

torch.

utils

.

data

import

DataLoader

,

TensorDataset

import

numpy

as

np

** 2. Define the RNN model**

Example

class

SimpleRNN

(

nn.

Module

)

:

   

def

init

(

self

,

input_size

,

hidden_size

,

output_size

)

:

       

super

(

SimpleRNN

,

self

)

.

init

(

)

       

Define the RNN layer

       

self

.

rnn

=

nn.

RNN

(

input_size

,

hidden_size

,

batch_first

=

True

)

       

Define the fully connected layers

       

self

.

fc

=

nn.

Linear

(

hidden_size

,

output_size

)

   

def

forward

(

self

,

x

)

:

       

x: (batch_size, seq_len, input_size)

        out

,

_

=

self

.

rnn

(

x

)

 

out: (batch_size, seq_len, hidden_size)

       

Take the output of the last time step of the sequence as the model's output

        out

=

out

[

:

,

1

,

:

]

 

(batch_size, hidden_size)

        out

=

self

.

fc

(

out

)

 

Fully connected layer

       

return

out

3. Create training data

To train the RNN, we generate some random sequence data. Here the goal is to use the last value of each sequence as the classification target.

Example

Generate some random sequence data

num_samples

=

1000

seq_len

=

10

input_size

=

5

output_size

=

2

 

Assume a binary classification problem

Randomly generate input data (batch_size, seq_len, input_size)

X

=

torch.

randn

(

num_samples

,

seq_len

,

input_size

)

Randomly generate target labels (batch_size, output_size)

Y

=

torch.

randint

(

0

,

output_size

,

(

num_samples

,

)

)

Create a data loader

dataset

=

TensorDataset

(

X

,

Y

)

train_loader

=

DataLoader

(

dataset

,

batch_size

=

32

,

shuffle

=

True

)

4. Define the loss function and optimizer

Example

Model instantiation

model

=

SimpleRNN

(

input_size

=

input_size

,

hidden_size

=

64

,

output_size

=

output_size

)

Define the loss function and optimizer

criterion

=

nn.

CrossEntropyLoss

(

)

 

Multi-class cross-entropy loss

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

0.001

)

5. Train the model

Example

num_epochs

=

10

for

epoch

in

range

(

num_epochs

)

:

    model.

train

(

)

 

Set the model to training mode

    total_loss

=

0

    correct

=

0

    total

=

0

   

for

inputs

,

labels

in

train_loader:

       

Forward propagation

        outputs

=

model

(

inputs

)

        loss

=

criterion

(

outputs

,

labels

)

       

Backpropagation and optimization

        optimizer.

zero_grad

(

)

        loss.

backward

(

)

        optimizer.

step

(

)

        total_loss +

=

loss.

item

(

)

       

Compute accuracy

        _

,

predicted

=

torch.

max

(

outputs

,

1

)

        total +

=

labels.

size

(

0

)

        correct +

=

(

predicted

==

labels

)

.

sum

(

)

.

item

(

)

    accuracy

=

100

   

print

(

f

"Epoch [{epoch+1}/{num_epochs}], Loss: {total_loss / len(train_loader):.4f}, Accuracy: {accuracy:.2f}%"

)

6. Test the model

After training, we can evaluate the model's performance on the test set.

Example

Test the model

model.

eval

(

)

 

Set the model to evaluation mode

with

torch.

no_grad

(

)

:

    total

=

0

    correct

=

0

   

for

inputs

,

labels

in

train_loader:

        outputs

=

model

(

inputs

)

        _

,

predicted

=

torch.

max

(

outputs

,

1

)

        total +

=

labels.

size

(

0

)

        correct +

=

(

predicted

==

labels

)

.

sum

(

)

.

item

(

)

    accuracy

=

100

   

print

(

f

"Test Accuracy: {accuracy:.2f}%"

)

** 7. The complete code is as follows:**

Example

import

torch

import

torch.

nn

as

nn

import

torch.

optim

as

optim

import

matplotlib.

pyplot

as

plt

import

numpy

as

np

Dataset: character sequence prediction (Hello -> Elloh)

char_set

=

list

(

"hello"

)

char_to_idx

=

{

c: i

for

i

,

c

in

enumerate

(

char_set

)

}

idx_to_char

=

{

i: c

for

i

,

c

in

enumerate

(

char_set

)

}

Data preparation

input_str

=

"hello"

target_str

=

"elloh"

input_data

=

[

char_to_idx

[

c

]

for

c

in

input_str

]

target_data

=

[

char_to_idx

[

c

]

for

c

in

target_str

]

Convert to one-hot encoding

input_one_hot

=

np.

eye

(

len

(

char_set

)

)

[

input_data

]

Convert to a PyTorch Tensor

inputs

=

torch.

tensor

(

input_one_hot

,

dtype

=

torch.

float32

)

targets

=

torch.

tensor

(

target_data

,

dtype

=

torch.

long

)

Model hyperparameters

input_size

=

len

(

char_set

)

hidden_size

=

8

output_size

=

len

(

char_set

)

num_epochs

=

200

learning_rate

=

0.1

Define the RNN model

class

RNNModel

(

nn.

Module

)

:

   

def

init

(

self

,

input_size

,

hidden_size

,

output_size

)

:

       

super

(

RNNModel

,

self

)

.

init

(

)

       

self

.

rnn

=

nn.

RNN

(

input_size

,

hidden_size

,

batch_first

=

True

)

       

self

.

fc

=

nn.

Linear

(

hidden_size

,

output_size

)

   

def

forward

(

self

,

x

,

hidden

)

:

        out

,

hidden

=

self

.

rnn

(

x

,

hidden

)

        out

=

self

.

fc

(

out

)

 

Apply the fully connected layer

       

return

out

,

hidden

model

=

RNNModel

(

input_size

,

hidden_size

,

output_size

)

Define the loss function and optimizer

criterion

=

nn.

CrossEntropyLoss

(

)

optimizer

=

optim.

Adam

(

model.

parameters

(

)

,

lr

=

learning_rate

)

Train the RNN

losses

=

[

]

hidden

=

None

 

Initial hidden state is None

for

epoch

in

range

(

num_epochs

)

:

    optimizer.

zero_grad

(

)

   

Forward propagation

    outputs

,

hidden

=

model

(

inputs.

unsqueeze

(

0

)

,

hidden

)

    hidden

=

hidden.

detach

(

)

 

Prevent exploding gradients

   

Compute the loss

    loss

=

criterion

(

outputs.

view

(

1

,

output_size

)

,

targets

)

    loss.

backward

(

)

    optimizer.

step

(

)

    losses.

append

(

loss.

item

(

)

)

   

if

(

epoch +

1

)

%

20

==

0

:

       

print

(

f

"Epoch [{epoch + 1}/{num_epochs}], Loss: {loss.item():.4f}"

)

Test the RNN

with

torch.

no_grad

(

)

:

    test_hidden

=

None

    test_output

,

_

=

model

(

inputs.

unsqueeze

(

0

)

,

test_hidden

)

    predicted

=

torch.

argmax

(

test_output

,

dim

=

2

)

.

squeeze

(

)

.

numpy

(

)

   

print

(

"Input sequence: "

,

''

.

join

(

[

idx_to_char

[

i

]

for

i

in

input_data

]

)

)

   

print

(

"Predicted sequence: "

,

''

.

join

(

[

idx_to_char

[

i

]

for

i

in

predicted

]

)

)

Code analysis:

  1. Data preparation:

  2. Use a character sequence helloand convert it to one-hot encoding.
  3. The target sequence is elloh, that is, rotated one character to the right.
  4. - Use the character sequence `hello` and convert it to one-hot encoding. - The target sequence is `elloh`, that is, rotated one character to the right.
    1. Model construction:

    2. Use torch.nn.RNN Create a recurrent neural network.
    3. Add a fully connected layer torch.nn.Linear to map the hidden state to the output.
    4. - Use `torch.nn.RNN` to create the recurrent neural network. - Add a fully connected layer `torch.nn.Linear` to map the hidden state to the output.
      1. Training part:

      2. Compute the loss and backpropagate in each epoch.
      3. The hidden state is passed through hidden.detach() to prevent exploding gradients.
      4. - Compute the loss and backpropagate in each epoch. - Pass the hidden state through `hidden.detach()` to prevent exploding gradients.
        1. Testing part:

        2. The model outputs the predicted characters.
        3. - The model outputs the predicted characters.
          1. Visualization:

          2. Plot the trend of training loss with Matplotlib.
          3. - Plot the trend of training loss with Matplotlib.

            Assuming your model is well trained, the output might look like this:

            Epoch [20/200], Loss: 0.0013
            
            Epoch [40/200], Loss: 0.0003
            
            Epoch [60/200], Loss: 0.0002
            
            Epoch [80/200], Loss: 0.0001
            
            Epoch [100/200], Loss: 0.0001
            
            Epoch [120/200], Loss: 0.0001
            
            Epoch [140/200], Loss: 0.0001
            
            Epoch [160/200], Loss: 0.0001
            
            Epoch [180/200], Loss: 0.0001
            
            Epoch [200/200], Loss: 0.0001
            
            Input sequence:  hello
            
            

            From the results, the plot shows the loss gradually decreasing, indicating effective model training.

            8. Visualization code:

            Example

            import

            torch

            import

            torch.

            nn

            as

            nn

            import

            torch.

            optim

            as

            optim

            import

            matplotlib.

            pyplot

            as

            plt

            import

            numpy

            as

            np

            Dataset: character sequence prediction (Hello -> Elloh)

            char_set

            =

            list

            (

            "hello"

            )

            char_to_idx

            =

            {

            c: i

            for

            i

            ,

            c

            in

            enumerate

            (

            char_set

            )

            }

            idx_to_char

            =

            {

            i: c

            for

            i

            ,

            c

            in

            enumerate

            (

            char_set

            )

            }

            Data preparation

            input_str

            =

            "hello"

            target_str

            =

            "elloh"

            input_data

            =

            [

            char_to_idx

            [

            c

            ]

            for

            c

            in

            input_str

            ]

            target_data

            =

            [

            char_to_idx

            [

            c

            ]

            for

            c

            in

            target_str

            ]

            Convert to one-hot encoding

            input_one_hot

            =

            np.

            eye

            (

            len

            (

            char_set

            )

            )

            [

            input_data

            ]

            Convert to a PyTorch Tensor

            inputs

            =

            torch.

            tensor

            (

            input_one_hot

            ,

            dtype

            =

            torch.

            float32

            )

            targets

            =

            torch.

            tensor

            (

            target_data

            ,

            dtype

            =

            torch.

            long

            )

            Model hyperparameters

            input_size

            =

            len

            (

            char_set

            )

            hidden_size

            =

            8

            output_size

            =

            len

            (

            char_set

            )

            num_epochs

            =

            200

            learning_rate

            =

            0.1

            Define the RNN model

            class

            RNNModel

            (

            nn.

            Module

            )

            :

               

            def

            init

            (

            self

            ,

            input_size

            ,

            hidden_size

            ,

            output_size

            )

            :

                   

            super

            (

            RNNModel

            ,

            self

            )

            .

            init

            (

            )

                   

            self

            .

            rnn

            =

            nn.

            RNN

            (

            input_size

            ,

            hidden_size

            ,

            batch_first

            =

            True

            )

                   

            self

            .

            fc

            =

            nn.

            Linear

            (

            hidden_size

            ,

            output_size

            )

               

            def

            forward

            (

            self

            ,

            x

            ,

            hidden

            )

            :

                    out

            ,

            hidden

            =

            self

            .

            rnn

            (

            x

            ,

            hidden

            )

                    out

            =

            self

            .

            fc

            (

            out

            )

             

            Apply the fully connected layer

                   

            return

            out

            ,

            hidden

            model

            =

            RNNModel

            (

            input_size

            ,

            hidden_size

            ,

            output_size

            )

            Define the loss function and optimizer

            criterion

            =

            nn.

            CrossEntropyLoss

            (

            )

            optimizer

            =

            optim.

            Adam

            (

            model.

            parameters

            (

            )

            ,

            lr

            =

            learning_rate

            )

            Train the RNN

            losses

            =

            [

            ]

            hidden

            =

            None

             

            Initial hidden state is None

            for

            epoch

            in

            range

            (

            num_epochs

            )

            :

                optimizer.

            zero_grad

            (

            )

               

            Forward propagation

                outputs

            ,

            hidden

            =

            model

            (

            inputs.

            unsqueeze

            (

            0

            )

            ,

            hidden

            )

                hidden

            =

            hidden.

            detach

            (

            )

             

            Prevent exploding gradients

               

            Compute the loss

                loss

            =

            criterion

            (

            outputs.

            view

            (

            1

            ,

            output_size

            )

            ,

            targets

            )

                loss.

            backward

            (

            )

                optimizer.

            step

            (

            )

                losses.

            append

            (

            loss.

            item

            (

            )

            )

               

            if

            (

            epoch +

            1

            )

            %

            20

            ==

            0

            :

                   

            print

            (

            f

            "Epoch [{epoch + 1}/{num_epochs}], Loss: {loss.item():.4f}"

            )

            Test the RNN

            with

            torch.

            no_grad

            (

            )

            :

                test_hidden

            =

            None

                test_output

            ,

            _

            =

            model

            (

            inputs.

            unsqueeze

            (

            0

            )

            ,

            test_hidden

            )

                predicted

            =

            torch.

            argmax

            (

            test_output

            ,

            dim

            =

            2

            )

            .

            squeeze

            (

            )

            .

            numpy

            (

            )

               

            print

            (

            "Input sequence: "

            ,

            ''

            .

            join

            (

            [

            idx_to_char

            [

            i

            ]

            for

            i

            in

            input_data

            ]

            )

            )

               

            print

            (

            "Predicted sequence: "

            ,

            ''

            .

            join

            (

            [

            idx_to_char

            [

            i

            ]

            for

            i

            in

            predicted

            ]

            )

            )

            Visualize the loss

            plt.

            plot

            (

            losses

            ,

            label

            =

            "Training Loss"

            )

            plt.

            xlabel

            (

            "Epoch"

            )

            plt.

            ylabel

            (

            "Loss"

            )

            plt.

            title

            (

            "RNN Training Loss Over Epochs"

            )

            plt.

            legend

            (

            )

            plt.

            show

            (

            )

            After running, the displayed image is as follows: