## 开发（python）

»# How to Model Residual Errors to Correct Time Series Forecasts with Python

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.Let’s get started.

Model of Residual ErrorsThe difference between what was expected and what was predicted is called the residual error.

It is calculated as:

residual error = expected - predictedJust 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.

Daily Female Births DatasetThis 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 and learn more about the dataset here .

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.

frompandasimportSeries frommatplotlibimportpyplot series = Series.from_csv('daily-total-female-births.csv', header=0) print(series.head()) series.plot() pyplot.show()Running the example prints the first 5 rows of the loaded file.

Date 1959-01-01 35 1959-01-02 32 1959-01-03 30 1959-01-04 31 1959-01-05 44 Name: Births, dtype: int64The dataset is also shown in a line plot of observations over time.

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 ModelThe 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.

This is called the “naive forecast” or the persistence forecast model. This model will provide the predictions from which we can calculate the residual error time series. Alternately, we could develop an autoregression model of the time series and use that as our model. We will not develop an autoregression model in this case for brevity and to focus on the model of residual error.

We can implement the persistence model in Python.

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.

# create lagged dataset values = DataFrame(series.values) dataframe = concat([values.shift(1), values], axis=1) 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.

# split into train and test sets X = dataframe.values train_size = int(len(X) * 0.66) train, test = X[1:train_size], X[train_size:] train_X, train_y = train[:,0], train[:,1] 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 ).

# persistence model 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 ).

# calculate residuals 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 explorethis tutorial.

frompandasimportSeries frompandasimportDataFrame frompandasimportconcat series = Series.from_csv('daily-total-female-births.csv', header=0) # create lagged dataset values = DataFrame(series.values) dataframe = concat([values.shift(1), values], axis=1) dataframe.columns = ['t-1', 't+1'] # split into train and test sets X = dataframe.values train_size = int(len(X) * 0.66) train, test = X[1:train_size], X[train_size:] train_X, train_y = train[:,0], train[:,1] test_X, test_y = test[:,0], test[:,1] # persistence model predictions = [x for x in test_X] # calculate residuals residuals = [test_y[i]-predictions[i] for i in range(len(predictions))] residuals = DataFrame(residuals) print(residuals.head())Running the example prints the mean squared error for the predictions at 83.744.

The example then prints the first 5 rows of the forecast residual errors.

Test MSE: 83.744 0 0 9.0 1 -10.0 2 3.0 3-6.0 430.0Finally, the residual time series is plotted.

Daily Female Births Persistence Model Residual Error Time Series

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

Autoregression of Residual ErrorWe 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 re本文开发（python）相关术语:python基础教程 python多线程 web开发工程师 软件开发工程师 软件开发流程

本文标题：How to Model Residual Errors to Correct Time Series Forecasts with Python

本站链接：http://www.codesec.net/view/522951.html

分享请点击：

1.凡CodeSecTeam转载的文章,均出自其它媒体或其他官网介绍,目的在于传递更多的信息,并不代表本站赞同其观点和其真实性负责；

2.转载的文章仅代表原创作者观点,与本站无关。其原创性以及文中陈述文字和内容未经本站证实,本站对该文以及其中全部或者部分内容、文字的真实性、完整性、及时性，不作出任何保证或承若；

3.如本站转载稿涉及版权等问题,请作者及时联系本站,我们会及时处理。