Building a Basic RNN Model with PyTorch

Introduction to Building a Basic RNN Model

Welcome to the next step in your journey of mastering Recurrent Neural Networks (RNNs) for time series analysis. In the previous lesson, you learned how to prepare time series data for RNNs by normalizing it and converting it into sequences. This foundation is crucial as we now move on to building and evaluating a basic RNN model. In this lesson, you will learn how to define, train, and evaluate a simple RNN model using PyTorch. By the end of this lesson, you will be able to implement a basic RNN model to predict time series values and assess its performance.

Defining the RNN Model

Let's start by defining a basic RNN model. We will use PyTorch, which is a powerful tool for building neural networks. The model will consist of an RNN layer, followed by a Linear layer. The RNN layer is responsible for processing the sequences of data, while the Linear layer outputs the prediction.

Here's how you can define the model:

Python
import torch
import torch.nn as nn

class SimpleRNNModel(nn.Module):
    def __init__(self, input_size, hidden_size, output_size):
        super(SimpleRNNModel, self).__init__()
        self.rnn = nn.RNN(input_size, hidden_size, batch_first=True)
        self.linear = nn.Linear(hidden_size, output_size)

    def forward(self, x):
        out, _ = self.rnn(x)
        out = self.linear(out[:, -1, :])  # Take the last output of the sequence
        return out

# Define RNN model
input_size = 1
hidden_size = 10
output_size = 1
model = SimpleRNNModel(input_size, hidden_size, output_size)

In this code, we define a class SimpleRNNModel that subclasses nn.Module. The model consists of an RNN layer with 10 hidden units and a Linear layer to produce the final output. The forward method defines the forward pass of the model, where we take the last output of the RNN sequence to pass through the Linear layer.

Splitting the Data

For time series data, it's important to split the data chronologically to avoid data leakage. This means using the earlier part of the series for training and the later part for testing.

Here's how you can split the data:

Python
# Determine split index
split_idx = int(len(X) * 0.8)

# Chronological split
X_train, X_test = X[:split_idx], X[split_idx:]
y_train, y_test = y[:split_idx], y[split_idx:]

In this code, we use the first 80% of the data for training and the remaining 20% for testing, preserving the temporal order of the time series. This approach ensures that the model is always tested on data points that occur after those it was trained on, which is essential for time series forecasting.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal