Saturday, June 30, 2018

A way to Grid Search ARIMA Model Hyperparameters with Python

There are 3 parameters that require estimation by iterative trial and error from reviewing diagnostic plots and using 40-year-old heuristic rules.
We can automate the process of evaluating a large number of hyperparameters for the ARIMA model by using a grid search procedure.
In this tutorial, you will discover how to tune the ARIMA model using a grid search of hyperparameters in Python.
After completing this tutorial, you will know:
  • A general procedure that you can use to tune the ARIMA hyperparameters for a rolling one-step forecast.
  • How to apply ARIMA hyperparameter optimization on a standard univariate time series dataset.
  • Ideas for extending the procedure for more elaborate and robust models.
Let’s get started.

Grid Searching Method

Diagnostic plots of the time series can be used along with heuristic rules to determine the hyperparameters of the ARIMA model.
These are good in most, but perhaps not all, situations.
We can automate the process of training and evaluating ARIMA models on different combinations of model hyperparameters. In machine learning this is called a grid search or model tuning.
In this tutorial, we will develop a method to grid search ARIMA hyperparameters for a one-step rolling forecast.
The approach is broken down into two parts:
  1. Evaluate an ARIMA model.
  2. Evaluate sets of ARIMA parameters.
The code in this tutorial makes use of the scikit-learn, Pandas, and the statsmodels Python libraries.

1. Evaluate ARIMA Model

We can evaluate an ARIMA model by preparing it on a training dataset and evaluating predictions on a test dataset.
This approach involves the following steps:
  1. Split the dataset into training and test sets.
  2. Walk the time steps in the test dataset.
    1. Train an ARIMA model.
    2. Make a one-step prediction.
    3. Store prediction; get and store actual observation.
  3. Calculate error score for predictions compared to expected values.
We can implement this in Python as a new standalone function called evaluate_arima_model() that takes a time series dataset as input as well as a tuple with the pd, and q parameters for the model to be evaluated.
The dataset is split in two: 66% for the initial training dataset and the remaining 34% for the test dataset.
Each time step of the test set is iterated. Just one iteration provides a model that you could use to make predictions on new data. The iterative approach allows a new ARIMA model to be trained each time step.
A prediction is made each iteration and stored in a list. This is so that at the end of the test set, all predictions can be compared to the list of expected values and an error score calculated. In this case, a mean squared error score is calculated and returned.
The complete function is listed below.
Now that we know how to evaluate one set of ARIMA hyperparameters, let’s see how we can call this function repeatedly for a grid of parameters to evaluate.

2. Iterate ARIMA Parameters

Evaluating a suite of parameters is relatively straightforward.
The user must specify a grid of pd, and q ARIMA parameters to iterate. A model is created for each parameter and its performance evaluated by calling the evaluate_arima_model()function described in the previous section.
The function must keep track of the lowest error score observed and the configuration that caused it. This can be summarized at the end of the function with a print to standard out.
We can implement this function called evaluate_models() as a series of four loops.
There are two additional considerations. The first is to ensure the input data are floating point values (as opposed to integers or strings), as this can cause the ARIMA procedure to fail.
Second, the statsmodels ARIMA procedure internally uses numerical optimization procedures to find a set of coefficients for the model. These procedures can fail, which in turn can throw an exception. We must catch these exceptions and skip those configurations that cause a problem. This happens more often then you would think.
Additionally, it is recommended that warnings be ignored for this code to avoid a lot of noise from running the procedure. This can be done as follows:
Finally, even with all of these protections, the underlying C and Fortran libraries may still report warnings to standard out, such as:
These have been removed from the results reported in this tutorial for brevity.
The complete procedure for evaluating a grid of ARIMA hyperparameters is listed below.
Now that we have a procedure to grid search ARIMA hyperparameters, let’s test the procedure on two univariate time series problems.
We will start with the Shampoo Sales dataset.

Shampoo Sales Case Study

The Shampoo Sales dataset describes the monthly number of sales of shampoo over a 3-year period.
The units are a sales count and there are 36 observations. The original dataset is credited to Makridakis, Wheelwright, and Hyndman (1998).
Download the dataset and place it into your current working directory with the filename “shampoo-sales.csv“.
The timestamps in the time series do not contain an absolute year component. We can use a custom date-parsing function when loading the data and baseline the year from 1900, as follows:
Once loaded, we can specify a site of pd, and q values to search and pass them to the evaluate_models() function.
We will try a suite of lag values (p) and just a few difference iterations (d) and residual error lag values (q).
Putting this all together with the generic procedures defined in the previous section, we can grid search ARIMA hyperparameters in the Shampoo Sales dataset.
The complete code example is listed below.
Running the example prints the ARIMA parameters and MSE for each successful evaluation completed.
The best parameters of ARIMA(4, 2, 1) are reported at the end of the run with a mean squared error of 4,694.873.

Daily Female Births Case Study

The Daily Female Births 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 and place it in your current working directory with the filename “daily-total-female-births.csv“.
This dataset can be easily loaded directly as a Pandas Series.
To keep things simple, we will explore the same grid of ARIMA hyperparameters as in the previous section.
Putting this all together, we can grid search ARIMA parameters on the Daily Female Births dataset. The complete code listing is provided below.
Running the example prints the ARIMA parameters and mean squared error for each configuration successfully evaluated.
The best mean parameters are reported as ARIMA(6, 1, 0) with a mean squared error of 53.187.

Extensions

The grid search method used in this tutorial is simple and can easily be extended.
This section lists some ideas to extend the approach you may wish to explore.
  • Seed Grid. The classical diagnostic tools of ACF and PACF plots can still be used with the results used to seed the grid of ARIMA parameters to search.
  • Alternate Measures. The search seeks to optimize the out-of-sample mean squared error. This could be changed to another out-of-sample statistic, an in-sample statistic, such as AIC or BIC, or some combination of the two. You can choose a metric that is most meaningful on your project.
  • Residual Diagnostics. Statistics can automatically be calculated on the residual forecast errors to provide an additional indication of the quality of the fit. Examples include statistical tests for whether the distribution of residuals is Gaussian and whether there is an autocorrelation in the residuals.
  • Update Model. The ARIMA model is created from scratch for each one-step forecast. With careful inspection of the API, it may be possible to update the internal data of the model with new observations rather than recreating it from scratch.
  • Preconditions. The ARIMA model can make assumptions about the time series dataset, such as normality and stationarity. These could be checked and a warning raised for a given of a dataset prior to a given model being trained.