text_plain_output_1.png
import itertools

import keras

import numpy as np # linear algebra

import pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)

df = pd.read_csv('/kaggle/input/demand-forecast-abal2/demand_forecast.csv', parse_dates=['date'])
df

df.groupby(['store', 'item']).size()

input_df = df.set_index(['date', 'store', 'item'])

def train_test_split(dataframe, train_size=0.9):
    index_df = input_df.index.levels[0]
    train_cnt = int(len(index_df) * train_size)
    pivot = index_df[train_cnt]
    train = dataframe.iloc[dataframe.index.get_level_values('date') <= pivot]
    test = dataframe.iloc[dataframe.index.get_level_values('date') > pivot]
    return (train, test)

train_df.index.levels[1:][0]

train_df.iloc[(train_df.index.get_level_values('store') == 1) & (train_df.index.get_level_values('item') == 1)]

def create_dataset(input_df, time_steps=1):
    Xs, ys = ([], [])
    stores = train_df.index.levels[1]
    items = train_df.index.levels[2]
    store_items = list(itertools.product(stores, items))
    for store, item in store_items:
        curr_df = input_df.iloc[(input_df.index.get_level_values('store') == store) & (input_df.index.get_level_values('item') == item)]
        for i in range(len(curr_df) - time_steps):
            v = curr_df.iloc[i:i + time_steps].values
            Xs.append(v)
            ys.append(curr_df.iloc[i + time_steps].values)
    return (np.array(Xs), np.array(ys))

time_steps = 10
X_train, y_train = create_dataset(train_df, time_steps)
X_test, y_test = create_dataset(test_df, time_steps)

model = keras.Sequential()
model.add(keras.layers.Bidirectional(keras.layers.LSTM(units=128, input_shape=(X_train.shape[1], X_train.shape[2]))))
model.add(keras.layers.Dropout(rate=0.2))
model.add(keras.layers.Dense(units=1))
model.compile(loss='mean_squared_error', optimizer='adam')