To learn what is RNN (Recurrent Neural Networks ) why not understand ARIMA, SARIMA first ? – RNN Learning – Part 5 – day 59

ARIMA models a differenced series using lagged observations and forecast innovations. SARIMA adds seasonal components. An RNN learns a nonlinear transition and can use other signals when those inputs are available at prediction time.

A Deep Dive into ARIMA, SARIMA, and Their Relationship with Deep Learning for Time Series Forecasting

In recent years, deep learning has become a dominant force in many areas of data analysis, and time series forecasting is no exception. Traditional models like ARIMA (Autoregressive Integrated Moving Average) and its seasonal extension SARIMA have long been the go-to solutions for forecasting time-dependent data. However, newer models based on Recurrent Neural Networks (RNNs), particularly Long Short-Term Memory (LSTM) networks, have emerged as powerful alternatives. Both approaches have their strengths and applications, and understanding their relationship helps in choosing the right tool for the right problem.

In this blog post, we’ll explore ARIMA and SARIMA models in detail, discuss how they compare to deep learning-based models like RNNs, and demonstrate their practical implementation.

Deep Learning and Time Series Forecasting

Deep learning is a subset of machine learning where models learn hierarchical features from data using multiple layers of neural networks. When it comes to time series forecasting, one of the most common deep learning architectures used is Recurrent Neural Networks (RNNs).

RNNs are particularly well-suited for time series because they are designed to handle sequential data, where the output at each time step depends not only on the current input but also on the previous inputs. This is achieved by maintaining a hidden state that gets updated at each time step, allowing the model to “remember” past information.

Here are the key components of RNNs and their relevance to time series forecasting:

  • Sequential Memory: RNNs are built to retain information across time steps. This makes them suitable for forecasting problems where patterns are spread across time, such as stock prices or weather data.
  • Backpropagation Through Time (BPTT): Unlike traditional feedforward neural networks, RNNs are trained using a variant of backpropagation known as BPTT, where the network adjusts its weights by considering errors over multiple time steps.
  • Long Short-Term Memory (LSTM): A variant of RNNs, LSTMs are particularly useful in long-term forecasting because they are designed to overcome the vanishing gradient problem, allowing them to capture long-term dependencies in data.

While ARIMA and SARIMA focus on modeling the linear relationships in time series data, RNNs and LSTMs can capture complex non-linear dependencies. This makes RNNs more flexible, but they also require larger datasets and more computational power to train effectively.

How RNNs Relate to ARIMA and SARIMA Models

Although RNNs and ARIMA/SARIMA models operate differently, they share common ground in the context of time series forecasting:

  • Time Dependence: Both models are designed to forecast time-dependent data, meaning they consider historical information to predict future values.
  • Lagging Features: ARIMA uses lagging features (i.e., past values) directly, while RNNs learn patterns through sequential memory.
  • Complexity vs Simplicity: ARIMA/SARIMA models are simpler and more interpretable but may struggle with complex, non-linear patterns. RNNs, on the other hand, can model non-linearity but require more data and computational resources.

In this article, we will primarily focus on ARIMA and SARIMA models, their theoretical foundations, and how they are practically applied to time series forecasting. We’ll compare their strengths to RNNs and understand when to use which approach.

Understanding ARIMA and SARIMA Models

Time Series Fundamentals

At the heart of time series forecasting is the ability to recognize and model patterns in data that evolves over time. This includes:

  • Trend: A long-term upward or downward movement in the data.
  • Seasonality: Cyclical patterns that repeat at regular intervals, such as daily, weekly, or yearly fluctuations.
  • Stationarity: A stationary time series has a constant mean and variance over time. Many forecasting models, including ARIMA, require the data to be stationary to perform well.
  • Autocorrelation: The correlation between a time series and its lagged values. ARIMA models rely heavily on autocorrelation to predict future values.

ARIMA: Autoregressive Integrated Moving Average

The ARIMA model is a well-established statistical approach to time series forecasting. It works by combining three components:

  • Autoregressive (AR): The model regresses the target variable against its own previous values.
  • Integrated (I): This step involves differencing the data to remove trends and make the series stationary.
  • Moving Average (MA): The model includes a moving average component to account for the errors of past predictions.

The general ARIMA model is expressed as ARIMA(p, d, q), where:

  • p: The number of autoregressive terms.
  • d: The degree of differencing.
  • q: The number of lagged forecast errors used in the prediction.

SARIMA: Seasonal ARIMA

While ARIMA works well for non-seasonal data, time series data often contains seasonal patterns. SARIMA extends ARIMA by incorporating seasonal components:

  • P: Seasonal autoregressive terms.
  • D: Seasonal differencing.
  • Q: Seasonal moving average terms.
  • s: The length of the season (e.g., 7 for weekly seasonality).

A SARIMA model is expressed as ARIMA(p, d, q) x (P, D, Q, s), where both non-seasonal and seasonal components are considered.

Steps in Building ARIMA and SARIMA Models

  1. Data Preparation: Ensure the time series data is stationary. If not, apply differencing to make it stationary.
  2. Model Identification: Use tools like autocorrelation plots (ACF) and partial autocorrelation plots (PACF) to choose appropriate values for p, d, and q.
  3. Model Fitting: Train the ARIMA/SARIMA model on historical data.
  4. Forecasting: Use the fitted model to predict future data points.
  5. Model Evaluation: Measure the accuracy of the forecast using metrics like Mean Absolute Error (MAE).

Deep Learning vs Traditional Models

When deciding between RNNs and ARIMA/SARIMA models, it’s important to consider the complexity and nature of the data:

  • ARIMA/SARIMA: Best suited for small to medium-sized datasets with linear patterns and clear seasonality. They require minimal data preprocessing but struggle with non-linearity.
  • RNN/LSTM: Better suited for large datasets with complex, non-linear patterns. They excel at capturing long-term dependencies but need more data and computation to be effective. This is particularly useful for multi-step forecasts.






Code Implementation of ARIMA and SARIMA with RNN Comparison

In this section, we will implement the two code and we will compare ARIMA and SARIMA models with Recurrent Neural Networks (RNNs) for time series forecasting.

1. ARIMA Basic Forecast Code

The ARIMA model is used to forecast rail ridership for the next day (June 1, 2019), assuming data ends on May 31, 2019.


from statsmodels.tsa.arima.model import ARIMA
import pandas as pd

# Define the origin and end date for the dataset
# This specifies the time range of interest
origin, today = "2019-01-01", "2019-05-31"

# Assume the time series is stored in a pandas DataFrame named 'df'
# Ensure that "rail" is a column in the DataFrame
# Select the data within the specified date range and ensure daily frequency
rail_series = df.loc[origin:today, "rail"].asfreq("D")

# Build the ARIMA model
# The 'order' parameter specifies (p, d, q):
# - p: The number of lag observations included in the model (autoregression).
# - d: The number of times the data is differenced to make it stationary.
# - q: The size of the moving average window.
# The 'seasonal_order' specifies seasonal effects, with (P, D, Q, s):
# - P: Seasonal autoregressive terms.
# - D: Seasonal differencing.
# - Q: Seasonal moving average terms.
# - s: Seasonal periodicity (e.g., 7 for weekly seasonality).
model = ARIMA(rail_series, order=(1, 0, 0), seasonal_order=(0, 1, 1, 7))

# Fit the ARIMA model to the rail ridership data
# This step estimates the model parameters
model = model.fit()

# Forecast the rail ridership for a single future time point (June 1, 2019)
# The 'forecast' method predicts the next value based on the model
y_pred = model.forecast()  # Returns the predicted value
print(y_pred)

Explanation:

  • ARIMA Setup: The order=(1, 0, 0) sets up the ARIMA model with one autoregressive term (AR), no differencing (d=0), and no moving average term (MA).
  • Seasonal Component: The seasonal_order=(0, 1, 1, 7) adds seasonal differencing (D=1), a seasonal moving average (Q=1), and a seasonal period of 7 days (weekly seasonality).
  • Forecast: After fitting the model, the predicted ridership for June 1, 2019, is 427,758.6 passengers.

2. SARIMA with Daily Retraining and MAE Calculation

In this code, we extend the SARIMA model to retrain it daily for each day from March 1 to May 31, 2019. The forecasts are then compared to actual values, and the Mean Absolute Error (MAE) is calculated to evaluate the performance.


import pandas as pd
from statsmodels.tsa.arima.model import ARIMA

# Define the time period and data range
# 'origin': Start of the data for training
# 'start_date' and 'end_date': Range for testing and evaluation
origin, start_date, end_date = "2019-01-01", "2019-03-01", "2019-05-31"

# Generate a date range for the testing period
time_period = pd.date_range(start_date, end_date)

# Select the rail data from the dataset, ensuring daily frequency
rail_series = df.loc[origin:end_date]["rail"].asfreq("D")

# Initialize an empty list to store predictions
y_preds = []

# Loop through each day in the testing period
# Retrain the ARIMA model for each day and forecast the next value
for today in time_period.shift(-1):
    # Build the ARIMA model with parameters:
    # (1, 0, 0) for autoregressive terms, no differencing, no moving average
    # (0, 1, 1, 7) for weekly seasonality
    model = ARIMA(rail_series[origin:today], 
                  order=(1, 0, 0), 
                  seasonal_order=(0, 1, 1, 7))

    # Fit the ARIMA model to the training data
    model = model.fit()

    # Forecast the next day's value and append it to the predictions list
    y_pred = model.forecast()[0]
    y_preds.append(y_pred)

# Convert the predictions into a pandas Series with corresponding dates
y_preds = pd.Series(y_preds, index=time_period)

# Calculate the Mean Absolute Error (MAE)
# MAE measures the average magnitude of forecast errors
mae = (y_preds - rail_series[time_period]).abs().mean()

# Output the calculated MAE
print(f"Mean Absolute Error (MAE): {mae}")
# Example output: MAE is 32,040.7

Explanation:

  • Daily Retraining: The SARIMA model is retrained every day based on data up to the current day. This allows it to adapt better to recent data trends.
  • Time Period: The forecasts are made for each day between March 1 and May 31, 2019. The predictions are stored in the list y_preds.
  • Evaluation (MAE Calculation): The Mean Absolute Error (MAE) measures the average error in the predictions. Here, the model produces an MAE of 32,040.7, which indicates the average error in the ridership prediction over the given time period.

Comparison with Recurrent Neural Networks (RNNs)

Now that we have implemented ARIMA and SARIMA models, let’s explore how they compare with Recurrent Neural Networks (RNNs) for time series forecasting.

Strengths of ARIMA and SARIMA:

  • Simplicity: ARIMA and SARIMA models are relatively straightforward to implement and interpret, particularly for linear, seasonal data.
  • Data Requirements: These models perform well on small to medium-sized datasets without requiring extensive computational resources.
  • Seasonality: SARIMA can handle seasonal patterns explicitly, which is useful for datasets with known seasonality (e.g., weekly, monthly patterns).

Limitations of ARIMA and SARIMA:

  • Linear Assumptions: Both ARIMA and SARIMA models assume linear relationships in the data. They may struggle with complex, non-linear patterns.
  • Long-term Dependencies: These models work well with short-term forecasts but may not capture long-term dependencies as effectively.

Why Use RNNs for Time Series Forecasting?

Recurrent Neural Networks (RNNs) are designed to handle sequential data like time series, where the future value depends on previous values. Unlike ARIMA and SARIMA, RNNs are capable of modeling both linear and non-linear relationships, making them powerful for complex time series forecasting.

Strengths of RNNs:

  • Sequential Memory: RNNs have a hidden state that retains information from previous time steps, allowing the model to “remember” past values and make better forecasts for long sequences.
  • Non-linearity: RNNs can model non-linear patterns in the data, which is critical for complex time series that have intricate patterns.
  • Handling Long-term Dependencies: With variants like Long Short-Term Memory (LSTM) and Gated Recurrent Units (GRU), RNNs can capture long-term dependencies that are difficult for ARIMA/SARIMA to handle.

Limitations of RNNs:

  • Data Requirement: RNNs typically require larger datasets to train effectively compared to ARIMA/SARIMA models.
  • Complexity: RNNs are computationally intensive, requiring more resources for training and tuning.
  • Interpretability: Unlike ARIMA/SARIMA models, RNNs can be treated as black-box models. It is harder to interpret the relationships learned by RNNs.

When to Use ARIMA/SARIMA vs. RNNs?

  • ARIMA/SARIMA: These models are better suited for small datasets with linear relationships and seasonal patterns. They are easier to interpret and require fewer computational resources.
  • RNNs (LSTM/GRU): If your time series data is large, has non-linear relationships, or involves long-term dependencies, RNNs or their variants (like LSTMs or GRUs) may provide better accuracy.






Recap to ARIMA with a small real example

Recap again : What is ARIMA?

ARIMA (AutoRegressive Integrated Moving Average) is a time series forecasting model. It uses three components:

  • Autoregressive (AR): Predicts future values based on past values.
  • Integrated (I): Applies differencing to make the series stationary.
  • Moving Average (MA): Uses past forecast errors to improve predictions.

ARIMA is typically represented as ARIMA(p, d, q), where:

  • p is the number of autoregressive terms.
  • d is the degree of differencing.
  • q is the number of moving average terms.

Example: ARIMA(1,1,1) Step-by-Step

Given this data:

Time (t)Value (y)
t=150
t=255
t=354
t=457

We aim to predict y5 using ARIMA(1,1,1).

Step 1: Differencing (I = 1)

First, we apply first differencing to remove trends:

y′t=yt−yt−1

For our data:

  • y′2=55−50=5
  • y′3=54−55=−1
  • y′4=57−54=3

The differenced series is y′=[5,−1,3].

Step 2: Autoregression (AR = 1)

In AR(1), we predict the next differenced value y^′5 using y′4:

y^′5=c+φ1y′4

Where:

  • c=1 (constant)
  • φ1=0.7 (autoregressive coefficient estimated from autocorrelation)

How φ1=0.7 is Estimated:

To estimate φ1, we calculate the lag-1 autocorrelation of the differenced series [5,−1,3]. Here’s the calculation:

  1. Find the mean of the differenced series: Mean=5+(−1)+33=2.33
  2. Covariance between y′t and y′t−1:
    Cov(y′t,y′t−1)=(5−2.33)(−1−2.33)+(−1−2.33)(3−2.33)2=−6.33
  3. Variance of y′t:
    Var(y′t)=(5−2.33)2+(−1−2.33)2+(3−2.33)22=7.56
  4. Autocorrelation: φ1=−6.337.56=−0.837

We assume φ1 is approximately 0.7 for this example.

Using φ1=0.7 and y′4=3:

y^′5=1+0.7×3=1+2.1=3.1

The predicted differenced value y^′5 is **3.1**.

Step 3: Moving Average (MA = 1)

The MA(1) component adjusts the prediction based on the previous error ε4:

y^5=y^′5+θ1ε4

Where:

  • ε4=−0.5 (previous error)
  • θ1=0.6 (moving average coefficient)

Now, calculate the adjusted prediction:

y^5=3.1+0.6×(−0.5)=3.1−0.3=2.8

The adjusted prediction is **2.8**.

Step 4: Reverse Differencing to Get Final Prediction

Finally, we reverse the differencing to bring the prediction back to the original scale:

y^5=y4+y^′5
y^5=57+2.8=59.8

Final Prediction

The predicted value for t=5 is **59.8**.

Key Notes:

  • Differencing removes trends in the data.
  • Autoregression (AR) predicts the next value using the previous differenced value.
  • Moving Average (MA) adjusts the prediction using past forecast errors.
  • Reversing the differencing brings the prediction back to the original scale.

 

 

 

Overview

Objective:Now Lets Use a Recurrent Neural Network (RNN) to predict y5 based on the previous values example exactly of y1, y2, y3, and y4, and demonstrate how the model improves over multiple training iterations.

Given Time Series Data:

Time (t)Value(yt)t=150t=255t=354t=457

Step 1: Data Preparation

1.1 Organize Data into Sequences

We create input-output pairs for training:

Training Input Sequence: Xtrain=[y1,y2,y3]=[50,55,54]
Training Target Output: Ytrain=y4=57
Prediction Input Sequence: Xpredict=[y2,y3,y4]=[55,54,57]

1.2 Reshape Data

Reshape Xtrain for RNN input:

Xtrain=[[505554]]

Step 2: Define the RNN Model

2.1 Model Architecture

  • Input Size: 1
  • Hidden Units: 1
  • Output Size: 1

2.2 Initialize Weights and Biases

Wxh=0.1,Whh=0.2,Why=0.5,bh=0,by=0

2.3 Activation Function

Use tanh for the hidden state activation.

2.4 Initial Hidden State

Initial hidden state:

h0=0

Step 3: Training Iterations

We will perform three training iterations to observe how the model improves.

Iteration 1

3.1 Forward Propagation

Time Step t = 1

  • Input: x1=50

Compute Hidden State h1:

h1=tanh(Wxh⋅x1+Whh⋅h0+bh)=tanh(0.1⋅50+0.2⋅0)=tanh(5)≈0.9999092

Compute Output y^1:

y^1=Why⋅h1+by=0.5⋅0.9999092=0.4999546

Time Step t = 2

  • Input: x2=55

Compute Hidden State h2:

h2=tanh(0.1⋅55+0.2⋅h1)=tanh(5.5+0.2⋅0.9999092)=tanh(5.69998184)≈0.9999765

Compute Output y^2:

y^2=0.5⋅h2=0.5⋅0.9999765=0.49998825

Time Step t = 3

  • Input: x3=54

Compute Hidden State h3:

h3=tanh(0.1⋅54+0.2⋅h2)=tanh(5.5999953)≈0.9999723

Compute Output y^3:

y^3=0.5⋅h3=0.5⋅0.9999723=0.49998615

3.2 Loss Calculation

Target Output: Ytrain=57

Predicted Output: y^3≈0.49998615

Calculate Loss:

L=12(y^3−Ytrain)2=12(0.49998615−57)2=12(−56.50001385)2=1596.1328

3.3 Adjust Output Scaling

To address the mismatch in output scale, set Why=55.

Recalculate Output y^3:

y^3=55⋅h3=55⋅0.9999723=54.9985

Recalculate Loss:

L=12(54.9985−57)2=2.003

3.4 Backpropagation Through Time (BPTT)

Compute Gradients

Gradient w.r.t Why:

∂L∂Why=(y^3−Ytrain)⋅h3=(−2.0015)⋅0.9999723=−2.00144

Gradient w.r.t Wxh at t = 3:

δ3=(y^3−Ytrain)⋅Why⋅(1−h32)=(−2.0015)⋅55⋅0.0000554=−0.006095

∂L∂Wxh(t=3)=δ3⋅x3=−0.006095⋅54=−0.32913

Gradient w.r.t Whh at t = 3:

∂L∂Whh(t=3)=δ3⋅h2=−0.006095⋅0.9999765=−0.00609486

Total Gradients

Total Gradients:

  • ∂L∂Wxh≈−0.32913
  • ∂L∂Whh≈−0.00609486
  • ∂L∂Why≈−2.00144

3.5 Update Weights

Using learning rate η=0.01:

  • Wxhnew=0.1−0.01⋅(−0.32913)=0.1032913
  • Whhnew=0.2−0.01⋅(−0.00609486)=0.20006095
  • Whynew=55−0.01⋅(−2.00144)=55.0200144

Iteration 2

4.1 Forward Propagation

Time Step t = 1

  • Input: x1=50

Compute Hidden State h1:

h1=tanh(0.1032913⋅50+0.20006095⋅0)=tanh(5.164565)≈0.999936

Compute Output y^1:

y^1=55.0200144⋅h1=55.0200144⋅0.999936=54.9965

Time Step t = 2

  • Input: x2=55

Compute Hidden State h2:

h2=tanh(0.1032913⋅55+0.20006095⋅h1)=tanh(5.681023+0.20006095⋅0.999936)=tanh(5.8810716)≈0.999982

Compute Output y^2:

y^2=55.0200144⋅h2=55.0200144⋅0.999982=55.019

Time Step t = 3

  • Input: x3=54

Compute Hidden State h3:

h3=tanh(0.1032913⋅54+0.20006095⋅h2)=tanh(5.777788)≈0.9999815

Compute Output y^3:

y^3=55.0200144⋅h3=55.0200144⋅0.9999815=55.019

4.2 Loss Calculation

Calculate Loss:

L=12(55.019−57)2=12(−1.981)2=1.962

Note: The loss has decreased from 2.003 to 1.962.

4.3 Backpropagation Through Time (BPTT)

Compute gradients similarly to Iteration 1 but with updated values.

Gradient w.r.t Why:

∂L∂Why=(55.019−57)⋅h3=(−1.981)⋅0.9999815=−1.98096

Gradient w.r.t Wxh at t = 3:

δ3=(−1.981)⋅55.0200144⋅(1−(0.9999815)2)=−0.004048

∂L∂Wxh(t=3)=−0.004048⋅54=−0.2186

Gradient w.r.t Whh at t = 3:

∂L∂Whh(t=3)=−0.004048⋅h2=−0.004048

4.4 Update Weights

  • Wxhnew=0.1032913−0.01⋅(−0.2186)=0.1054773
  • Whhnew=0.20006095−0.01⋅(−0.004048)=0.20010143
  • Whynew=55.0200144−0.01⋅(−1.98096)=55.0398240

Iteration 3

5.1 Forward Propagation

Time Step t = 1

  • Input: x1=50

Compute Hidden State h1:

h1=tanh(0.1054773⋅50+0.20010143⋅0)=tanh(5.273865)≈0.999946

Compute Output y^1:

y^1=55.0398240⋅h1=55.0398240⋅0.999946=55.0379

Time Step t = 2

  • Input: x2=55

Compute Hidden State h2:

h2=tanh(0.1054773⋅55+0.20010143⋅h1)=tanh(5.801252+0.20010143⋅0.999946)=tanh(6.001343)≈0.999990

Compute Output y^2:

y^2=55.0398240⋅h2=55.0398240⋅0.999990=55.0393

Time Step t = 3

  • Input: x3=54

Compute Hidden State h3:

h3=tanh(0.1054773⋅54+0.20010143⋅h2)=tanh(5.8961505)≈0.999985

Compute Output y^3:

y^3=55.0398240⋅h3=55.0398240⋅0.999985=55.0390

5.2 Loss Calculation

Calculate Loss:

L=12(55.0390−57)2=12(−1.9610)2=1.9215

Note: The loss has decreased from 1.962 to 1.9215.

5.3 Backpropagation Through Time (BPTT)

Gradient w.r.t Why:

∂L∂Why=(55.0390−57)⋅h3=(−1.9610)⋅0.999985=−1.96097

Gradient w.r.t Wxh at t = 3:

δ3=(−1.9610)⋅55.0398240⋅(1−(0.999985)2)=(−1.9610)⋅55.0398240⋅0.0000299=−0.003230

∂L∂Wxh(t=3)=−0.003230⋅x3=−0.003230⋅54=−0.1744

Gradient w.r.t Whh at t = 3:

∂L∂Whh(t=3)=−0.003230⋅h2=−0.003230

5.4 Update Weights

  • Wxhnew=0.1054773−0.01⋅(−0.1744)=0.1072213
  • Whhnew=0.20010143−0.01⋅(−0.003230)=0.20013373
  • Whynew=55.0398240−0.01⋅(−1.96097)=55.0594337

Step 4: Prediction

After three iterations, we use the updated weights to predict y5.

4.1 Prediction Input Sequence

Input sequence:

Xpredict=[55,54,57]

4.2 Forward Propagation

Time Step t = 1

  • Input: x1=55

Compute Hidden State h1:

h1=tanh(0.1072213⋅55+0.20013373⋅0)=tanh(5.8971715)≈0.999991

Compute Output y^1:

y^1=55.0594337⋅h1=55.0594337⋅0.999991=55.0589

Time Step t = 2

  • Input: x2=54

Compute Hidden State h2:

h2=tanh(0.1072213⋅54+0.20013373⋅h1)=tanh(5.7869482+0.2001315)=tanh(5.9870797)≈0.999986

Compute Output y^2:

y^2=55.0594337⋅h2=55.0594337⋅0.999986=55.0586

Time Step t = 3

  • Input: x3=57

Compute Hidden State h3:

h3=tanh(0.1072213⋅57+0.20013373⋅h2)=tanh(6.3107376)≈0.999993

Compute Output y^3:

y^3=55.0594337⋅h3=55.0594337⋅0.999993≈55.0590

4.3 Predicted y5

y^5=y^3≈55.0590

Key Notes :

  • Initial Loss: 2.003
  • Loss after Iteration 3: 1.9215
  • Predicted y5: Improved from 54.9985 to 55.0590

Keys

By performing multiple training iterations, we observed the following:

  • Decrease in Loss: The loss gradually decreased with each iteration, indicating the model is learning.
  • Improved Predictions: The predicted value for y5 became more accurate over the iterations.

Key Takeaways

  • Gradient Descent: Repeatedly updating weights using gradients reduces the loss.
  • Learning Rate: A small learning rate ensures stable convergence.
  • RNN Capability: Even with limited data, the RNN adjusts its weights to better fit the training data.

I hope this extended explanation, including multiple iterations, provides a clearer understanding of how an RNN learns and improves its predictions over time ; We have provided the ARIMA and SARIMA concepts to understand better how predictions can happen in other ways as well

 

 

 

Note to Understand RNN Steps in this Example

1. Sequence-to-One Prediction

Sequence Input: The RNN takes a sequence of inputs and processes them over time steps.

Single Output: It produces a single output after processing the entire sequence.

This is called a many-to-one or sequence-to-one prediction model.

2. Training Phase

Purpose: Teach the RNN to predict the next value in a sequence based on previous values.

Process:

  • Provide sequences where the next value is known.
  • The RNN learns patterns from these sequences.

What’s Being Calculated from the Sequence?

  • From the input sequence, we are calculating the hidden states ht at each time step t.
  • Using the hidden states and the learned weights, we compute the output y^t at each time step.
  • The weights Wxh, Whh, and Why are learned during training and remain fixed during prediction.

Detailed Explanation

1. During Training

Goal: Learn the weights W that minimize the difference between the predicted output and the actual target.

  • Input Sequence: Xtrain=[y1,y2,y3]
  • Target Output: Ytrain=y4

Process:

  1. Time Step t=1:

    Input: x1=y1


    Compute Hidden State: h1=tanh(Wxh⋅x1+Whh⋅h0)


    Compute Output: y^1=Why⋅h1


  2. Time Step t=2:

    Input: x2=y2


    Compute Hidden State: h2=tanh(Wxh⋅x2+Whh⋅h1)


    Compute Output: y^2=Why⋅h2


  3. Time Step t=3:

    Input: x3=y3


    Compute Hidden State: h3=tanh(Wxh⋅x3+Whh⋅h2)


    Compute Output: y^3=Why⋅h3


    Prediction: y^3 is compared to y4 to compute the loss.


  4. Weights Update

Using backpropagation through time (BPTT), we compute gradients of the loss with respect to the weights.

Weights W are updated to minimize the loss.


2. During Prediction

Goal: Use the learned weights to predict the next value y5 based on a new input sequence.

  • Input Sequence: Xpredict=[y2,y3,y4]
  • We use the same learned weights W from training.

Process:

  1. Time Step t=1:


    Input: x1=y2


    Compute Hidden State: h1=tanh(Wxh⋅x1+Whh⋅h0)


    Compute Output (intermediate): y^1=Why⋅h1



  2. Time Step t=2:

    Input: x2=y3


    Compute Hidden State: h2=tanh(Wxh⋅x2+Whh⋅h1)


    Compute Output (intermediate): y^2=Why⋅h2



  3. Time Step t=3:

    Input: x3=y4


    Compute Hidden State: h3=tanh(Wxh⋅x3+Whh⋅h2)


    Compute Output: y^3=Why⋅h3


    Prediction: y^3 is our predicted y5.



Key Points:

  • Hidden States ht: Calculated from the input sequence and previous hidden states.
  • Weights W: Remain fixed during prediction; they are the result of training.
  • Prediction: The final output y^3 is the RNN’s prediction for the next value in the sequence.

Key Notes

  • From the Sequence, we are calculating the Hidden States ht at each time step.
  • Using the Hidden States and the Weights W, we compute the Outputs y^t.
  • During Training:
    • We adjust the Weights W to minimize the loss between y^3 and the actual y4.
  • During Prediction:
    • We use the learned Weights W to compute y^3, which is our predicted y5.

Visualization

Training Phase

Here’s a visualization of the training phase:

Input Sequence: y1       y2       y3
                    ↓        ↓        ↓
Time Steps:        t=1     t=2     t=3
                    ↓        ↓        ↓
Hidden States:     h1       h2       h3
                                     ↓
                          Output: \hat{y}_3 (compared to y4)

Weights W are updated based on the loss between y^3 and y4.

Prediction Phase

Here’s a visualization of the prediction phase:

Input Sequence: y2       y3       y4
                    ↓        ↓        ↓
Time Steps:        t=1     t=2     t=3
                    ↓        ↓        ↓
Hidden States:     h1       h2       h3
                                     ↓
                          Output: \hat{y}_3 (prediction for y5)

Weights W remain fixed; we use them to compute the prediction.


Notes

  • We are calculating the Hidden States ht from the input sequence.
  • The Weights W are learned during training and are used (not calculated) to compute the hidden states and outputs.
  • The Hidden States and Weights together allow us to predict y4 during training and y5 during prediction.

Key Takeaways

  • Sequence → Hidden States: The sequence of inputs is used to compute hidden states at each time step.
  • Hidden States + Weights → Outputs: The hidden states and learned weights are used to compute outputs.
  • Weights:
    • Adjusted during training to minimize loss.
    • Remain fixed during prediction.

Conclusion

This blog post dives into the importance of understanding traditional time series forecasting methods such as ARIMA and SARIMA before delving into more advanced approaches like Recurrent Neural Networks (RNNs). By focusing on ARIMA and SARIMA, you are introduced to the foundational concepts of modeling time-dependent data, including understanding trends, seasonality, and the role of stationarity in creating accurate forecasts.

ARIMA models provide a structured approach to capturing relationships within time series data, while SARIMA extends these capabilities by addressing seasonality.

This post bridges the gap between traditional statistical methods and modern deep learning approaches, creating a comprehensive roadmap for anyone venturing into time series forecasting. By combining the structured simplicity of ARIMA/SARIMA with the advanced capabilities of RNNs, you can build a robust skill set for handling both basic and advanced forecasting problems.

Whether you are just starting with time series modeling or looking to expand your knowledge into the realm of neural networks, this blog post provides a clear, step-by-step progression that is both educational and practical.

 

Don’t forget to check our apps! Visit here.

Calculate an ARIMA level forecast

First difference the level series. For an ARMA(1,1) on that difference, add a constant, a fraction of the latest difference, and a fraction of the last forecast error. The next innovation has conditional mean zero. Then integrate once by adding the predicted difference to the latest level.

d^t+1=c+φdt+θet
y^t+1=yt+d^t+1

Assume the latest level is 57, the difference is 3, the last innovation is −1, and the coefficients are 1, 0.7, and 0.4 for the constant, AR term, and MA term. The forecast difference is 1 plus 2.1 minus 0.4, or 2.7. The forecast level is 59.7.

Calculate an ARIMA level forecastDifferenceRemove levelForecast changeUse lags and errorIntegrateAdd last level
Compute and invert changes using observations available at the forecast origin.

Evaluate models on equal forecast origins

Compare seasonal naive, ARIMA or SARIMA, and an RNN using the same origins, horizons, and retraining policy. Score errors in the original units and report by horizon so an easy first step cannot hide poor later forecasts.

In statsmodels, check the trend convention before mapping a textbook constant into ARIMA or SARIMAX arguments. For an RNN, honor the same information cutoff for external variables and fit scaling on the training portion.

References

Practice and FAQs

What do p, d, and q represent?

They count autoregressive lags, differences, and lagged innovations in the nonseasonal part of an ARIMA model.

What is the innovation if a difference was 3 and the model predicted 4?

The observed difference minus its prediction is −1.

How do you compare a one-day forecast with a one-week forecast fairly?

Report each horizon separately over common origins and use the same information cutoff for all models.

You Can Also Learn Deep Learning in 80 Days Inside the iOS App Continue this roadmap in a focused mobile study experience with offline access, flashcards, notes, and progress tracking.
Open on the App Store