text_plain_output_2.png application_vnd.jupyter.stderr_output_1.png
from sklearn.preprocessing import MinMaxScaler

import matplotlib.pyplot as plt

import numpy as np

import pandas as pd

import tensorflow as tf

data = pd.read_csv('../input/time-series-datasets/monthly-beer-production-in-austr.csv', index_col='Month', parse_dates=True)
data.columns = ['Production']

train = data[:'1992-12-31']
test = data['1993-01-01':]

scaler = MinMaxScaler()
scaler.fit(train)

scaled_train = scaler.transform(train)
scaled_test = scaler.transform(test)

n_months = 12
generator = tf.keras.preprocessing.sequence.TimeseriesGenerator(scaled_train, scaled_train, length=n_months, batch_size=1)

tf.keras.backend.clear_session()
model = tf.keras.Sequential([tf.keras.layers.InputLayer(input_shape=(n_months, 1)), tf.keras.layers.LSTM(100, activation='tanh', return_sequences=True), tf.keras.layers.LSTM(50, activation='tanh', return_sequences=True), tf.keras.layers.LSTM(25, activation='tanh'), tf.keras.layers.Dense(1)])
model.compile(optimizer='adam', loss='mse')
model.summary()

early_stop = tf.keras.callbacks.EarlyStopping(monitor='loss', verbose=1, patience=2)
history = model.fit(generator, epochs=10, callbacks=[early_stop])

temp = scaled_train[-n_months:]
temp = temp.reshape((1, n_months, 1))
model.predict(temp)

test_predictions = []
last_batch = scaled_train[-n_months:]
current_batch = last_batch.reshape((1, n_months, 1))
for i in range(test.shape[0]):
    pred = model.predict(current_batch)[0]
    test_predictions.append(pred)
    current_batch = np.append(current_batch[:, 1:, :], [[pred]], axis=1)

test.plot(figsize=(12, 6))
plt.title('Forecasted vs Actual Time Series')
plt.show()