Sharedtime.series / Chapter_5_PM2.5_Time_Series-v1_by_1D_convolution.ipynbOpen in CoCalc
TS-IPythonv1

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

from __future__ import print_function
import os
import sys
import pandas as pd
import numpy as np
%matplotlib inline
from matplotlib import pyplot as plt
import seaborn as sns
import datetime

#set current working directory
path="/home/user/time.series"
os.chdir(path)

#Read the dataset into a pandas.DataFrame

print('Shape of the dataframe:', df.shape)

Shape of the dataframe: (43824, 13)
#Let's see the first five rows of the DataFrame

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
"""
Rows having NaN values in column pm2.5 are dropped.
"""
df.dropna(subset=['pm2.5'], axis=0, inplace=True)
df.reset_index(drop=True, inplace=True)


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.

df['datetime'] = df[['year', 'month', 'day', 'hour']].apply(lambda row: datetime.datetime(year=row['year'], month=row['month'], day=row['day'],
hour=row['hour']), axis=1)
df.sort_values('datetime', ascending=True, inplace=True)

#Let us draw a box plot to visualize the central tendency and dispersion of PRES
plt.figure(figsize=(5.5, 5.5))
g = sns.boxplot(df['pm2.5'])
g.set_title('Box plot of PM2.5')

Text(0.5,1,'Box plot of PM2.5')
plt.figure(figsize=(5.5, 5.5))
g = sns.tsplot(df['pm2.5'])
g.set_title('Time series of pm2.5')
g.set_xlabel('Index')

--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-1-7d4bb0e8da02> in <module>() ----> 1 plt.figure(figsize=(5.5, 5.5)) 2 g = sns.tsplot(df['pm2.5']) 3 g.set_title('Time series of pm2.5') 4 g.set_xlabel('Index') 5 g.set_ylabel('pm2.5 readings') NameError: name 'plt' is not defined 
#Let's plot the series for six months to check if any pattern apparently exists.
plt.figure(figsize=(5.5, 5.5))
g = sns.tsplot(df['pm2.5'].loc[df['datetime']<=datetime.datetime(year=2010,month=6,day=30)], color='g')
g.set_title('pm2.5 during 2010')
g.set_xlabel('Index')

#Let's zoom in on one month.
plt.figure(figsize=(5.5, 5.5))
g = sns.tsplot(df['pm2.5'].loc[df['datetime']<=datetime.datetime(year=2010,month=1,day=31)], color='g')
g.set_title('pm2.5 during Jan 2010')
g.set_xlabel('Index')

--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-1-367fe73a6ff5> in <module>() 1 #Let's plot the series for six months to check if any pattern apparently exists. ----> 2 plt.figure(figsize=(5.5, 5.5)) 3 g = sns.tsplot(df['pm2.5'].loc[df['datetime']<=datetime.datetime(year=2010,month=6,day=30)], color='g') 4 g.set_title('pm2.5 during 2010') 5 g.set_xlabel('Index') NameError: name 'plt' is not defined 

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

from sklearn.preprocessing import MinMaxScaler
scaler = MinMaxScaler(feature_range=(0, 1))
df['scaled_pm2.5'] = scaler.fit_transform(np.array(df['pm2.5']).reshape(-1, 1))

--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-2-473805effdcf> in <module>() 1 from sklearn.preprocessing import MinMaxScaler 2 scaler = MinMaxScaler(feature_range=(0, 1)) ----> 3 df['scaled_pm2.5'] = scaler.fit_transform(np.array(df['pm2.5']).reshape(-1, 1)) NameError: name 'np' is not defined 

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.

"""
Let's start by splitting the dataset into train and validation. The dataset's time period if from
Jan 1st, 2010 to Dec 31st, 2014. The first fours years - 2010 to 2013 is used as train and
2014 is kept for validation.
"""
split_date = datetime.datetime(year=2014, month=1, day=1, hour=0)
df_train = df.loc[df['datetime']<split_date]
df_val = df.loc[df['datetime']>=split_date]
print('Shape of train:', df_train.shape)
print('Shape of test:', df_val.shape)

--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-3-7a3ee49aee25> in <module>() 4 2014 is kept for validation. 5 """ ----> 6 split_date = datetime.datetime(year=2014, month=1, day=1, hour=0) 7 df_train = df.loc[df['datetime']<split_date] 8 df_val = df.loc[df['datetime']>=split_date] NameError: name 'datetime' is not defined 
#First five rows of train

--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-4-1d5efefecfbd> in <module>() 1 #First five rows of train ----> 2 df_train.head() NameError: name 'df_train' is not defined 
#First five rows of validation

--------------------------------------------------------------------------- NameError Traceback (most recent call last) <ipython-input-5-a68d66813964> in <module>() 1 #First five rows of validation ----> 2 df_val.head() NameError: name 'df_val' is not defined 
#Reset the indices of the validation set
df_val.reset_index(drop=True, inplace=True)

"""
The train and validation time series of scaled pm2.5 is also plotted.
"""

plt.figure(figsize=(5.5, 5.5))
g = sns.tsplot(df_train['scaled_pm2.5'], color='b')
g.set_title('Time series of scaled pm2.5 in train set')
g.set_xlabel('Index')

plt.figure(figsize=(5.5, 5.5))
g = sns.tsplot(df_val['scaled_pm2.5'], color='r')
g.set_title('Time series of scaled pm2.5 in validation set')
g.set_xlabel('Index')

<matplotlib.text.Text at 0x18f3ae6d2b0>

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.

def makeXy(ts, nb_timesteps):
"""
Input:
ts: original time series
nb_timesteps: number of time steps in the regressors
Output:
X: 2-D array of regressors
y: 1-D array of target
"""
X = []
y = []
for i in range(nb_timesteps, ts.shape[0]):
X.append(list(ts.loc[i-nb_timesteps:i-1]))
y.append(ts.loc[i])
X, y = np.array(X), np.array(y)
return X, y

X_train, y_train = makeXy(df_train['scaled_pm2.5'], 7)
print('Shape of train arrays:', X_train.shape, y_train.shape)

Shape of train arrays: (33089, 7) (33089,)
X_val, y_val = makeXy(df_val['scaled_pm2.5'], 7)
print('Shape of validation arrays:', X_val.shape, y_val.shape)

Shape of validation arrays: (8654, 7) (8654,)

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.

#X_train and X_val are reshaped to 3D arrays
X_train, X_val = X_train.reshape((X_train.shape[0], X_train.shape[1], 1)),\
X_val.reshape((X_val.shape[0], X_val.shape[1], 1))
print('Shape of arrays after reshaping:', X_train.shape, X_val.shape)

Shape of arrays after reshaping: (33089, 7, 1) (8654, 7, 1)

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.

from keras.layers import Dense
from keras.layers import Input
from keras.layers import Dropout
from keras.layers import Flatten
from keras.layers.convolutional import Conv1D
from keras.layers.pooling import AveragePooling1D
from keras.optimizers import SGD
from keras.models import Model
from keras.callbacks import ModelCheckpoint

Using TensorFlow backend.
#Define input layer which has shape (None, 7) and of type float32. None indicates the number of instances
input_layer = Input(shape=(7,1), dtype='float32')


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.

#Add zero padding


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.

#Add 1D convolution layers
conv1D_layer1 = Conv1D(64, 3, strides=1, use_bias=True)(zeropadding_layer)
conv1D_layer2 = Conv1D(32, 3, strides=1, use_bias=True)(conv1D_layer1)


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.

#Add AveragePooling1D layer
avgpooling_layer = AveragePooling1D(pool_size=3, strides=1)(conv1D_layer2)


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

#Add Flatten layer
flatten_layer = Flatten()(avgpooling_layer)

#A couple of Dense layers are also added
dense_layer1 = Dense(32)(avgpooling_layer)
dense_layer2 = Dense(16)(dense_layer1)

dropout_layer = Dropout(0.2)(flatten_layer)

#Finally the output layer gives prediction for the next day's air pressure.
output_layer = Dense(1, activation='linear')(dropout_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.

ts_model = Model(inputs=input_layer, outputs=output_layer)
ts_model.summary()

_________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) (None, 7, 1) 0 _________________________________________________________________ zero_padding1d_1 (ZeroPaddin (None, 9, 1) 0 _________________________________________________________________ conv1d_1 (Conv1D) (None, 7, 64) 256 _________________________________________________________________ conv1d_2 (Conv1D) (None, 5, 32) 6176 _________________________________________________________________ average_pooling1d_1 (Average (None, 3, 32) 0 _________________________________________________________________ flatten_1 (Flatten) (None, 96) 0 _________________________________________________________________ dropout_1 (Dropout) (None, 96) 0 _________________________________________________________________ dense_3 (Dense) (None, 1) 97 ================================================================= Total params: 6,529 Trainable params: 6,529 Non-trainable params: 0 _________________________________________________________________

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.

save_weights_at = os.path.join('keras_models', 'PRSA_data_PM2.5_1DConv_weights.{epoch:02d}-{val_loss:.4f}.hdf5')
save_best = ModelCheckpoint(save_weights_at, monitor='val_loss', verbose=0,
save_best_only=True, save_weights_only=False, mode='min',
period=1)
ts_model.fit(x=X_train, y=y_train, batch_size=16, epochs=20,
verbose=1, callbacks=[save_best], validation_data=(X_val, y_val),
shuffle=True)

Train on 33089 samples, validate on 8654 samples Epoch 1/20 33089/33089 [==============================] - 5s - loss: 0.0191 - val_loss: 0.0136 Epoch 2/20 33089/33089 [==============================] - 4s - loss: 0.0168 - val_loss: 0.0135 Epoch 3/20 33089/33089 [==============================] - 4s - loss: 0.0166 - val_loss: 0.0147 Epoch 4/20 33089/33089 [==============================] - 4s - loss: 0.0164 - val_loss: 0.0137 Epoch 5/20 33089/33089 [==============================] - 4s - loss: 0.0164 - val_loss: 0.0140 Epoch 6/20 33089/33089 [==============================] - 4s - loss: 0.0162 - val_loss: 0.0158 Epoch 7/20 33089/33089 [==============================] - 4s - loss: 0.0163 - val_loss: 0.0136 Epoch 8/20 33089/33089 [==============================] - 7s - loss: 0.0161 - val_loss: 0.0140 Epoch 9/20 33089/33089 [==============================] - 7s - loss: 0.0161 - val_loss: 0.0136 Epoch 10/20 33089/33089 [==============================] - 7s - loss: 0.0161 - val_loss: 0.0131 Epoch 11/20 33089/33089 [==============================] - 7s - loss: 0.0161 - val_loss: 0.0155 Epoch 12/20 33089/33089 [==============================] - 7s - loss: 0.0160 - val_loss: 0.0148 Epoch 13/20 33089/33089 [==============================] - 7s - loss: 0.0160 - val_loss: 0.0133 Epoch 14/20 33089/33089 [==============================] - 6s - loss: 0.0160 - val_loss: 0.0140 Epoch 15/20 33089/33089 [==============================] - 4s - loss: 0.0159 - val_loss: 0.0133 Epoch 16/20 33089/33089 [==============================] - 5s - loss: 0.0160 - val_loss: 0.0148 Epoch 17/20 33089/33089 [==============================] - 5s - loss: 0.0160 - val_loss: 0.0138 Epoch 18/20 33089/33089 [==============================] - 5s - loss: 0.0159 - val_loss: 0.0143 Epoch 19/20 33089/33089 [==============================] - 4s - loss: 0.0158 - val_loss: 0.0128 Epoch 20/20 33089/33089 [==============================] - 4s - loss: 0.0159 - val_loss: 0.0130
<keras.callbacks.History at 0x18f837c8b70>

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.

best_model = load_model(os.path.join('keras_models', 'PRSA_data_PM2.5_1DConv_weights.18-0.0128.hdf5'))
preds = best_model.predict(X_val)
pred_pm25 = scaler.inverse_transform(preds)
pred_pm25 = np.squeeze(pred_pm25)

from sklearn.metrics import mean_absolute_error

mae = mean_absolute_error(df_val['pm2.5'].loc[7:], pred_pm25)
print('MAE for the validation set:', round(mae, 4))

MAE for the validation set: 12.724
#Let's plot the first 50 actual and predicted values of pm2.5.
plt.figure(figsize=(5.5, 5.5))
plt.plot(range(50), df_val['pm2.5'].loc[7:56], linestyle='-', marker='*', color='r')
plt.plot(range(50), pred_pm25[:50], linestyle='-', marker='.', color='b')
plt.legend(['Actual','Predicted'], loc=2)
plt.title('Actual vs Predicted pm2.5')
plt.ylabel('pm2.5')
plt.xlabel('Index')

<matplotlib.text.Text at 0x18f8404f128>