Professional Documents
Culture Documents
Navigation
Search...
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.
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
It is calculated as:
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.
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
The units are a count and there are 365 observations. The source of the dataset is credited to Newton (1988).
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.
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
Email Address
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
We can see that there is no obvious trend or seasonality. The dataset looks stationary, which is an expectation of using
an autoregression model.
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.
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.
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.
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
This is a linear regression model that creates a weighted linear sum of lagged residual error terms. For example:
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.
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
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.
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.
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).
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
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.
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:
We can update the example from the previous section to add the estimated forecast error to the persistence forecast as
follows:
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.
Email Address
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
Summary
In this tutorial, you discovered how to model residual error time series and use it to correct predictions with Python.
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
It covers self-study tutorials and end-to-end projects on topics like: Loading data,
visualization, modeling, algorithm tuning, and much more...
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 #
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.
REPLY
lucy August 24, 2019 at 12:14 pm #
REPLY
r4ever January 15, 2018 at 3:40 pm #
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 #
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?
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
“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 #
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 #
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.
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 #
REPLY
Row November 7, 2019 at 2:47 pm #
REPLY
Jason Brownlee November 8, 2019 at 6:37 am #
You’re welcome.
REPLY
Howbow December 4, 2019 at 10:36 pm #
Hi Jason,
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 #
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.
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.
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 #
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 #
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 #
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?
Email Address
REPLY
TalaOwis May 9, 2020 at 7:59 am #
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 #
REPLY
Jason Brownlee May 9, 2020 at 1:48 pm #
Yes.
REPLY
Parth May 28, 2020 at 11:21 pm #
“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 #
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.
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)
Website
SUBMIT COMMENT
Welcome!
I'm Jason Brownlee PhD
and I help developers get results with machine learning.
Read more
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
Email Address
https://machinelearningmastery.com/model-residual-errors-correct-time-series-forecasts-python/ 22/22