In [2]:
# How to predict a timeseries using GRU in Keras

def Snippet_399(): 

    print()
    print(format('How to predict a timeseries using GRU in Keras','*^92'))

    # load libraries
    import pandas, time
    import numpy as np
    from keras.layers.recurrent import GRU
    from keras.layers.core import Dense, Dropout
    from keras.optimizers import RMSprop
    from keras.models import Sequential
    import matplotlib.pyplot as plt
    from sklearn.preprocessing import MinMaxScaler

    start_time = time.time()    

    # load the dataset
    dataframe = pandas.read_csv('international-airline-passengers.csv', usecols=[1], 
                                engine='python', skipfooter=3)
    dataset = dataframe.values; dataset = dataset.astype('float32')

    # normalize the dataset
    scaler = MinMaxScaler(feature_range=(0, 1))
    dataset = scaler.fit_transform(dataset)

    # split into train and test sets
    train_size = int(len(dataset) * 0.67) 
    train_dataset, test_dataset = dataset[0:train_size,:], dataset[train_size:len(dataset),:]

    # Window -> X timestep back
    step_back = 1
    X_train, Y_train = [], []
    for i in range(len(train_dataset)-step_back - 1):
        a = train_dataset[i:(i+step_back), 0]
        X_train.append(a)
        Y_train.append(train_dataset[i + step_back, 0])
    X_train = np.array(X_train); Y_train = np.array(Y_train);
    
    X_test, Y_test = [], []
    for i in range(len(test_dataset)-step_back - 1):
        a = test_dataset[i:(i+step_back), 0]
        X_test.append(a)
        Y_test.append(test_dataset[i + step_back, 0])
    X_test = np.array(X_test); Y_test = np.array(Y_test);

    print(X_train); print(Y_train);             print(X_test); print(Y_test);

    # -----------------------------------------------------------
    # reshape input to be [samples, time steps, features]
    # -----------------------------------------------------------    
    X_train = np.reshape(X_train, (X_train.shape[0], 1, X_train.shape[1]))
    X_test  = np.reshape(X_test, (X_test.shape[0], 1, X_test.shape[1]))

    # -------------------------------------
    # setup a LSTM network in keras
    # -------------------------------------
    model = Sequential()
    model.add(GRU(32, input_shape=(1, step_back)))
    model.add(Dense(units = 512, activation = 'relu'))
    model.add(Dropout(0.2))
    model.add(Dense(units = 1, activation = 'linear'))
    model.summary()

    model.compile(loss='mean_squared_error', optimizer=RMSprop(lr = 0.01))
    model.fit(X_train, Y_train, epochs=20, batch_size=2, verbose=2)    

    # Estimate model performance
    print()
    trainScore = model.evaluate(X_train, Y_train, verbose=1)
    print('Train Score: %.2f MSE (%.2f RMSE)' % (trainScore, np.sqrt(trainScore)))
    testScore = model.evaluate(X_test, Y_test, verbose=1)
    print('Test Score: %.2f MSE (%.2f RMSE)' % (testScore, np.sqrt(testScore))) 

    # Evaluate the skill of the Trained model
    trainPredict = model.predict(X_train)
    testPredict  = model.predict(X_test)

    # invert predictions
    trainPredict = scaler.inverse_transform(trainPredict)
    testPredict = scaler.inverse_transform(testPredict)
    
    # shift train predictions for plotting
    trainPredictPlot = np.empty_like(dataset)
    trainPredictPlot[:, :] = np.nan
    trainPredictPlot[step_back:len(trainPredict)+step_back, :] = trainPredict

    # shift test predictions for plotting
    testPredictPlot = np.empty_like(dataset)
    testPredictPlot[:, :] = np.nan
    testPredictPlot[len(trainPredict)+(step_back*2)+1:len(dataset)-1, :] = testPredict

    # plot baseline and predictions
    plt.plot(scaler.inverse_transform(dataset))
    plt.plot(trainPredictPlot)
    plt.plot(testPredictPlot)
    plt.show()

    print(); print("Execution Time %s seconds: " % (time.time() - start_time))

Snippet_399()
***********************How to predict a timeseries using GRU in Keras***********************
[[0.01544401]
 [0.02702703]
 [0.05405405]
 [0.04826255]
 [0.03281853]
 [0.05984557]
 [0.08494207]
 [0.08494207]
 [0.06177607]
 [0.02895753]
 [0.        ]
 [0.02702703]
 [0.02123553]
 [0.04247104]
 [0.07142857]
 [0.05984557]
 [0.04054055]
 [0.08687258]
 [0.12741312]
 [0.12741312]
 [0.10424709]
 [0.05598456]
 [0.01930502]
 [0.06949806]
 [0.07915059]
 [0.08880308]
 [0.14285713]
 [0.11389962]
 [0.13127413]
 [0.14285713]
 [0.18339768]
 [0.18339768]
 [0.15444016]
 [0.11196911]
 [0.08108109]
 [0.1196911 ]
 [0.12934363]
 [0.14671814]
 [0.17181468]
 [0.14864865]
 [0.15250966]
 [0.22007722]
 [0.24324325]
 [0.26640925]
 [0.2027027 ]
 [0.16795367]
 [0.13127413]
 [0.17374519]
 [0.17760617]
 [0.17760617]
 [0.25482625]
 [0.25289574]
 [0.24131274]
 [0.26833975]
 [0.3088803 ]
 [0.32432434]
 [0.25675675]
 [0.20656371]
 [0.14671814]
 [0.18725869]
 [0.19305018]
 [0.16216215]
 [0.25289574]
 [0.23745173]
 [0.25096524]
 [0.3088803 ]
 [0.38223937]
 [0.36486486]
 [0.2992278 ]
 [0.24131274]
 [0.1911197 ]
 [0.24131274]
 [0.26640925]
 [0.24903473]
 [0.31467178]
 [0.3185328 ]
 [0.32046333]
 [0.4073359 ]
 [0.5019305 ]
 [0.46911195]
 [0.40154442]
 [0.32818535]
 [0.25675675]
 [0.3359073 ]
 [0.34749034]
 [0.33397684]
 [0.41119692]
 [0.4034749 ]
 [0.4131274 ]
 [0.52123547]
 [0.5965251 ]
 [0.58108103]]
[0.02702703 0.05405405 0.04826255 0.03281853 0.05984557 0.08494207
 0.08494207 0.06177607 0.02895753 0.         0.02702703 0.02123553
 0.04247104 0.07142857 0.05984557 0.04054055 0.08687258 0.12741312
 0.12741312 0.10424709 0.05598456 0.01930502 0.06949806 0.07915059
 0.08880308 0.14285713 0.11389962 0.13127413 0.14285713 0.18339768
 0.18339768 0.15444016 0.11196911 0.08108109 0.1196911  0.12934363
 0.14671814 0.17181468 0.14864865 0.15250966 0.22007722 0.24324325
 0.26640925 0.2027027  0.16795367 0.13127413 0.17374519 0.17760617
 0.17760617 0.25482625 0.25289574 0.24131274 0.26833975 0.3088803
 0.32432434 0.25675675 0.20656371 0.14671814 0.18725869 0.19305018
 0.16216215 0.25289574 0.23745173 0.25096524 0.3088803  0.38223937
 0.36486486 0.2992278  0.24131274 0.1911197  0.24131274 0.26640925
 0.24903473 0.31467178 0.3185328  0.32046333 0.4073359  0.5019305
 0.46911195 0.40154442 0.32818535 0.25675675 0.3359073  0.34749034
 0.33397684 0.41119692 0.4034749  0.4131274  0.52123547 0.5965251
 0.58108103 0.484556  ]
[[0.3223938 ]
 [0.3899614 ]
 [0.4073359 ]
 [0.3803089 ]
 [0.48648646]
 [0.47104248]
 [0.484556  ]
 [0.6138996 ]
 [0.6969112 ]
 [0.70077217]
 [0.57915056]
 [0.46911195]
 [0.38803086]
 [0.44787642]
 [0.45559844]
 [0.4131274 ]
 [0.4980695 ]
 [0.47104248]
 [0.49999997]
 [0.6389961 ]
 [0.7471043 ]
 [0.7741313 ]
 [0.57915056]
 [0.492278  ]
 [0.3976834 ]
 [0.44980696]
 [0.49420848]
 [0.45945945]
 [0.5830116 ]
 [0.5637065 ]
 [0.61003864]
 [0.71042466]
 [0.8571429 ]
 [0.8783784 ]
 [0.69305015]
 [0.5849421 ]
 [0.4980695 ]
 [0.58108103]
 [0.6042471 ]
 [0.554054  ]
 [0.60810804]
 [0.6891892 ]
 [0.71042466]
 [0.8320464 ]
 [1.        ]]
[0.3899614  0.4073359  0.3803089  0.48648646 0.47104248 0.484556
 0.6138996  0.6969112  0.70077217 0.57915056 0.46911195 0.38803086
 0.44787642 0.45559844 0.4131274  0.4980695  0.47104248 0.49999997
 0.6389961  0.7471043  0.7741313  0.57915056 0.492278   0.3976834
 0.44980696 0.49420848 0.45945945 0.5830116  0.5637065  0.61003864
 0.71042466 0.8571429  0.8783784  0.69305015 0.5849421  0.4980695
 0.58108103 0.6042471  0.554054   0.60810804 0.6891892  0.71042466
 0.8320464  1.         0.96911204]
Model: "sequential_2"
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
gru_2 (GRU)                  (None, 32)                3264      
_________________________________________________________________
dense_3 (Dense)              (None, 512)               16896     
_________________________________________________________________
dropout_2 (Dropout)          (None, 512)               0         
_________________________________________________________________
dense_4 (Dense)              (None, 1)                 513       
=================================================================
Total params: 20,673
Trainable params: 20,673
Non-trainable params: 0
_________________________________________________________________
Epoch 1/20
 - 1s - loss: 0.0166
Epoch 2/20
 - 0s - loss: 0.0071
Epoch 3/20
 - 0s - loss: 0.0077
Epoch 4/20
 - 0s - loss: 0.0061
Epoch 5/20
 - 0s - loss: 0.0063
Epoch 6/20
 - 0s - loss: 0.0045
Epoch 7/20
 - 0s - loss: 0.0045
Epoch 8/20
 - 0s - loss: 0.0050
Epoch 9/20
 - 0s - loss: 0.0042
Epoch 10/20
 - 0s - loss: 0.0048
Epoch 11/20
 - 0s - loss: 0.0057
Epoch 12/20
 - 0s - loss: 0.0051
Epoch 13/20
 - 0s - loss: 0.0043
Epoch 14/20
 - 0s - loss: 0.0040
Epoch 15/20
 - 0s - loss: 0.0044
Epoch 16/20
 - 0s - loss: 0.0045
Epoch 17/20
 - 0s - loss: 0.0047
Epoch 18/20
 - 0s - loss: 0.0041
Epoch 19/20
 - 0s - loss: 0.0038
Epoch 20/20
 - 0s - loss: 0.0047

92/92 [==============================] - 0s 839us/step
Train Score: 0.00 MSE (0.05 RMSE)
45/45 [==============================] - 0s 56us/step
Test Score: 0.02 MSE (0.14 RMSE)
Execution Time 2.7712292671203613 seconds: