Hire a web Developer and Designer to upgrade and boost your online presence with cutting edge Technologies

Saturday 7 September 2024

Weight Regularization with LSTM Networks for Time Series Forecasting

 Long Short-Term Memory (LSTM) models are a recurrent neural network capable of learning sequences of observations.

This may make them a network well suited to time series forecasting.

An issue with LSTMs is that they can easily overfit training data, reducing their predictive skill.

Weight regularization is a technique for imposing constraints (such as L1 or L2) on the weights within LSTM nodes. This has the effect of reducing overfitting and improving model performance.

In this tutorial, you will discover how to use weight regularization with LSTM networks and design experiments to test for its effectiveness for time series forecasting.

After completing this tutorial, you will know:

  • How to design a robust test harness for evaluating LSTM networks for time series forecasting.
  • How to design, execute, and interpret the results from using bias weight regularization with LSTMs.
  • How to design, execute, and interpret the results from using input and recurrent weight regularization with LSTMs.

    Tutorial Overview

    This tutorial is broken down into 6 parts. They are:

    1. Shampoo Sales Dataset
    2. Experimental Test Harness
    3. Bias Weight Regularization
    4. Input Weight Regularization
    5. Recurrent Weight Regularization
    6. Review of Results

    Environment

    This tutorial assumes you have a Python SciPy environment installed. You can use either Python 2 or 3 with this example.

    This tutorial assumes you have Keras v2.0 or higher installed with either the TensorFlow or Theano backend.

    This tutorial also assumes you have scikit-learn, Pandas, NumPy, and Matplotlib installed.Next, let’s take a look at a standard time series forecasting problem that we can use as context for this experiment.

    Shampoo Sales Dataset

    This 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).

    The example below loads and creates a plot of the loaded dataset.

    Running the example loads the dataset as a Pandas Series and prints the first 5 rows.

    A line plot of the series is then created showing a clear increasing trend.

    Line Plot of Shampoo Sales Dataset

    Line Plot of Shampoo Sales Dataset

    Next, we will take a look at the model configuration and test harness used in the experiment.

    Experimental Test Harness

    This section describes the test harness used in this tutorial.

    Data Split

    We will split the Shampoo Sales dataset into two parts: a training and a test set.

    The first two years of data will be taken for the training dataset and the remaining one year of data will be used for the test set.

    Models will be developed using the training dataset and will make predictions on the test dataset.

    The persistence forecast (naive forecast) on the test dataset achieves an error of 136.761 monthly shampoo sales. This provides a lower acceptable bound of performance on the test set.

    Model Evaluation

    A rolling-forecast scenario will be used, also called walk-forward model validation.

    Each time step of the test dataset will be walked one at a time. A model will be used to make a forecast for the time step, then the actual expected value from the test set will be taken and made available to the model for the forecast on the next time step.

    This mimics a real-world scenario where new Shampoo Sales observations would be available each month and used in the forecasting of the following month.

    This will be simulated by the structure of the train and test datasets.

    All forecasts on the test dataset will be collected and an error score calculated to summarize the skill of the model. The root mean squared error (RMSE) will be used as it punishes large errors and results in a score that is in the same units as the forecast data, namely monthly shampoo sales.

    Data Preparation

    Before we can fit a model to the dataset, we must transform the data.

    The following three data transforms are performed on the dataset prior to fitting a model and making a forecast.

    1. Transform the time series data so that it is stationary. Specifically, a lag=1 differencing to remove the increasing trend in the data.
    2. Transform the time series into a supervised learning problem. Specifically, the organization of data into input and output patterns where the observation at the previous time step is used as an input to forecast the observation at the current timestep
    3. Transform the observations to have a specific scale. Specifically, to rescale the data to values between -1 and 1.

    These transforms are inverted on forecasts to return them into their original scale before calculating and error score.

    LSTM Model

    We will use a base stateful LSTM model with 1 neuron fit for 1000 epochs.

    Ideally a batch size of 1 would be used for walk-foward validation. We will assume walk-forward validation and predict the whole year for speed. As such we can use any batch size that is divisble by the number of samples, in this case we will use a value of 4.

    Ideally, more training epochs would be used (such as 1500), but this was truncated to 1000 to keep run times reasonable.

    The model will be fit using the efficient ADAM optimization algorithm and the mean squared error loss function.

    Experimental Runs

    Each experimental scenario will be run 30 times and the RMSE score on the test set will be recorded from the end each run.

    Let’s dive into the experiments.

    Baseline LSTM Model

    Let’s start-off with the baseline LSTM model.

    The baseline LSTM model for this problem has the following configuration:

    • Lag inputs: 1
    • Epochs: 1000
    • Units in LSTM hidden layer: 3
    • Batch Size: 4
    • Repeats: 3

    The complete code listing is provided below.

    This code listing will be used as the basis for all following experiments, with only the changes to this code provided in subsequent sections.

    Running the experiment prints summary statistics for the test RMSE for all repeats.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    We can see that on average, this model configuration achieves a test RMSE of about 92 monthly shampoo sales with a standard deviation of 5.

    A box and whisker plot is also created from the distribution of test RMSE results and saved to a file.

    The plot provides a clear depiction of the spread of the results, highlighting the middle 50% of values (the box) and the median (green line).

    Box and Whisker Plot of Baseline Performance on the Shampoo Sales Dataset

    Box and Whisker Plot of Baseline Performance on the Shampoo Sales Dataset

    Bias Weight Regularization

    Weight regularization can be applied to the bias connection within the LSTM nodes.

    In Keras, this is specified with a bias_regularizer argument when creating an LSTM layer. The regularizer is defined as an instance of the one of the L1, L2, or L1L2 classes.

    More details here:

    In this experiment, we will compare L1, L2, and L1L2 with a default value of 0.01 against the baseline model. We can specify all configurations using the L1L2 class, as follows:

    • L1L2(0.0, 0.0) [e.g. baseline]
    • L1L2(0.01, 0.0) [e.g. L1]
    • L1L2(0.0, 0.01) [e.g. L2]
    • L1L2(0.01, 0.01) [e.g. L1L2 or elasticnet]

    Below lists the updated fit_lstm(), experiment(), and run() functions for using bias weight regularization with LSTMs.

    Running this experiment prints descriptive statistics for each evaluated configuration.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    The results suggest that on average, the default of no bias regularization results in better performance compared to all of the other configurations considered.

    A box and whisker plot is also created to compare the distributions of results for each configuration.

    The plot shows that all configurations have about the same spread and that the addition of bias regularization uniformly was not helpful on this problem.

    Box and Whisker Plots of Bias Weight Regularization Performance on the Shampoo Sales Dataset

    Box and Whisker Plots of Bias Weight Regularization Performance on the Shampoo Sales Dataset

    Input Weight Regularization

    We can also apply regularization to input connections on each LSTM unit.

    In Keras, this is achieved by setting the kernel_regularizer argument to a regularizer class.

    We will test the same regularizer configurations as were used in the previous section, specifically:

    • L1L2(0.0, 0.0) [e.g. baseline]
    • L1L2(0.01, 0.0) [e.g. L1]
    • L1L2(0.0, 0.01) [e.g. L2]
    • L1L2(0.01, 0.01) [e.g. L1L2 or elasticnet]

    Below lists the updated fit_lstm(), experiment(), and run() functions for using bias weight regularization with LSTMs.

    Running this experiment prints descriptive statistics for each evaluated configuration.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    The results suggest that adding weight regularization to input connections does offer benefit across the board on this setup.

    We can see that the test RMSE is approximately 10 units lower for all configurations with perhaps more benefit when both L1 and L2 are combined into an elasticnet type constraint.

    A box and whisker plot is also created to compare the distributions of results for each configuration.

    The plot shows the general lower distribution of error for input regularization. The results also suggest a tighter spread of results with regularization that may be more pronounced with the L1L2 configuration that achieved the better results.

    This is an encouraging finding, suggesting that additional experiments with different L1L2 values for input regularization would be well worth investigating.

    Box and Whisker Plots of Input Weight Regularization Performance on the Shampoo Sales Dataset

    Box and Whisker Plots of Input Weight Regularization Performance on the Shampoo Sales Dataset

    Recurrent Weight Regularization

    Finally, we can also apply regularization to recurrent connections on each LSTM unit.

    In Keras, this is achieved by setting the recurrent_regularizer argument to a regularizer class.

    We will test the same regularizer configurations as were used in the previous section, specifically:

    • L1L2(0.0, 0.0) [e.g. baseline]
    • L1L2(0.01, 0.0) [e.g. L1]
    • L1L2(0.0, 0.01) [e.g. L2]
    • L1L2(0.01, 0.01) [e.g. L1L2 or elasticnet]

    Below lists the updated fit_lstm(), experiment(), and run() functions for using bias weight regularization with LSTMs.

    Running this experiment prints descriptive statistics for each evaluated configuration.

    Note: Your results may vary given the stochastic nature of the algorithm or evaluation procedure, or differences in numerical precision. Consider running the example a few times and compare the average outcome.

    The results suggest no obvious benefit from using regularization on the recurrent connection with LSTMs on this problem.

    The mean performance of all variations tried resulted in worse performance than the baseline model.

    A box and whisker plot is also created to compare the distributions of results for each configuration.

    The plot shows the same story as the summary statistics, suggesting little benefit from using recurrent weight regularization.

    Box and Whisker Plots of Recurrent Weight Regularization Performance on the Shampoo Sales Dataset

    Box and Whisker Plots of Recurrent Weight Regularization Performance on the Shampoo Sales Dataset

    Extensions

    This section lists ideas for follow-up experiments to extend the work in this tutorial.

    • Input Weight Regularization. The experimental results for input weight regularization on this problem showed great promise of listing performance. This could be investigated further by perhaps grid searching different L1 and L2 values to find an optimal configuration.
    • Behavior Dynamics. The dynamic behavior of each weight regularization scheme could be investigated by plotting train and test RMSE over training epochs to get an idea of weight regularization on overfitting or underfitting behavior patterns.
    • Combine Regularization. Experiments could be designed to explore the effect of combining different weight regularization schemes.
    • Activation Regularization. Keras also supports activation regularization, and this could be another avenue to explore imposing constraints on the LSTM and reduce overfitting.

    Summary

    In this tutorial, you discovered how to use weight regularization with LSTMs for time series forecasting.

    Specifically, you learned:

    • How to design a robust test harness for evaluating LSTM networks for time series forecasting.
    • How to configure bias weight regularization on LSTMs for time series forecasting.
    • How to configure input and recurrent weight regularization on LSTMs for time series forecasting.

    Do you have any questions about using weight regularization with LSTM networks?
    Ask your questions in the comments below and I will do my best to answer.

No comments:

Post a Comment

Connect broadband

How to Evaluate the Skill of Deep Learning Models

 I often see practitioners expressing confusion about how to evaluate a deep learning model. This is often obvious from questions like: W...