text_html_output_2.png text_plain_output_3.png text_html_output_1.png text_plain_output_2.png text_plain_output_1.png
from sklearn.preprocessing import MinMaxScaler

from tensorflow.keras.callbacks import EarlyStopping

from tensorflow.keras.layers import Dense

from tensorflow.keras.layers import LSTM

from tensorflow.keras.models import Sequential

from tensorflow.keras.preprocessing.sequence import TimeseriesGenerator

import pandas as pd

df = pd.read_csv('https://fred.stlouisfed.org/graph/fredgraph.csv?bgcolor=%23e1e9f0&chart_type=line&drp=0&fo=open%20sans&graph_bgcolor=%23ffffff&height=450&mode=fred&recession_bars=on&txtcolor=%23444444&ts=12&tts=12&width=1168&nt=0&thu=0&trc=0&show_legend=yes&show_axis_titles=yes&show_tooltip=yes&id=MRTSSM448USN&scale=left&cosd=1992-01-01&coed=2020-03-01&line_color=%234572a7&link_values=false&line_style=solid&mark_type=none&mw=3&lw=2&ost=-99999&oet=99999&mma=0&fml=a&fq=Monthly&fam=avg&fgst=lin&fgsnd=2009-06-01&line_index=1&transformation=lin&vintage_date=2020-05-16&revision_date=2020-05-16&nd=1992-01-01')
df.rename(columns={'MRTSSM448USN': 'Sales'}, inplace=True)
df['DATE'] = df['DATE'].astype('datetime64[ns]')
df.set_index('DATE', drop=True, inplace=True)

test_size = 18
test_ind = len(df) - 18
train = df.iloc[:test_ind]
test = df.iloc[test_ind:]

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

length = 12
generator = TimeseriesGenerator(scaled_train, scaled_train, length=length, batch_size=1)
X, y = generator[0]

n_features = 1
def testmodel():
    model = Sequential()
    model.add(LSTM(units=100, activation='relu', input_shape=(length, n_features)))
    model.add(Dense(1))
    model.compile(optimizer='adam', loss='mse')
    return model
modeltest = testmodel()

early_stop = EarlyStopping(monitor='val_loss', patience=2)
validation_generator = TimeseriesGenerator(scaled_test, scaled_test, length=length, batch_size=1)

modeltest.fit_generator(generator, epochs=20, validation_data=validation_generator, callbacks=[early_stop])