<jupyter_start><jupyter_text>Predicting Time Series Forecast - Fast Food Sales - LSTM<jupyter_code>import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
from keras.models import Sequential
from keras.layers import Dense
from keras.layers import LSTM
import keras
from keras.models import load_model
from sklearn import model_selection
%matplotlib inline<jupyter_output>Using TensorFlow backend.<jupyter_text>Importing data from Excel file. The data contains the monthly sale from 2014 to October 2017<jupyter_code>df = pd.read_excel('Faturamento2.xlsx')
df.head()<jupyter_output><empty_output><jupyter_text>Getting the "Data"<jupyter_code>#df.index = df['Data']
#df.drop('Data', axis=1 , inplace=True)
x = df['Vendas'].values
plt.plot(x)
plt.show<jupyter_output><empty_output><jupyter_text>Scaling the data<jupyter_code>from sklearn.preprocessing import MinMaxScaler

x = x.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(0, 1))
scaler = scaler.fit(x)
x_scaled = scaler.transform(x)

plt.plot(x_scaled)
plt.xlabel('Time Period')
plt.ylabel('Normalized Values')<jupyter_output>C:\Users\Owner\Anaconda3\lib\site-packages\sklearn\utils\validation.py:475: DataConversionWarning: Data with input dtype int64 was converted to float64 by MinMaxScaler.
  warnings.warn(msg, DataConversionWarning)<jupyter_text>Extracting Sequences<jupyter_code># Function that transforms series and window-size into an input / output set for the RNN model
def window_transform_series(series, window_size):
    """
      Arguments:
        series(np.array(list)): Sequence of Values
        window_size(int      ): Size of window
      
      Return:
         X(np.array(list(list))): Input Matrix
         y(np.array(list))      : Output Array
    """

    # Objects for input/output 
    X = np.asarray([series[i:(i + window_size)] for i in range(len(series) - window_size)])
    y = np.asarray([series[i + window_size] for i in range(len(series) - window_size)])

    return X,y
window_size = 6
X,y = window_transform_series(series = x_scaled, window_size = window_size)<jupyter_output><empty_output><jupyter_text>Training an Test Split<jupyter_code>seed = 7
X_train , X_test , y_train , y_test = model_selection.train_test_split(X,y,test_size=0.2, random_state=seed)#int(np.ceil(2*len(y)/float(3)))  # Ponto de spplit

# To create the RNN LSTM Model with Keras our data must be in the format [samples, window size, stepsize]
X_train = np.asarray(np.reshape(X_train, (X_train.shape[0], window_size, 1)))
X_test = np.asarray(np.reshape(X_test, (X_test.shape[0], window_size, 1)))<jupyter_output><empty_output><jupyter_text>Building the RNN Model<jupyter_code>def build_RNN(window_size):
    model = Sequential()
    model.add(LSTM(5, input_shape=(window_size,1)))
    model.add(Dropout(0.2))
    model.add(Dense(1))
    return model
from keras.models import Sequential
from keras.layers import Dense,Dropout
from keras.layers import LSTM
import keras

# Random seed
np.random.seed(0)

# Build
model = build_RNN(window_size)

# Otimizer
#optimizer = keras.optimizers.RMSprop(lr = 0.001, rho = 0.9, epsilon = 1e-08, decay = 0.0)

# Compile
model.compile(loss = 'mean_squared_error', optimizer = 'rmsprop')
model.summary()
model.fit(X_train, y_train, epochs = 2000, batch_size = 12, verbose = 1)
# Predictions
train_predict = model.predict(X_train)
test_predict = model.predict(X_test)
# Print of training and test errors
training_error = model.evaluate(X_train, y_train, verbose=0)
print('Erro em Treinamento = %.3f %%' % training_error)

testing_error = model.evaluate(X_test, y_test, verbose=0)
print('Erro em Teste = %.3f %%' %  testing_error)
# Plot
import matplotlib.pyplot as plt
%matplotlib inline

# Plot of the original series
plt.plot(x_scaled,color = 'k')

# Plot of predictions in training
split_pt = X_train.shape[0] + window_size 
plt.plot(np.arange(window_size,split_pt,1),train_predict,color = 'b')

# plot of predictions in training
plt.plot(np.arange(split_pt,split_pt + len(test_predict),1),test_predict,color = 'r')

# Plot
plt.xlabel('Month')
plt.ylabel('Sales')
plt.legend(['Original Series','Training Predictions','Test Predictions'], loc='center left', bbox_to_anchor=(1, 0.5))
plt.show()
# Also defining the RMSE metric
def rmse(y_real,y_pred):
    return np.sqrt(sum([ (m - n)**2 for m, n in zip(y_real,y_pred[:-1])]))/len(y_real)
mean_squared_error_train = rmse(y_train, train_predict)
mean_squared_error_test = rmse(y_test, test_predict)
print('Mean train squared error: %.5f' %  mean_squared_error_train)
print('Mean test squared error: %.5f' %  mean_squared_error_test)<jupyter_output>Mean train squared error: 0.02144
Mean test squared error: 0.04908<jupyter_text>Forecasts with New Data Sets<jupyter_code>new_data = np.array([138513,130927,137397,141766,124636,140939,132573])
new_data
new_data = new_data.reshape(-1, 1)
scaler = MinMaxScaler(feature_range=(0, 1))
scaler = scaler.fit(new_data)
new_data_scaled = scaler.transform(new_data)
new_data_scaled
window_size = 6
series = new_data_scaled
new_X = np.asarray([series[i:(i + window_size)] for i in range(len(series) - window_size)])
new_X
final_X = np.asarray(np.reshape(new_X, (new_X.shape[0], window_size, 1)))
final_X.shape
pred = model.predict(final_X)
print("Next value in series: ", pred)
final_X_inversed = scaler.inverse_transform(pred)
print(final_X_inversed)<jupyter_output>[[ 137932.09375]]
{'fraction_non_alphanumeric': 0.12221396731054977, 'fraction_numerical': 0.02637444279346211, 'mean_word_length': 5.975388601036269, 'pattern_counts': {'":': 0, '<': 29, '<?xml version=': 0, '>': 29, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '8', 'dir': 'jupyter-structured-clean-dedup', 'id': '47654', 'license': 'MIT', 'n_tokens_mistral': 2083, 'n_tokens_neox': 1943, 'n_words': 430, 'path': 'Sales Forecast LSTM.ipynb', 'repo_name': 'pedrohesch/Time-Series-Sales-LSTM', 'size': '5384'}