You are on page 1of 22

8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

 Navigation

Click to Take the FREE Time Series Crash-Course

Search... 

How to Model Residual Errors to Correct Time Series


Forecasts with Python
by Jason Brownlee on January 11, 2017 in Time Series

Tweet Share Share

Last Updated on April 24, 2020

The residual errors from forecasts on a time series provide another source of information that we can model.

Residual errors themselves form a time series that can have temporal structure. A simple autoregression model of this
structure can be used to predict the forecast error, which in turn can be used to correct forecasts. This type of model is
called a moving average model, the same name but very different from moving average smoothing.

In this tutorial, you will discover how to model a residual error time series and use it to correct predictions with
Python.

After completing this tutorial, you will know:

About how to model residual error time series using an autoregressive model.
How to develop and evaluate a model of residual error time series.
How to use a model of residual error to correct predictions and improve forecast skill.

Kick-start your project with my new book Time Series Forecasting With Python, including step-by-step tutorials
Start Machine Learning ×
and the Python source code files for all examples.
You can master applied Machine Learning
Let’s get started. without math or fancy degrees.
Find out how in this free and practical course.
Updated Jan/2017: Improved some of the code examples to be more complete.
Updated Apr/2019: Updated the link to dataset.
Email Address
Updated Aug/2019: Updated data loading to use new API.
Updated Apr/2020: Changed AR to AutoReg due to API change.
START MY EMAIL COURSE
Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 1/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

Model of Residual Errors


The difference between what was expected and what was predicted is called the residual error.

It is calculated as:

1 residual error = expected - predicted

Just like the input observations themselves, the residual errors from a time series can have temporal structure like
trends, bias, and seasonality.

Any temporal structure in the time series of residual forecast errors is useful as a diagnostic as it suggests information
that could be incorporated into the predictive model. An ideal model would leave no structure in the residual error,
just random fluctuations that cannot be modeled.

Structure in the residual error can also be modeled directly. There may be complex signals in the residual error that are
difficult to directly incorporate into the model. Instead, you can create a model of the residual error time series and
predict the expected error for your model.

The predicted error can then be subtracted from the model prediction and in turn provide an additional lift in
performance.

A simple and effective model of residual error is an autoregression. This is where some number of lagged error values
are used to predict the error at the next time step. These lag errors are combined in a linear regression model, much
like an autoregression model of the direct time series observations.

An autoregression of the residual error time series is called a Moving Average (MA) model. This is confusing because
it has nothing to do with the moving average smoothing process. Think of it as the sibling to the autoregressive (AR)
process, except on lagged residual error rather than lagged raw observations.

In this tutorial, we will develop an autoregression model of the residual error time series.

Before we dive in, let’s look at a univariate dataset for which we will develop a model.

Stop learning Time Series Forecasting the slow


Start Machine way!
Learning ×
Take my free 7-day email course and discover how to get started (with sample code).
You can master applied Machine Learning
without math or fancy degrees.
Click to sign-up and also get a free PDF Ebook version of the course.
Find out how in this free and practical course.

Start Your FREE Mini-Course Now!


Email Address

START MY EMAIL COURSE


Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 2/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

Daily Female Births Dataset


This dataset describes the number of daily female births in California in 1959.

The units are a count and there are 365 observations. The source of the dataset is credited to Newton (1988).

Download the dataset.

Download the dataset and place it in your current working directory with the filename “daily-total-female-births.csv“.

Below is an example of loading the Daily Female Births dataset from CSV.

1 from pandas import read_csv


2 from matplotlib import pyplot
3 series = read_csv('daily-total-female-births.csv', header=0, index_col=0)
4 print(series.head())
5 series.plot()
6 pyplot.show()

Running the example prints the first 5 rows of the loaded file.

1 Date
2 1959-01-01 35
3 1959-01-02 32
4 1959-01-03 30
5 1959-01-04 31
6 1959-01-05 44
7 Name: Births, dtype: int64

The dataset is also shown in a line plot of observations over time.

Start Machine Learning ×


You can master applied Machine Learning
without math or fancy degrees.
Find out how in this free and practical course.

Email Address

START MY EMAIL COURSE


Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 3/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

Daily Total Female Births Plot

We can see that there is no obvious trend or seasonality. The dataset looks stationary, which is an expectation of using
an autoregression model.

Persistence Forecast Model


The simplest forecast that we can make is to forecast that what happened in the previous time step will be the same as
what will happen in the next time step.

StartThis
This is called the “naive forecast” or the persistence forecast model. Machine
model will Learning
provide the predictions from ×
which we can calculate the residual error time series. Alternately, we could develop an autoregression model of the
You can master applied Machine Learning
time series and use that as our model. We will not develop an autoregression model in this case for brevity and to
without math or fancy degrees.
focus on the model of residual error.
Find out how in this free and practical course.

We can implement the persistence model in Python.


Email Address
After the dataset is loaded, it is phrased as a supervised learning problem. A lagged version of the dataset is created
where the prior time step (t-1) is used as the input variable and the next time step (t+1) is taken as the output variable.
START MY EMAIL COURSE
Start Machine Learning
1 # create lagged dataset
https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 4/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

2 values = DataFrame(series.values)
3 dataframe = concat([values.shift(1), values], axis=1)
4 dataframe.columns = ['t-1', 't+1']

Next, the dataset is split into training and test sets. A total of 66% of the data is kept for training and the remaining
34% is held for the test set. No training is required for the persistence model; this is just a standard test harness
approach.

Once split, the train and test sets are separated into their input and output components.

1 # split into train and test sets


2 X = dataframe.values
3 train_size = int(len(X) * 0.66)
4 train, test = X[1:train_size], X[train_size:]
5 train_X, train_y = train[:,0], train[:,1]
6 test_X, test_y = test[:,0], test[:,1]

The persistence model is applied by predicting the output value (y) as a copy of the input value (x).

1 # persistence model
2 predictions = [x for x in test_X]

The residual errors are then calculated as the difference between the expected outcome (test_y) and the prediction
(predictions).

1 # calculate residuals
2 residuals = [test_y[i]-predictions[i] for i in range(len(predictions))]

The example puts this all together and gives us a set of residual forecast errors that we can explore this tutorial.

1 # calculate residual errors for a persistence forecast model


2 from pandas import read_csv
3 from pandas import DataFrame
4 from pandas import concat
5 from sklearn.metrics import mean_squared_error
6 from math import sqrt
7 # load data
8 series = read_csv('daily-total-female-births.csv', header=0, index_col=0, parse_dates=True, squ
9 # create lagged dataset
10 values = DataFrame(series.values)
11 dataframe = concat([values.shift(1), values], axis=1)
12 dataframe.columns = ['t', 't+1']
13 # split into train and test sets
14 X = dataframe.values
15 train_size = int(len(X) * 0.66)
16
17
train, test = X[1:train_size], X[train_size:]
train_X, train_y = train[:,0], train[:,1] Start Machine Learning ×
18 test_X, test_y = test[:,0], test[:,1]
19 # persistence model
You can master applied Machine Learning
20 predictions = [x for x in test_X]
21 # skill of persistence model without math or fancy degrees.
22 rmse = sqrt(mean_squared_error(test_y, predictions))
Find out how in this free and practical course.
23 print('Test RMSE: %.3f' % rmse)
24 # calculate residuals
25 residuals = [test_y[i]-predictions[i] for i in range(len(predictions))]
Email Address
26 residuals = DataFrame(residuals)
27 print(residuals.head())

The example then prints the RMSE and the first 5 rows of the forecast
STARTresidual errors.
MY EMAIL COURSE
Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 5/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python
1 Test RMSE: 9.151
2       0
3 0   9.0
4 1 -10.0
5 2   3.0
6 3  -6.0
7 4  30.0

We now have a residual error time series that we can model.

Autoregression of Residual Error


We can model the residual error time series using an autoregression model.

This is a linear regression model that creates a weighted linear sum of lagged residual error terms. For example:

1 error(t+1) = b0 + b1*error(t-1) + b2*error(t-2) ...+ bn*error(t-n)

We can use the autoregression model (AR) provided by the statsmodels library.

Building on the persistence model in the previous section, we can first train the model on the residual errors calculated
on the training dataset. This requires that we make persistence predictions for each observation in the training dataset,
then create the AR model, as follows.

1 # autoregressive model of residual errors


2 from pandas import read_csv
3 from pandas import DataFrame
4 from pandas import concat
5 from statsmodels.tsa.ar_model import AutoReg
6 series = read_csv('daily-total-female-births.csv', header=0, index_col=0, parse_dates=True, squ
7 # create lagged dataset
8 values = DataFrame(series.values)
9 dataframe = concat([values.shift(1), values], axis=1)
10 dataframe.columns = ['t', 't+1']
11 # split into train and test sets
12 X = dataframe.values
13 train_size = int(len(X) * 0.66)
14 train, test = X[1:train_size], X[train_size:]
15 train_X, train_y = train[:,0], train[:,1]
16 test_X, test_y = test[:,0], test[:,1]
17 # persistence model on training set
18 train_pred = [x for x in train_X]
19 # calculate residuals
20 train_resid = [train_y[i]-train_pred[i] for i in range(len(train_pred))]
21 # model the training set residuals
22 model = AutoReg(train_resid, lags=15) Start Machine Learning ×
23 model_fit = model.fit()
24 print('Coef=%s' % (model_fit.params))
You can master applied Machine Learning
without math
Running this piece prints the chosen lag of the 16 coefficients (intercept andorone
fancy
fordegrees.
each lag) of the trained linear
regression model. Find out how in this free and practical course.

1 Coef=[ 0.10120699 -0.84940615 -0.77783609 -0.73345006 -0.68902061 -0.59270551


Email Address
2 -0.5376728  -0.42553356 -0.24861246 -0.19972102 -0.15954013 -0.11045476
3 -0.14045572 -0.13299964 -0.12515801 -0.03615774]

Next, we can step through the test dataset and for each time step START
we must:
MY EMAIL COURSE
Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 6/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

1. Calculate the persistence prediction (t+1 = t-1).


2. Predict the residual error using the autoregression model.

The autoregression model requires the residual error of the 15 previous time steps. Therefore, we must keep these
values handy.

As we step through the test dataset timestep by timestep making predictions and estimating error, we can then
calculate the actual residual error and update the residual error time series lag values (history) so that we can calculate
the error at the next time step.

This is a walk forward forecast, or a rolling forecast, model.

We end up with a time series of the residual forecast error from the train dataset and a predicted residual error on the
test dataset.

We can plot these and get a quick idea of how skillful the model is at predicting residual error. The complete example
is listed below.

1 # forecast residual forecast error


2 from pandas import read_csv
3 from pandas import DataFrame
4 from pandas import concat
5 from statsmodels.tsa.ar_model import AutoReg
6 from matplotlib import pyplot
7 series = read_csv('daily-total-female-births.csv', header=0, index_col=0, parse_dates=True, squ
8 # create lagged dataset
9 values = DataFrame(series.values)
10 dataframe = concat([values.shift(1), values], axis=1)
11 dataframe.columns = ['t', 't+1']
12 # split into train and test sets
13 X = dataframe.values
14 train_size = int(len(X) * 0.66)
15 train, test = X[1:train_size], X[train_size:]
16 train_X, train_y = train[:,0], train[:,1]
17 test_X, test_y = test[:,0], test[:,1]
18 # persistence model on training set
19 train_pred = [x for x in train_X]
20 # calculate residuals
21 train_resid = [train_y[i]-train_pred[i] for i in range(len(train_pred))]
22 # model the training set residuals
23 window = 15
24 model = AutoReg(train_resid, lags=window)
25 model_fit = model.fit()
26
27
coef = model_fit.params
# walk forward over time steps in test Start Machine Learning ×
28 history = train_resid[len(train_resid)-window:]
29 history = [history[i] for i in range(len(history))]
You can master applied Machine Learning
30 predictions = list()
31 expected_error = list() without math or fancy degrees.
32 for t in range(len(test_y)): Find out how in this free and practical course.
33 # persistence
34 yhat = test_X[t]
35 error = test_y[t] - yhat Email Address
36 expected_error.append(error)
37 # predict error
38 length = len(history)
39 lag = [history[i] for i in range(length-window,length)]
START MY EMAIL COURSE
40 pred_error = coef[0] Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 7/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

41 for d in range(window):
42 pred_error += coef[d+1] * lag[window-d-1]
43 predictions.append(pred_error)
44 history.append(error)
45 print('predicted error=%f, expected error=%f' % (pred_error, error))
46 # plot predicted error
47 pyplot.plot(expected_error)
48 pyplot.plot(predictions, color='red')
49 pyplot.show()

Running the example first prints the predicted and expected residual error for each time step in the test dataset.

1 ...
2 predicted error=-1.951332, expected error=-10.000000
3 predicted error=6.675538, expected error=3.000000
4 predicted error=3.419129, expected error=15.000000
5 predicted error=-7.160046, expected error=-4.000000
6 predicted error=-4.179003, expected error=7.000000
7 predicted error=-10.425124, expected error=-5.000000

Next, the actual residual error for the time series is plotted (blue) compared to the predicted residual error (red).

Start Machine Learning ×


You can master applied Machine Learning
without math or fancy degrees.
Find out how in this free and practical course.

Email Address
Prediction of Residual Error Time Series

Now that we know how to model residual error, next we will look at how we can go about correcting forecasts and
START MY EMAIL COURSE
improving model skill. Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 8/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

Correct Predictions with a Model of Residual Errors


A model of forecast residual error is interesting, but it can also be useful to make better predictions.

With a good estimate of forecast error at a time step, we can make better predictions.

For example, we can add the expected forecast error to a prediction to correct it and in turn improve the skill of the
model.

1 improved forecast = forecast + estimated error

Let’s make this concrete with an example.

Let’s say that the expected value for a time step is 10. The model predicts 8 and estimates the error to be 3. The
improved forecast would be:

1 improved forecast = forecast + estimated error


2 improved forecast = 8 + 3
3 improved forecast = 11

This takes the actual forecast error from 2 units to 1 unit.

We can update the example from the previous section to add the estimated forecast error to the persistence forecast as
follows:

1 # correct the prediction


2 yhat = yhat + pred_error

The complete example is listed below.

1 # correct forecasts with a model of forecast residual errors


2 from pandas import read_csv
3 from pandas import DataFrame
4 from pandas import concat
5 from statsmodels.tsa.ar_model import AutoReg
6 from matplotlib import pyplot
7 from sklearn.metrics import mean_squared_error
8 from math import sqrt
9 # load data
10 series = read_csv('daily-total-female-births.csv', header=0, index_col=0, parse_dates=True, squ
11 # create lagged dataset
12 values = DataFrame(series.values)
13
14
dataframe = concat([values.shift(1), values], axis=1)
dataframe.columns = ['t', 't+1'] Start Machine Learning ×
15 # split into train and test sets
16 X = dataframe.values You can master applied Machine Learning
17 train_size = int(len(X) * 0.66)
without math or fancy degrees.
18 train, test = X[1:train_size], X[train_size:]
19 train_X, train_y = train[:,0], train[:,1] Find out how in this free and practical course.
20 test_X, test_y = test[:,0], test[:,1]
21 # persistence model on training set
22 train_pred = [x for x in train_X] Email Address
23 # calculate residuals
24 train_resid = [train_y[i]-train_pred[i] for i in range(len(train_pred))]
25 # model the training set residuals
26 window = 15 START MY EMAIL COURSE
27 model = AutoReg(train_resid, lags=15) Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 9/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python
28 model_fit = model.fit()
29 coef = model_fit.params
30 # walk forward over time steps in test
31 history = train_resid[len(train_resid)-window:]
32 history = [history[i] for i in range(len(history))]
33 predictions = list()
34 for t in range(len(test_y)):
35 # persistence
36 yhat = test_X[t]
37 error = test_y[t] - yhat
38 # predict error
39 length = len(history)
40 lag = [history[i] for i in range(length-window,length)]
41 pred_error = coef[0]
42 for d in range(window):
43 pred_error += coef[d+1] * lag[window-d-1]
44 # correct the prediction
45 yhat = yhat + pred_error
46 predictions.append(yhat)
47 history.append(error)
48 print('predicted=%f, expected=%f' % (yhat, test_y[t]))
49 # error
50 rmse = sqrt(mean_squared_error(test_y, predictions))
51 print('Test RMSE: %.3f' % rmse)
52 # plot predicted error
53 pyplot.plot(test_y)
54 pyplot.plot(predictions, color='red')
55 pyplot.show()

Running the example prints the predictions and the expected outcome for each time step in the test dataset.

The RMSE of the corrected forecasts is calculated to be 7.499, which is much better than the score of 9.151 for the
persistence model alone.

1 ...
2 predicted=40.675538, expected=37.000000
3 predicted=40.419129, expected=52.000000
4 predicted=44.839954, expected=48.000000
5 predicted=43.820997, expected=55.000000
6 predicted=44.574876, expected=50.000000
7 Test RMSE: 7.499

Finally, the expected values for the test dataset are plotted (blue) compared to the corrected forecast (red).

We can see that the persistence model has been aggressively corrected back to a time series that looks something like
a moving average.

Start Machine Learning ×


You can master applied Machine Learning
without math or fancy degrees.
Find out how in this free and practical course.

Email Address

START MY EMAIL COURSE


Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 10/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

Corrected Persistence Forecast for Daily Female Births

Summary
In this tutorial, you discovered how to model residual error time series and use it to correct predictions with Python.

Specifically, you learned:

About the Moving Average (MA) approach to developing an autoregressive model to residual error.
How to develop and evaluate a model of residual error to predict forecast error.
Start and
How to use the predictions of forecast error to correct predictions Machine Learning
improve model skill. ×
Do you have any questions about Moving Average models, or about
You canthis tutorial?
master applied Machine Learning
without
Ask your questions in the comments below and I will do my best math or fancy degrees.
to answer.
Find out how in this free and practical course.

Email Address
Want to Develop Time Series Forecasts with Python?
START
Develop Your Own Forecasts inMY EMAIL COURSE
Minutes
Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 11/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

...with just a few lines of python code


Discover how in my new Ebook:
Introduction to Time Series Forecasting With Python

It covers self-study tutorials and end-to-end projects on topics like: Loading data,
visualization, modeling, algorithm tuning, and much more...

Finally Bring Time Series Forecasting to


Your Own Projects
Skip the Academics. Just Results.

SEE WHAT'S INSIDE

Tweet Share Share

About Jason Brownlee


Jason Brownlee, PhD is a machine learning specialist who teaches developers how to get results with modern
machine learning methods via hands-on tutorials.
View all posts by Jason Brownlee →

How to Create an ARIMA Model for Time Series Forecasting in Python


A Gentle Introduction to the Box-Jenkins Method for Time Series Forecasting

51 Responses to How to Model Residual Errors to Correct Time Series Forecasts with
Python
Start Machine Learning ×
REPLY 
dj January 17, 2017 at 2:34 pm #
You can master applied Machine Learning
without math or fancy degrees.
Is anyone else finding that these tutorials just don’t work?
Find out how in this free and practical course.

Email Address
REPLY 
Jason Brownlee January 17, 2017 at 2:38 pm #

Sorry to hear that, what problem are you getting exactly?


START MY EMAIL COURSE
Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 12/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

Update: I updated the first two code examples to be more complete/easier to run directly.

REPLY 
nanda December 19, 2019 at 6:35 pm #

Hai jason, Is there any way to forecast auto correlated residual without having test data residuals

REPLY 
Jason Brownlee December 20, 2019 at 6:41 am #

Perhaps. You have complete freedom over how the problem is framed, e.g. the inputs and
outputs.

Be sure to choose inputs that you have available at prediction time.

REPLY 
lucy August 24, 2019 at 12:14 pm #

hi,how to know lag numer?

REPLY 
r4ever January 15, 2018 at 3:40 pm #

can I conclude above process as how arima(p,d,q) process works in background?

REPLY 
Jason Brownlee January 16, 2018 at 7:30 am #

Sorry, I don’t follow. Perhaps you can restate your question with more context?

REPLY 
darkphoenix February 19, 2018 at 9:27 am #
Start Machine Learning ×
i’m trying to model residual from arima using ann,it’s called hybrid arima. do you have any clue?
You can master applied Machine Learning
without math or fancy degrees.
Find out how in this free and practical course.
REPLY 
Jason Brownlee February 19, 2018 at 10:39 am #

What is the problem you are having exactly? Email Address

START MY EMAIL COURSE


Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 13/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

REPLY 
Gurudev April 21, 2018 at 1:36 am #

Sir Actually he is taking about Hybride ARIMA-ANN model G. Peter Zhang model in which
residuals are modeled by ANN ..
Problem is that how such small set of residuals are modeled by ANN…
Thanks in advance

REPLY 
Kue Bum Kim December 30, 2018 at 11:28 pm #

Thank you for the tutorial. Would you please explain this tutorial with matlab?

REPLY 
Jason Brownlee December 31, 2018 at 6:10 am #

Sorry, I don’t have matlab tutorials, it is a platform that is only used in school – not on business projects.

REPLY 
Rima January 7, 2019 at 8:04 pm #

Hello Jason,
I used an SARIMAX model for my time series data and when calculating residual error for the test and train set, I
observed a seasonality in the residual error. Do you think should I re-correct the SARIMAX model somehow or I can
implement the above method you explained to the residual error?

Thank you Jason!


Have a good day.

PS: It will be useful to receive email from you whenever you reply to our messages.

REPLY 
Jason Brownlee January 8, 2019 at 6:47 am #

possible.
Start Machine Learning ×
Yes, if there is a signal in the residual errors then the model should be updated to also cover that signal if

You can master applied Machine Learning


without math or fancy degrees.
Find out how in this free and practical course.
REPLY 
Fatima August 31, 2019 at 5:38 am #

Hello Jason, Email Address

“We can model the residual error time series using an autoregression model”
STARTerror
Would it be perhaps possible ( and more accurate) to model the Start
residual MY EMAIL aCOURSE
Machineusing machine learning model?
Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 14/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

REPLY 
Jason Brownlee August 31, 2019 at 6:13 am #

Why?

REPLY 
Hiyam September 10, 2019 at 9:19 pm #

Hello Jason, I wanted to ask the same question as Fatima.

In my case, the dataset is actually multivariate, and I want to model the residual error on this multivariate
dataset, and I assume the AR model won’t work in my case. Can I use the classical ML models for the same
purpose ?

REPLY 
Hiyam September 10, 2019 at 9:20 pm #

Know that, I do have the lags included in my dataset

REPLY 
Jason Brownlee September 11, 2019 at 5:34 am #

Perhaps try a range of models including linear and machine learning and discover what works
best for your specific dataset.

REPLY 
Winnie September 12, 2019 at 1:28 am #

Hi Jason,
I do not quite understand how you got
‘next time step (t+1) is taken as the output variable’

It seems you used the values at time t as the values at time t+1.
Should it be ” values.shift(-1) ” ?
Start Machine Learning ×
Thank you very much!
You can master applied Machine Learning
without math or fancy degrees.
Find out how in this free and practical course.
REPLY 
Jason Brownlee September 12, 2019 at 5:20 am #
Email Address
Yes, I use t+1 for t. It was not a good choice of terminology.

START MY EMAIL COURSE


Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 15/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

REPLY 
Row November 7, 2019 at 12:44 pm #

Hello Jason,
Thanks again for all your helpful tutorials!
I was reading about regression with ARMA errors on Rob Hyndman’s blog
(https://robjhyndman.com/hyndsight/arimax/). Is it similar to what you have here except yours used a persistance model
instead of ARMA / ARIMA?
Row

REPLY 
Jason Brownlee November 7, 2019 at 2:06 pm #

Yes, ARIMA is ARMA wit the added differencing step.

REPLY 
Row November 7, 2019 at 2:47 pm #

Thank you, Jason.

REPLY 
Jason Brownlee November 8, 2019 at 6:37 am #

You’re welcome.

REPLY 
Howbow December 4, 2019 at 10:36 pm #

Hi Jason,

thank you for posting this example.


In your example you are forecasting 1 step into the future, but what if you had to forecast lets say 10 steps ahead using
this a persistence model combined with this error correction model?
Would you simply forecast the errors by changing the code to:

model_fit.forecast()[10] ?
Start Machine Learning ×
You can
In general, I think it would be useful if you would show an example master applied
of multiple Machine
steps ahead outLearning
of sample forecasts.
without math or fancy degrees.
Cheers!
Find out how in this free and practical course.

Email Address
REPLY 
Jason Brownlee December 5, 2019 at 6:41 am #

Call model.forecsat(10) START MY EMAIL COURSE


Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 16/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

REPLY 
Shashank December 19, 2019 at 4:41 am #

history = train_resid[len(train_resid)-window:]
history = [history[i] for i in range(len(history))]

The first line outputs the same result as the second one. Could you explain why you have included them both? Thank
you.

REPLY 
Jason Brownlee December 19, 2019 at 6:34 am #

Typo, I expect.

REPLY 
Shashank December 19, 2019 at 9:08 am #

Thanks for your reply. I made an ARIMA forecast for my dataset, for which I would like to forecast
the errors too. Should I make a training set, fit the ARIMA model, forecast for the length of the test set and
then get the errors from the test set? Or does it differ when using the ARIMA approach?

REPLY 
Jason Brownlee December 19, 2019 at 12:48 pm #

Yes, that sounds reasonable. Be sure to collect errors in the same way as obs, e.g. step-by-step or
sequence by sequence.

Shashank December 20, 2019 at 5:06 am #

So I collected the errors step by step, and then checked for stationarity using the ADF and
KPSS tests, which tell me that the errors are stationary. Then I fit an ARIMA(0, 0, 0) model on the
errors after taking a look at the autocorrelation and partial autocorrelation plots. This model kind of
Start
averages out and is not very flexible, in the sense that itMachine Learning
doesn’t capture ×
spikes in the data, i.e., where
the errors deviate a lot from the mean. Is there a way to fit a more flexible model or use a different
one perhaps? Please let me know. Thanks! You can master applied Machine Learning
without math or fancy degrees.
Find out how in this free and practical course.

Jason Brownlee December 20, 2019 at 6:53


Email
am #Address

Well done!
START MY EMAIL COURSE
Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 17/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

Perhaps try a suite of models and model configurations and discover what works best for your
dataset.

REPLY 
Adonis El Hajj March 18, 2020 at 5:53 pm #

Hi Jason,
is it possible to mix LSTM with a residual architecture?
thank you in advance.

REPLY 
Jason Brownlee March 19, 2020 at 6:21 am #

Yes, residual errors can be provided as input to the model.

REPLY 
Saurabh April 7, 2020 at 8:50 am #

Hi Jason,

Thanks a lot for your work! Is it safe to assume that the process that you laid out in this blog is exactly what happens
behind-the-scenes if I include an MA term in the ARIMA model?

REPLY 
Jason Brownlee April 7, 2020 at 1:28 pm #

Very close.

REPLY 
Danilel May 1, 2020 at 3:13 am #

Hi Jason,

Contrasting the described 2-step approach of separately estimating models (first for response then for residuals) and
Start
subsequently combining them in the forecast step with estimation Machine
in the likes of GLMMLearning
or Transfer Functions Models
×
where we (can) impose some correlation structure on the errors directly: are there any pitfalls if the practical objective
You can master applied Machine Learning
is only a “good” forecast as measured here by RMSE (instead of say hypothesis testing on parameters)?
without math or fancy degrees.
Thanks for your great work, I really appreciate it. Find out how in this free and practical course.

Email Address

REPLY 
Jason Brownlee May 1, 2020 at 6:45 am #
START MY EMAIL COURSE
Start
Sorry, not sure I follow your question. Perhaps you can Machine
restate it?Learning
https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 18/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

REPLY 
Danilel May 1, 2020 at 7:20 pm #

In the article you say:


“Structure in the residual error can also be modeled directly. There may be complex signals in the residual
error that are difficult to directly incorporate into the model. Instead, you can create a model of the residual
error time series and predict the expected error for your model.”

Now the question is: in which cases is direct modelling of error structure preferred over the proposed 2-step
method?

I guess standard errors of parameters are affected, but is there any practical difference regarding forecast
performance alone?

Thanks

REPLY 
Jason Brownlee May 2, 2020 at 5:42 am #

No, use results/data to guide model selection.

Perhaps try both approaches and use the model that has better skill/less error.

REPLY 
TalaOwis May 9, 2020 at 2:04 am #

I was wondering if ARMARESULT.resid gives the actual residuals .I want to use those residuals in a different
model .but the size of the array it return is 55 and the dataset I am fitting is 57 .

REPLY 
Jason Brownlee May 9, 2020 at 6:19 am #

Perhaps the model had a difference of 2 to account for the number of residuals?

Start Machine Learning ×


REPLY 
TalaOwis May 9, 2020 at 7:49 am #
You can master applied Machine Learning
you mean the q value is 2 ? without math or fancy degrees.
Find out how in this free and practical course.

Email Address
REPLY 
TalaOwis May 9, 2020 at 7:59 am #

If q is the reason why I am getting those results ,how wouldMY


START I align
EMAILtheCOURSE
residuals along with the time
Start Machine Learning
series data to feed them into another model like LSTM?
https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 19/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

If you can answer me and give me an example or any referrence I will be grateful .

REPLY 
Jason Brownlee May 9, 2020 at 1:48 pm #

I don’t have an example, you will have to experiment.

REPLY 
Jason Brownlee May 9, 2020 at 1:48 pm #

Yes.

REPLY 
Parth May 28, 2020 at 11:21 pm #

Good post. Have a question on 1 point.


Initially blog mentions this point

“There may be complex signals in the residual error that are difficult to directly incorporate into the model. ”

Regarding this, question is, can you share some ideas or techniques through which we can detect such structure in
residual series. This will help to determine, if we need to do residual modelling or not, in first place.

REPLY 
Jason Brownlee May 29, 2020 at 6:32 am #

Sometimes, simply fitting a model on the residuals can lift performance.

REPLY 
Vignesh Aravind June 28, 2020 at 8:48 am #

Hi Jason.. on the explanation about White noise… You mentioned that the only error after we extracted the
signal from any time series should be White Noise. But that is the ideal model which we try to achieve…But there is
always some Residual errors which we calculate from the Error measures like RSME… So basically any model would
Start
have both Residual errors which are reducible and White noise that Machine Learning
are irreducible?
×
As George Box said “All models are wrong but some are useful”.
You can master applied Machine Learning
without math or fancy degrees.
Find out how in this free and practical course.
REPLY 
Jason Brownlee June 29, 2020 at 6:24 am #
Email Address
Ideally we would get to the point where the residual error is comprise of white noise only.

This is an ideal, not possible or very hard to achieve in practice.


START MY EMAIL COURSE
Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 20/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

Leave a Reply

Name (required)

Email (will not be published) (required)

Website

SUBMIT COMMENT

Welcome!
I'm Jason Brownlee PhD
and I help developers get results with machine learning.
Read more

Picked for you:

How to Create an ARIMA Model for Time Series Forecasting in Python

Start Machine Learning ×


How to Convert a Time Series to a Supervised Learning Problem in Python
You can master applied Machine Learning
without math or fancy degrees.
Find out how in this free and practical course.

11 Classical Time Series Forecasting Methods in Python (Cheat Sheet)


Email Address

START MY EMAIL COURSE


Time Series Forecasting as Supervised Learning Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 21/22
8/22/2020 How to Model Residual Errors to Correct Time Series Forecasts with Python

How To Backtest Machine Learning Models for Time Series Forecasting

Loving the Tutorials?

The Time Series with Python playbook is


where you'll find the Really Good stuff.

>> SEE WHAT'S INSIDE

© 2020 Machine Learning Mastery Pty. Ltd. All Rights Reserved.


Address: PO Box 206, Vermont Victoria 3133, Australia. | ACN: 626 223 336.
LinkedIn | Twitter | Facebook | Newsletter | RSS

Privacy | Disclaimer | Terms | Contact | Sitemap | Search

Start Machine Learning ×


You can master applied Machine Learning
without math or fancy degrees.
Find out how in this free and practical course.

Email Address

START MY EMAIL COURSE


Start Machine Learning

https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 22/22

You might also like