We use RNNs to understand data that changes over time, like weather or stock prices. They help predict what comes next by remembering past information.
Predicting tomorrow's temperature based on past days
Forecasting sales for the next month using previous sales data
Analyzing heart rate signals to detect irregularities
Predicting energy usage in a building over time
Understanding speech or text sequences for voice assistants
Syntax
TensorFlow
model = tf.keras.Sequential([
tf.keras.layers.SimpleRNN(units, input_shape=(time_steps, features)),
tf.keras.layers.Dense(output_units)
])
model.compile(optimizer='adam', loss='mse')
SimpleRNN layer processes sequences step-by-step.
input_shape is (time steps, features per step).
Examples
RNN with 10 units, input sequences of length 5 with 1 feature each, output is 1 number.
TensorFlow
model = tf.keras.Sequential([
tf.keras.layers.SimpleRNN(10, input_shape=(5, 1)),
tf.keras.layers.Dense(1)
])
Stacked RNN layers: first returns full sequence, second returns last output, then dense layer.
TensorFlow
model = tf.keras.Sequential([
tf.keras.layers.SimpleRNN(20, return_sequences=True, input_shape=(10, 3)),
tf.keras.layers.SimpleRNN(10),
tf.keras.layers.Dense(1)
])
Sample Model
This code trains a simple RNN to predict the next number in a sequence. It uses sequences of 10 numbers and tries to guess the next number. After training, it predicts the next number after 100-109.
TensorFlow
import numpy as np
import tensorflow as tf
# Create simple time series data: y = next value after sequence
np.random.seed(0)
time_steps = 10
features = 1
samples = 100# Generate sequences
X = np.array([np.arange(i, i + time_steps) for i inrange(samples)])
X = X[..., np.newaxis] # shape (samples, time_steps, features)# Targets are next value after sequence
Y = np.array([i + time_steps for i inrange(samples)])
# Build model
model = tf.keras.Sequential([
tf.keras.layers.SimpleRNN(20, input_shape=(time_steps, features)),
tf.keras.layers.Dense(1)
])
model.compile(optimizer='adam', loss='mse')
# Train model
history = model.fit(X, Y, epochs=10, verbose=0)
# Predict next value for a new sequence
test_seq = np.array([np.arange(100, 110)])[..., np.newaxis]
pred = model.predict(test_seq)
print(f"Prediction for input sequence 100-109: {pred[0,0]:.2f}")
print(f"Actual next value: 110")
print(f"Final training loss: {history.history['loss'][-1]:.4f}")
OutputSuccess
Important Notes
RNNs remember past steps but can forget long ago information.
For longer sequences, consider LSTM or GRU layers instead of SimpleRNN.
Normalize your data for better training results.
Summary
RNNs help predict future values from past sequences.
Use SimpleRNN layer for basic sequence learning.
Train with sequences shaped as (samples, time steps, features).
Practice
(1/5)
1. What is the main purpose of using an RNN (Recurrent Neural Network) in time series prediction?
easy
A. To learn patterns from past time steps to predict future values
B. To classify images into categories
C. To reduce the size of the dataset
D. To perform arithmetic operations on numbers
Solution
Step 1: Understand RNN's role in time series
RNNs are designed to process sequences by remembering past information.
Step 2: Connect RNN to prediction task
They use past time steps to predict future values in a sequence.
Final Answer:
To learn patterns from past time steps to predict future values -> Option A
Quick Check:
RNN predicts future from past [OK]
Hint: RNNs remember past data to predict next steps [OK]
Common Mistakes:
Confusing RNN with image classifiers
Thinking RNN reduces data size
Assuming RNN does simple math only
2. Which of the following is the correct way to add a SimpleRNN layer with 50 units in TensorFlow Keras?
easy
A. model.add(tf.keras.layers.SimpleRNN(input_shape=(None, 1), 50))
B. model.add(tf.keras.layers.RNN(50))
C. model.add(tf.keras.layers.SimpleRNN(activation='relu', 50))
D. model.add(tf.keras.layers.SimpleRNN(units=50))
Solution
Step 1: Recall SimpleRNN syntax
The units parameter must be named or passed first as an integer.
Step 2: Check each option
model.add(tf.keras.layers.SimpleRNN(units=50)) uses named parameter units=50, which is correct and clear.
Final Answer:
model.add(tf.keras.layers.SimpleRNN(units=50)) -> Option D
Quick Check:
Use named units parameter [OK]
Hint: Use named 'units' parameter for clarity [OK]
Common Mistakes:
Passing activation before units
Omitting units parameter name
Missing input_shape when required
3. Given this code snippet, what will be the shape of the output from the SimpleRNN layer?
First layer in Sequential must specify input_shape if no input layer is given.
Step 2: Verify code
SimpleRNN(20) lacks input_shape=(10,3), so model won't know input dimensions.
Final Answer:
SimpleRNN layer missing input_shape parameter -> Option A
Quick Check:
First layer needs input_shape [OK]
Hint: Always specify input_shape in first RNN layer [OK]
Common Mistakes:
Ignoring input_shape in first layer
Changing Dense units unnecessarily
Misunderstanding loss or optimizer names
5. You want to predict the next 3 values in a time series using an RNN. Which model setup is best to output a sequence of 3 predictions for each input sequence?
hard
A. Use SimpleRNN with return_sequences=True and a Dense layer with 3 units
B. Use SimpleRNN with return_sequences=False and a Dense layer with 3 units
C. Use SimpleRNN with return_sequences=True and a TimeDistributed Dense layer with 1 unit
D. Use SimpleRNN with return_sequences=False and a TimeDistributed Dense layer with 1 unit
Solution
Step 1: Understand output requirements
Predicting next 3 values means outputting a sequence of length 3, one prediction per time step.
Step 2: Choose correct RNN and output layer
return_sequences=True outputs a sequence (batch, time steps, units). A Dense layer with 3 units applied at each time step (via TimeDistributed) or a Dense layer with 3 units on the last step can be used depending on output shape.
Step 3: Analyze options
Use SimpleRNN with return_sequences=True and a Dense layer with 3 units outputs only the last time step's output with 3 units, which is not a sequence of 3 predictions. Use SimpleRNN with return_sequences=True and a TimeDistributed Dense layer with 1 unit uses return_sequences=True and TimeDistributed Dense(1), producing a sequence output of shape (batch, time steps, 1), which can be adjusted to 3 time steps for 3 predictions.
Final Answer:
Use SimpleRNN with return_sequences=True and a TimeDistributed Dense layer with 1 unit -> Option C