In this notebook, we will use a multi-layer perceptron to develop time series forecasting models. The dataset used for the examples of this notebook is on air pollution measured by concentration of particulate matter (PM) of diameter less than or equal to 2.5 micrometers. There are other variables such as air pressure, air temparature, dewpoint and so on. Two time series models are developed - one on air pressure and the other on pm2.5. The dataset has been downloaded from UCI Machine Learning Repository. https://archive.ics.uci.edu/ml/datasets/Beijing+PM2.5+Data
No | year | month | day | hour | pm2.5 | DEWP | TEMP | PRES | cbwd | Iws | Is | Ir | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 1 | 2010 | 1 | 1 | 0 | NaN | -21 | -11.0 | 1021.0 | NW | 1.79 | 0 | 0 |
1 | 2 | 2010 | 1 | 1 | 1 | NaN | -21 | -12.0 | 1020.0 | NW | 4.92 | 0 | 0 |
2 | 3 | 2010 | 1 | 1 | 2 | NaN | -21 | -11.0 | 1019.0 | NW | 6.71 | 0 | 0 |
3 | 4 | 2010 | 1 | 1 | 3 | NaN | -21 | -14.0 | 1019.0 | NW | 9.84 | 0 | 0 |
4 | 5 | 2010 | 1 | 1 | 4 | NaN | -20 | -12.0 | 1018.0 | NW | 12.97 | 0 | 0 |
To make sure that the rows are in the right order of date and time of observations, a new column datetime is created from the date and time related columns of the DataFrame. The new column consists of Python's datetime.datetime objects. The DataFrame is sorted in ascending order over this column.
Gradient descent algorithms perform better (for example converge faster) if the variables are wihtin range [-1, 1]. Many sources relax the boundary to even [-3, 3]. The pm2.5 variable is mixmax scaled to bound the tranformed variable within [0,1].
Before training the model, the dataset is split in two parts - train set and validation set. The neural network is trained on the train set. This means computation of the loss function, back propagation and weights updated by a gradient descent algorithm is done on the train set. The validation set is used to evaluate the model and to determine the number of epochs in model training. Increasing the number of epochs will further decrease the loss function on the train set but might not neccesarily have the same effect for the validation set due to overfitting on the train set.Hence, the number of epochs is controlled by keeping a tap on the loss function computed for the validation set. We use Keras with Tensorflow backend to define and train the model. All the steps involved in model training and validation is done by calling appropriate functions of the Keras API.
No | year | month | day | hour | pm2.5 | DEWP | TEMP | PRES | cbwd | Iws | Is | Ir | datetime | scaled_pm2.5 | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
0 | 25 | 2010 | 1 | 2 | 0 | 129.0 | -16 | -4.0 | 1020.0 | SE | 1.79 | 0 | 0 | 2010-01-02 00:00:00 | 0.129779 |
1 | 26 | 2010 | 1 | 2 | 1 | 148.0 | -15 | -4.0 | 1020.0 | SE | 2.68 | 0 | 0 | 2010-01-02 01:00:00 | 0.148893 |
2 | 27 | 2010 | 1 | 2 | 2 | 159.0 | -11 | -5.0 | 1021.0 | SE | 3.57 | 0 | 0 | 2010-01-02 02:00:00 | 0.159960 |
3 | 28 | 2010 | 1 | 2 | 3 | 181.0 | -7 | -5.0 | 1022.0 | SE | 5.36 | 1 | 0 | 2010-01-02 03:00:00 | 0.182093 |
4 | 29 | 2010 | 1 | 2 | 4 | 138.0 | -7 | -5.0 | 1022.0 | SE | 6.25 | 2 | 0 | 2010-01-02 04:00:00 | 0.138833 |
No | year | month | day | hour | pm2.5 | DEWP | TEMP | PRES | cbwd | Iws | Is | Ir | datetime | scaled_pm2.5 | |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
33096 | 35065 | 2014 | 1 | 1 | 0 | 24.0 | -20 | 7.0 | 1014.0 | NW | 143.48 | 0 | 0 | 2014-01-01 00:00:00 | 0.024145 |
33097 | 35066 | 2014 | 1 | 1 | 1 | 53.0 | -20 | 7.0 | 1013.0 | NW | 147.50 | 0 | 0 | 2014-01-01 01:00:00 | 0.053320 |
33098 | 35067 | 2014 | 1 | 1 | 2 | 65.0 | -20 | 6.0 | 1013.0 | NW | 151.52 | 0 | 0 | 2014-01-01 02:00:00 | 0.065392 |
33099 | 35068 | 2014 | 1 | 1 | 3 | 70.0 | -20 | 6.0 | 1013.0 | NW | 153.31 | 0 | 0 | 2014-01-01 03:00:00 | 0.070423 |
33100 | 35069 | 2014 | 1 | 1 | 4 | 79.0 | -18 | 3.0 | 1012.0 | cv | 0.89 | 0 | 0 | 2014-01-01 04:00:00 | 0.079477 |
Now we need to generate regressors (X) and target variable (y) for train and validation. 2-D array of regressor and 1-D array of target is created from the original 1-D array of columm standardized_pm2.5 in the DataFrames. For the time series forecasting model, Past seven days of observations are used to predict for the next day. This is equivalent to a AR(7) model. We define a function which takes the original time series and the number of timesteps in regressors as input to generate the arrays of X and y.
The input to convolution layers must be of shape (number of samples, number of timesteps, number of features per timestep). In this case we are modeling only pm2.5 hence number of features per timestep is one. Number of timesteps is seven and number of samples is same as the number of samples in X_train and X_val, which are reshaped to 3D arrays.
Now we define the MLP using the Keras Functional API. In this approach a layer can be declared as the input of the following layer at the time of defining the next layer.
ZeroPadding1D layer is added next to add zeros at the begining and end of each series. Zeropadding ensure that the downstream convolution layer does not reduce the dimension of the output sequences. Pooling layer, added after the convolution layer is used to downsampling the input.
The first argument of Conv1D is the number of filters, which determine the number of features in the output. Second argument indicates length of the 1D convolution window. The third argument is strides and represent the number of places to shift the convolution window. Lastly, setting use_bias as True, add a bias value during computation of an output feature. Here, the 1D convolution can be thought of as generating local AR models over rolling window of three time units.
AveragePooling1D is added next to downsample the input by taking average over pool size of three with stride of one timesteps. The average pooling in this case can be thought of as taking moving averages over a rolling window of three time units. We have used average pooling instead of max pooling to generate the moving averages.
The preceeding pooling layer returns 3D output. Hence before passing to the output layer, a Flatten layer is added. The Flatten layer reshapes the input to (number of samples, number of timesteps*number of features per timestep), which is then fed to the output layer
The input, dense and output layers will now be packed inside a Model, which is wrapper class for training and making predictions. The box plot of pm2.5 shows the presence of outliers. Hence, mean absolute error (MAE) is used as absolute deviations suffer less fluctuations compared to squared deviations.
The network's weights are optimized by the Adam algorithm. Adam stands for adaptive moment estimation and has been a popular choice for training deep neural networks. Unlike, stochastic gradient descent, adam uses different learning rates for each weight and separately updates the same as the training progresses. The learning rate of a weight is updated based on exponentially weighted moving averages of the weight's gradients and the squared gradients.
The model is trained by calling the fit function on the model object and passing the X_train and y_train. The training is done for a predefined number of epochs. Additionally, batch_size defines the number of samples of train set to be used for a instance of back propagation.The validation dataset is also passed to evaluate the model after every epoch completes. A ModelCheckpoint object tracks the loss function on the validation set and saves the model for the epoch, at which the loss function has been minimum.
Prediction are made for the pm2.5 from the best saved model. The model's predictions, which are on the standardized pm2.5, are inverse transformed to get predictions of original pm2.5.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-23-9a710f268333> in <module>()
----> 1 best_model = load_model(os.path.join('keras_models', 'PRSA_data_PM2.5_1DConv_weights.18-0.0128.hdf5'))
2 preds = best_model.predict(X_val)
3 pred_pm25 = scaler.inverse_transform(preds)
4 pred_pm25 = np.squeeze(pred_pm25)
NameError: name 'os' is not defined
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-25-4135d558bcb1> in <module>()
----> 1 mae = mean_absolute_error(df_val['pm2.5'].loc[7:], pred_pm25)
2 print('MAE for the validation set:', round(mae, 4))
NameError: name 'df_val' is not defined
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
<ipython-input-26-5582b33dc36c> in <module>()
1 #Let's plot the first 50 actual and predicted values of pm2.5.
----> 2 plt.figure(figsize=(5.5, 5.5))
3 plt.plot(range(50), df_val['pm2.5'].loc[7:56], linestyle='-', marker='*', color='r')
4 plt.plot(range(50), pred_pm25[:50], linestyle='-', marker='.', color='b')
5 plt.legend(['Actual','Predicted'], loc=2)
NameError: name 'plt' is not defined