LEARN PYCARET
📖
Official Blog
Time Series Forecasting with PyCaret Regression

Time Series Forecasting with PyCaret Regression Module

Photo by Lukas Blazek on Unsplash

PyCaret

PyCaret is an open-source, low-code machine learning library and end-to-end model management tool built-in Python for automating machine learning workflows. It is incredibly popular for its ease of use, simplicity, and ability to build and deploy end-to-end ML prototypes quickly and efficiently.
PyCaret is an alternate low-code library that can be used to replace hundreds of lines of code with few lines only. This makes the experiment cycle exponentially fast and efficient.
PyCaret is simple and easy to use. All the operations performed in PyCaret are sequentially stored in a Pipeline that is fully automated for **deployment. **Whether it's imputing missing values, one-hot-encoding, transforming categorical data, feature engineering, or even hyperparameter tuning, PyCaret automates all of it. To learn more about PyCaret, watch this 1-minute video.
This tutorial assumes that you have some prior knowledge and experience with PyCaret. If you haven’t used it before, no problem — you can get a quick headstart through these tutorials:

Installing PyCaret

Installing PyCaret is very easy and takes only a few minutes. We strongly recommend using a virtual environment to avoid potential conflicts with other libraries.
PyCaret’s default installation is a slim version of pycaret which only installs hard dependencies that are listed here.
1
**# install slim version (default)
2
**pip install pycaret
3
4
**# install the full version**
5
pip install pycaret[full]
Copied!
When you install the full version of pycaret, all the optional dependencies as listed here are also installed.

👉 PyCaret Regression Module

PyCaret Regression Module is a supervised machine learning module used for estimating the relationships between a dependent variable (often called the ‘outcome variable’, or ‘target’) and one or more independent variables (often called ‘features’, or ‘predictors’).
The objective of regression is to predict continuous values such as sales amount, quantity, temperature, number of customers, etc. All modules in PyCaret provide many pre-processing features to prepare the data for modeling through the setup function. It has over 25 ready-to-use algorithms and several plots to analyze the performance of trained models.

👉 Time Series with PyCaret Regression Module

Time series forecasting can broadly be categorized into the following categories:
  • Classical / Statistical Models — Moving Averages, Exponential smoothing, ARIMA, SARIMA, TBATS
  • **Machine Learning **— Linear Regression, XGBoost, Random Forest, or any ML model with reduction methods
  • **Deep Learning **— RNN, LSTM
This tutorial is focused on the second category i.e. Machine Learning.
PyCaret’s Regression module default settings are not ideal for time series data because it involves few data preparatory steps that are not valid for ordered data (data with a sequence such as time series data).
For example, the split of the dataset into train and test set is done randomly with shuffling. This wouldn’t make sense for time series data as you don’t want the recent dates to be included in the training set whereas historical dates are part of the test set.
Time-series data also requires a different kind of cross-validation since it needs to respect the order of dates. PyCaret regression module by default uses k-fold random cross-validation when evaluating models. The default cross-validation setting is not suitable for time-series data.
The following section in this tutorial will demonstrate how you can change default settings in PyCaret Regression Module easily to make it work for time series data.

👉 Dataset

For the purpose of this tutorial, I have used the US airline passengers dataset. You can download the dataset from Kaggle.
1
**# read csv file
2
**import pandas as pd
3
data = pd.read_csv('AirPassengers.csv')
4
data['Date'] = pd.to_datetime(data['Date'])
5
data.head()
Copied!
Sample rows
1
**# create 12 month moving average
2
**data['MA12'] = data['Passengers'].rolling(12).mean()
3
4
**# plot the data and MA
5
**import plotly.express as px
6
fig = px.line(data, x="Date", y=["Passengers", "MA12"], template = 'plotly_dark')
7
fig.show()
Copied!
US Airline Passenger Dataset Time Series Plot with Moving Average = 12
Since algorithms cannot directly deal with dates, let’s extract some simple features from dates such as month and year, and drop the original date column.
1
**# extract month and year from dates**
2
data['Month'] = [i.month for i in data['Date']]
3
data['Year'] = [i.year for i in data['Date']]
4
5
**# create a sequence of numbers
6
**data['Series'] = np.arange(1,len(data)+1)
7
8
**# drop unnecessary columns and re-arrange
9
**data.drop(['Date', 'MA12'], axis=1, inplace=True)
10
data = data[['Series', 'Year', 'Month', 'Passengers']]
11
12
**# check the head of the dataset**
13
data.head()
Copied!
Sample rows after extracting features
1
**# split data into train-test set
2
**train = data[data['Year'] < 1960]
3
test = data[data['Year'] >= 1960]
4
5
**# check shape
6
**train.shape, test.shape
7
>>> ((132, 4), (12, 4))
Copied!
I have manually split the dataset before initializing the setup . An alternate would be to pass the entire dataset to PyCaret and let it handle the split, in which case you will have to pass data_split_shuffle = False in the setup function to avoid shuffling the dataset before the split.

👉 Initialize Setup

Now it’s time to initialize the setup function, where we will explicitly pass the training data, test data, and cross-validation strategy using the fold_strategy parameter.
1
**# import the regression module**
2
from pycaret.regression import *
3
4
**# initialize setup**
5
s = setup(data = train, test_data = test, target = 'Passengers', fold_strategy = 'timeseries', numeric_features = ['Year', 'Series'], fold = 3, transform_target = True, session_id = 123)
Copied!

👉 Train and Evaluate all Models

1
best = compare_models(sort = 'MAE')
Copied!
Results from compare_models
The best model based on cross-validated MAE is **Least Angle Regression **(MAE: 22.3). Let’s check the score on the test set.
1
prediction_holdout = predict_model(best);
Copied!
Results from predict_model(best) function
MAE on the test set is 12% higher than the cross-validated MAE. Not so good, but we will work with it. Let’s plot the actual and predicted lines to visualize the fit.
1
**# generate predictions on the original dataset**
2
predictions = predict_model(best, data=data)
3
4
**# add a date column in the dataset**
5
predictions['Date'] = pd.date_range(start='1949-01-01', end = '1960-12-01', freq = 'MS')
6
7
**# line plot**
8
fig = px.line(predictions, x='Date', y=["Passengers", "Label"], template = 'plotly_dark')
9
10
**# add a vertical rectange for test-set separation**
11
fig.add_vrect(x0="1960-01-01", x1="1960-12-01", fillcolor="grey", opacity=0.25, line_width=0)
12
13
fig.show()
Copied!
Actual and Predicted US airline passengers (1949–1960)
The grey backdrop towards the end is the test period (i.e. 1960). Now let’s finalize the model i.e. train the best model i.e. Least Angle Regression on the entire dataset (this time, including the test set).
1
final_best = finalize_model(best)
Copied!

👉 Create a future scoring dataset

Now that we have trained our model on the entire dataset (1949 to 1960), let’s predict five years out in the future through 1964. To use our final model to generate future predictions, we first need to create a dataset consisting of the Month, Year, Series column on the future dates.
1
future_dates = pd.date_range(start = '1961-01-01', end = '1965-01-01', freq = 'MS')
2
3
future_df = pd.DataFrame()
4
5
future_df['Month'] = [i.month for i in future_dates]
6
future_df['Year'] = [i.year for i in future_dates]
7
future_df['Series'] = np.arange(145,(145+len(future_dates)))
8
9
future_df.head()
Copied!
Sample rows from future_df
Now, let’s use the future_df to score and generate predictions.
1
predictions_future = predict_model(final_best, data=future_df)
2
predictions_future.head()
Copied!
Sample rows from predictions_future
Let’s plot it.
1
concat_df = pd.concat([data,predictions_future], axis=0)
2
concat_df_i = pd.date_range(start='1949-01-01', end = '1965-01-01', freq = 'MS')
3
concat_df.set_index(concat_df_i, inplace=True)
4
5
fig = px.line(concat_df, x=concat_df.index, y=["Passengers", "Label"], template = 'plotly_dark')
6
fig.show()
Copied!
Actual (1949–1960) and Predicted (1961–1964) US airline passengers
Wasn’t that easy?
There is no limit to what you can achieve using this lightweight workflow automation library in Python. If you find this useful, please do not forget to give us ⭐️ on our GitHub repository.
To hear more about PyCaret follow us on LinkedIn and Youtube.
Join us on our slack channel. Invite link here.

You may also be interested in:

Want to learn about a specific module?

Click on the links below to see the documentation and working examples.