<jupyter_start><jupyter_text>Recurrent Neural Networks  Import module<jupyter_code>import pandas as pd
import numpy as np
%matplotlib inline
import matplotlib.pyplot as plt
from tensorflow.keras.models import Sequential
from tensorflow.keras.layers import Dense
import tensorflow.keras.backend as K
from tensorflow.keras.callbacks import EarlyStopping
from tensorflow.keras.layers import LSTM, GRU
df = pd.read_csv('../data/cansim-0800020-eng-6674700030567901031.csv',
                 skiprows=6, skipfooter=9,
                 engine='python')
df.head()
from pandas.tseries.offsets import MonthEnd
# Đổi string sang date *** Rất quan trọng khi làm RNN!!!!
df['Adjustments'] = pd.to_datetime(df['Adjustments']) + MonthEnd(1)
df = df.set_index('Adjustments')
df.head()
df.plot()
split_date = pd.Timestamp('01-01-2011')
train = df.loc[:split_date, ['Unadjusted']]
test = df.loc[split_date:, ['Unadjusted']]
ax = train.plot()
test.plot(ax=ax)
plt.legend(['train', 'test'])<jupyter_output><empty_output><jupyter_text>Scaling, tách train-test<jupyter_code>from sklearn.preprocessing import MinMaxScaler

sc = MinMaxScaler()

train_sc = sc.fit_transform(train)
test_sc = sc.transform(test)
train_sc[:4]
X_train = train_sc[:-1]
y_train = train_sc[1:]

X_test = test_sc[:-1]
y_test = test_sc[1:]
early_stop = EarlyStopping(monitor='loss', patience=3, verbose=1)
train_sc.shape
train_sc_df = pd.DataFrame(train_sc, columns=['Scaled'], index=train.index)
test_sc_df = pd.DataFrame(test_sc, columns=['Scaled'], index=test.index)
train_sc_df.head()<jupyter_output><empty_output><jupyter_text>Tạo các rolling window có kích thước 12 tháng<jupyter_code>for s in range(1, 13):
    train_sc_df['shift_{}'.format(s)] = train_sc_df['Scaled'].shift(s)
    test_sc_df['shift_{}'.format(s)] = test_sc_df['Scaled'].shift(s)
train_sc_df.head(13)
X_train = train_sc_df.dropna().drop('Scaled', axis=1)
y_train = train_sc_df.dropna()[['Scaled']]

X_test = test_sc_df.dropna().drop('Scaled', axis=1)
y_test = test_sc_df.dropna()[['Scaled']]
X_train.head()
X_train.shape
X_train = X_train.values
X_test= X_test.values

y_train = y_train.values
y_test = y_test.values
X_train_t = X_train.reshape(X_train.shape[0], 1, 12)
X_test_t = X_test.reshape(X_test.shape[0], 1, 12)
X_train_t.shape<jupyter_output><empty_output><jupyter_text>Tạo model RNN<jupyter_code>K.clear_session()
model = Sequential()
# Thêm lớp LSTM
model.add(LSTM(6, input_shape=(1, 12)))
# Thêm lớp DNN đầu ra
model.add(Dense(1))
# Thiết lập thông số
model.compile(loss='mean_squared_error', optimizer='adam')
model.summary()
model.fit(X_train_t, y_train, epochs=100,
          batch_size=1, verbose=1, callbacks=[early_stop])
y_pred = model.predict(X_test_t)
plt.plot(y_test)
plt.plot(y_pred)
from sklearn.metrics import mean_squared_error
mean_squared_error(y_test, y_pred, squared=False)<jupyter_output><empty_output>