Prophet for Time Series Forecasting

Loading

Prophet for Time Series Forecasting: A Detailed Guide

1. Introduction to Prophet

Prophet is an open-source forecasting tool developed by Facebook (Meta). It is designed to handle time series forecasting efficiently, even when the data has missing values, outliers, and complex seasonal trends.

Why Use Prophet?
✔ Handles daily, weekly, and yearly seasonality automatically.
✔ Works well with irregular time series data.
✔ Can handle holidays, special events, and custom seasonality.
Interpretable results with clear trend and seasonality breakdown.
✔ Available in Python & R, making it widely accessible.

📌 Best Suited For:

  • Business Forecasting
  • Demand Forecasting
  • Financial Forecasting
  • Sales Predictions
  • Stock Market Analysis
  • Website Traffic Forecasting
  • Weather Predictions

2. Installing and Importing Prophet

Before using Prophet, install it using:

pip install prophet

Now, import necessary libraries:

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from prophet import Prophet

3. Understanding Prophet’s Model Components

Prophet follows an additive model structure: y(t)=g(t)+s(t)+h(t)+ϵty(t) = g(t) + s(t) + h(t) + \epsilon_t

Where:

  • g(t) → Trend (long-term upward/downward movement).
  • s(t) → Seasonality (recurring patterns like daily, weekly, or yearly effects).
  • h(t) → Holidays or special events.
  • ε_t → Residual errors (random noise).

Prophet automatically detects these components and builds a reliable forecasting model.


4. Loading Time Series Data

Step 1: Load & Preprocess Data

Prophet requires a specific format with two columns:

  • ds (Datetime column)
  • y (Value to be forecasted)
# Load dataset
df = pd.read_csv("time_series_data.csv")

# Convert date column to datetime
df['ds'] = pd.to_datetime(df['Date'])  # Rename 'Date' to 'ds'

# Rename target variable to 'y'
df.rename(columns={'Sales': 'y'}, inplace=True)  # Change 'Sales' to your target variable

# Visualize data
plt.figure(figsize=(12,6))
plt.plot(df['ds'], df['y'], label="Original Data", color='blue')
plt.xlabel("Time")
plt.ylabel("Value")
plt.title("Time Series Data")
plt.legend()
plt.show()

5. Building a Prophet Model

Step 1: Initialize Prophet Model

model = Prophet()

Step 2: Fit the Model

model.fit(df)

Step 3: Create Future Dates for Forecasting

future = model.make_future_dataframe(periods=365)  # Forecast for 1 year (365 days)
print(future.tail())  # Check future dates

Step 4: Generate Predictions

forecast = model.predict(future)

Step 5: Plot Forecast Results

model.plot(forecast)
plt.show()

✅ Prophet automatically detects trends, seasonality, and generates future predictions.


6. Understanding the Forecast Output

The forecast dataframe contains:

  • ds: Date of prediction
  • yhat: Predicted value
  • yhat_lower: Lower bound of confidence interval
  • yhat_upper: Upper bound of confidence interval

📌 Check forecast results:

forecast[['ds', 'yhat', 'yhat_lower', 'yhat_upper']].tail(10)

📌 Plot Forecast Components (Trend & Seasonality):

model.plot_components(forecast)
plt.show()

7. Handling Seasonality and Trends in Prophet

By default, Prophet captures daily, weekly, and yearly seasonality, but you can customize seasonality settings.

1️⃣ Customizing Seasonality

If your data has a special seasonal pattern, you can add it manually:

model = Prophet()
model.add_seasonality(name='quarterly', period=90, fourier_order=8)
model.fit(df)

2️⃣ Adding Holiday Effects

Holidays can impact time series data. Prophet allows defining holidays and adjusting forecasts.

# Define holiday dataframe
holidays = pd.DataFrame({
  'holiday': 'special_event',
  'ds': pd.to_datetime(['2023-12-25', '2024-01-01']),  # Example holiday dates
  'lower_window': 0,
  'upper_window': 1
})

# Add holidays to the model
model = Prophet(holidays=holidays)
model.fit(df)

8. Handling Outliers in Prophet

Prophet is robust to outliers, but sometimes they may need adjustment.

Removing Outliers

df = df[df['y'] < df['y'].quantile(0.99)]  # Remove extreme outliers

Adding Change Points to Detect Trend Shifts

model = Prophet(changepoint_prior_scale=0.05)  # Adjust sensitivity
model.fit(df)

9. Advanced Prophet Features

1️⃣ Adjusting Trend Flexibility

If the model underfits or overfits, adjust changepoint_prior_scale:

model = Prophet(changepoint_prior_scale=0.1)  # Increase flexibility

2️⃣ Forecasting at Different Frequencies

Forecast weekly or hourly instead of daily:

future = model.make_future_dataframe(periods=52, freq='W')  # Weekly Forecasting
future = model.make_future_dataframe(periods=24, freq='H')  # Hourly Forecasting

3️⃣ Using External Regressors

If additional variables impact the forecast (e.g., promotions, weather), Prophet allows adding extra regressors.

df['extra_feature'] = np.random.rand(len(df))  # Example feature
model.add_regressor('extra_feature')

10. Evaluating Prophet’s Performance

After forecasting, compare predictions with actual values.

1️⃣ Calculate Mean Absolute Error (MAE) & RMSE

from sklearn.metrics import mean_absolute_error, mean_squared_error

actual = df['y']
predicted = forecast['yhat'][:len(df)]

mae = mean_absolute_error(actual, predicted)
rmse = np.sqrt(mean_squared_error(actual, predicted))

print(f"MAE: {mae}, RMSE: {rmse}")

✅ Lower MAE & RMSE = Better Model Performance.


Leave a Reply

Your email address will not be published. Required fields are marked *