DEV Community

Cover image for Recurrent Neural Networks (RNN): A Practical Guide with Python
nuz14
nuz14

Posted on

Recurrent Neural Networks (RNN): A Practical Guide with Python

Introduction

In machine learning, many problems involve data that comes in a sequence. Examples include sentences, stock prices, weather records, speech, and video.

Traditional neural networks process each input independently. However, they do not naturally remember information from previous inputs.

This is where Recurrent Neural Networks (RNNs) become useful.

RNNs are a type of neural network designed to work with sequential data. They use information from previous steps to help understand the current input.

In this article, we will understand how RNNs work, explore their applications, and build a simple RNN model using Python and TensorFlow.

1. What Is a Recurrent Neural Network?

A Recurrent Neural Network is a type of artificial neural network that processes information one step at a time while maintaining information from previous steps.

Unlike a traditional neural network, an RNN has a memory-like mechanism called a hidden state.

The hidden state carries information from earlier steps in a sequence.

For example, consider this sentence:

"The weather is very cold today."

To understand the sentence, a model may need to remember earlier words while processing later words.

An RNN processes the words in order and uses information from previous words to understand the current one.

2. How Does an RNN Work?

An RNN processes sequential data in a series of steps.

At each step, it:

  1. Receives the current input.
  2. Uses information from the previous step.
  3. Updates its hidden state.
  4. Produces an output.

For example, when processing a sentence, the RNN reads the first word, then the second word, and continues until it reaches the final word.

The information from earlier words is carried forward through the hidden state.

This allows the network to learn patterns in sequential data.

3. Applications of RNNs

RNNs are useful in tasks where the order of information matters.

Some common applications include:

  • Text generation: Predicting the next word in a sentence.
  • Sentiment analysis: Understanding whether a review is positive or negative.
  • Language translation: Processing sentences in one language to generate another.
  • Speech recognition: Converting spoken words into text.
  • Time-series forecasting: Predicting future values using previous observations.
  • Weather prediction: Learning patterns from historical weather data.

4. Types of RNN Architectures

RNNs can be designed in different ways depending on the problem.

One-to-One

One input produces one output. This is similar to a traditional neural network.

One-to-Many

One input produces a sequence of outputs.

Example: Generating a caption for an image.

Many-to-One

A sequence of inputs produces one output.

Example: Predicting whether a movie review is positive or negative.

Many-to-Many

A sequence of inputs produces a sequence of outputs.

Example: Language translation.

5. What Is the Difference Between RNN and ANN?

Feature ANN RNN
Data type General structured data Sequential data
Memory No built-in sequence memory Uses a hidden state
Input processing Usually independent inputs Processes sequences
Applications Classification and prediction Text, speech, and time series

6. Building an RNN Model Using Python

Now, let's build a simple RNN model to predict the next value in a numerical sequence.

We will use TensorFlow and Keras to create the model.

For this example, we will generate a simple sequence of numbers and train the RNN to learn the pattern.

Step 1: Import the Libraries

First, import the required libraries.

import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import SimpleRNN, Dense
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • numpy helps us create and work with numerical data.
  • tensorflow provides tools for building deep learning models.
  • Sequential allows us to create a model layer by layer.
  • SimpleRNN creates a basic recurrent neural network layer.
  • Dense creates a fully connected output layer.

Step 2: Create the Dataset

We will create a sequence where each number increases by one.

For example:

1, 2, 3, 4, 5, 6, 7, 8, ...
Enter fullscreen mode Exit fullscreen mode

The model will learn to predict the next number using the previous three numbers.

data = np.array(range(1, 101), dtype=float)
Enter fullscreen mode Exit fullscreen mode

Here, range(1, 101) generates numbers from 1 to 100.

Step 3: Prepare the Input and Output Data

An RNN expects sequential input data.

We will use three consecutive numbers as input and the next number as the output.

For example:

  • Input: [1, 2, 3]
  • Output: 4
X = []
y = []

for i in range(len(data) - 3):
    X.append(data[i:i+3])
    y.append(data[i+3])

X = np.array(X)
y = np.array(y)
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • X stores the input sequences.
  • y stores the values the model should predict.
  • The loop creates sequences of three numbers.
  • The next number becomes the expected output.

Step 4: Reshape the Input Data

RNN models expect input in three dimensions:

  • Number of samples
  • Number of time steps
  • Number of features

Our data has one feature at each time step.

X = X.reshape((X.shape[0], X.shape[1], 1))
Enter fullscreen mode Exit fullscreen mode

This changes the data into the format required by the RNN layer.

Step 5: Create the RNN Model

Now, let's create the neural network.

model = Sequential([
    SimpleRNN(50, activation='tanh',
              input_shape=(3, 1)),
    Dense(1)
])
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • Sequential creates the model layer by layer.
  • SimpleRNN(50) creates an RNN layer with 50 units.
  • activation='tanh' helps the network learn patterns.
  • input_shape=(3, 1) means each input contains three time steps and one feature.
  • Dense(1) produces one predicted number.

Step 6: Compile the Model

Before training, we need to configure the model.

model.compile(
    optimizer='adam',
    loss='mean_squared_error'
)
Enter fullscreen mode Exit fullscreen mode

Explanation:

  • optimizer='adam' helps the model update its weights during training.
  • mean_squared_error measures the difference between actual and predicted values.

Step 7: Train the Model

Now, train the RNN using our dataset.

model.fit(X, y, epochs=100, verbose=0)
Enter fullscreen mode Exit fullscreen mode

Here:

  • X contains the input sequences.
  • y contains the expected outputs.
  • epochs=100 means the model will go through the training data 100 times.
  • verbose=0 hides the training progress output.

During training, the model learns the numerical pattern in the sequence.

Step 8: Make a Prediction

Let's provide the model with the numbers 98, 99, and 100.

The expected next number is 101.

test_input = np.array([98, 99, 100])
test_input = test_input.reshape((1, 3, 1))

prediction = model.predict(test_input, verbose=0)

print("Predicted next number:", prediction[0][0])
Enter fullscreen mode Exit fullscreen mode

The model should predict a value close to 101.

The prediction may not be exactly 101 because the model learns the pattern through training rather than following a fixed mathematical rule.

7. Complete Python Code

Here is the complete code in one place:

import numpy as np
import tensorflow as tf
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import SimpleRNN, Dense

data = np.array(range(1, 101), dtype=float)

X = []
y = []

for i in range(len(data) - 3):
    X.append(data[i:i+3])
    y.append(data[i+3])

X = np.array(X)
y = np.array(y)

X = X.reshape((X.shape[0], X.shape[1], 1))

model = Sequential([
    SimpleRNN(50, activation='tanh',
              input_shape=(3, 1)),
    Dense(1)
])

model.compile(
    optimizer='adam',
    loss='mean_squared_error'
)

model.fit(X, y, epochs=100, verbose=0)

test_input = np.array([98, 99, 100])
test_input = test_input.reshape((1, 3, 1))

prediction = model.predict(test_input, verbose=0)

print("Predicted next number:", prediction[0][0])
Enter fullscreen mode Exit fullscreen mode

8. Advantages of RNNs

  • Designed to work with sequential data.
  • Can use information from previous inputs.
  • Useful for text, speech, and time-series applications.
  • Can learn patterns that depend on the order of data.

9. Limitations of RNNs

  • Traditional RNNs can struggle to remember information from long sequences.
  • Training can be slow for long sequences.
  • They may suffer from the vanishing gradient problem.
  • They can be difficult to train when important information appears far back in a sequence.

To address some of these limitations, advanced architectures such as LSTM and GRU were developed.

10. Conclusion

Recurrent Neural Networks are an important type of deep learning model designed for sequential data. Their ability to use information from previous steps makes them useful for tasks such as text processing, speech recognition, and time-series forecasting.

In this tutorial, we explored the working of RNNs and built a simple model using Python and TensorFlow to predict the next number in a sequence.

RNNs also provide the foundation for understanding more advanced sequence-learning models such as LSTM and GRU.

Top comments (0)