text_plain_output_4.png application_vnd.jupyter.stderr_output_3.png text_html_output_1.png text_plain_output_2.png application_vnd.jupyter.stderr_output_1.png
import matplotlib.pyplot as plt

import numpy as np

import pandas as pd

import tensorflow as tf

import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import tensorflow as tf
train = pd.read_csv('../input/tabular-playground-series-sep-2022/train.csv')
test = pd.read_csv('../input/tabular-playground-series-sep-2022/test.csv')
ss = pd.read_csv('../input/tabular-playground-series-sep-2022/sample_submission.csv')

cols = ['country', 'store', 'product']

cnt_val = pd.unique(train['country'])
str_val = pd.unique(train['store'])
prod_val = pd.unique(train['product'])
data = np.empty(shape=48, dtype='object')
i = 0
for x in cnt_val:
    for y in str_val:
        for z in prod_val:
            data[i] = train[(train['country'] == x) & (train['store'] == y) & (train['product'] == z)]
            i += 1

colors=['r','g','b','c','m','y']
fig=plt.figure(figsize=(20,500))
i=0
j=-1
days=[i for i in range(data[0].shape[0])]
for x in cnt_val:
    j+=1
    for y in str_val:
        for z in prod_val:
            ax=fig.add_subplot(len(cnt_val)*len(str_val)*len(prod_val),1,i+1)
            ax.set_title(x+', '+y+', '+z)
            ax.set_ylabel('num_sold')
            ax.plot(days,data[i]['num_sold'],color=colors[j])
            i+=1
plt.show()

i=0
j=-1
s=[i for i in range(24,48)]
fig=plt.figure(figsize=(25,90))
for x in cnt_val:
    j+=1
    for y in str_val:
        for z in prod_val:
            ax=fig.add_subplot(12,4,i+1)
            ax.set_title(x+', '+y+', '+z)
            ax.set_ylabel('number_of_samples')
            if i not in s:
                ax.hist(data[i]['num_sold'],bins=50,color=colors[j],ec='black')
            else:
                 ax.hist(data[i]['num_sold'].iloc[1100:],bins=50,color=colors[j],ec='black')
            i+=1
plt.show()

def windowed_dataset(series, window_size, batch_size, shuffle_buffer):
    dataset = tf.data.Dataset.from_tensor_slices(series)
    dataset = dataset.window(window_size + 1, shift=1, drop_remainder=True)
    dataset = dataset.flat_map(lambda window: window.batch(window_size + 1))
    dataset = dataset.shuffle(shuffle_buffer).map(lambda window: (window[:-1], window[-1]))
    dataset = dataset.batch(batch_size).prefetch(1)
    return dataset

days1 = 182
ep1 = 60
days2 = 60
ep2 = 21
for i in range(48):
    if i not in s:
        data_ = data[i]['num_sold'].copy()
        dataset = windowed_dataset(data_.values, days1, 700, 100)
        NN = tf.keras.Sequential([tf.keras.layers.Input(shape=(days1,)), tf.keras.layers.Dense(units=35, activation='relu'), tf.keras.layers.Dense(units=10, activation='relu'), tf.keras.layers.Dense(units=5, activation='relu'), tf.keras.layers.Dense(units=1, activation='relu')])
        NN.summary()
        NN.compile(optimizer=tf.keras.optimizers.Adagrad(), loss=tf.keras.losses.MeanSquaredError(), metrics=['MAPE'])
        hist = NN.fit(dataset, epochs=ep1)
        while hist.history['MAPE'][-1] >= 11:
            NN = tf.keras.Sequential([tf.keras.layers.Input(shape=(days1,)), tf.keras.layers.Dense(units=35, activation='relu'), tf.keras.layers.Dense(units=10, activation='relu'), tf.keras.layers.Dense(units=5, activation='relu'), tf.keras.layers.Dense(units=1, activation='relu')])
            NN.summary()
            NN.compile(optimizer=tf.keras.optimizers.Adagrad(), loss=tf.keras.losses.MeanSquaredError(), metrics=['MAPE'])
            hist = NN.fit(dataset, epochs=ep1)
        for j in range(365):
            pred = NN.predict(np.array([data_.values[-days1:]]))
            pred = int(pred * (pred - np.floor(pred) <= 0.5) + (int(pred) + 1) * (pred - np.floor(pred) > 0.5))
            data_ = data_.append(pd.Series(pred))
            print(pred)
            ss['num_sold'].iloc[i + 48 * j] = pred
    else:
        data_ = data[i]['num_sold'].iloc[1100:].copy()
        dataset = windowed_dataset(data_.values, days2, 180, 50)
        NN = tf.keras.Sequential([tf.keras.layers.Input(shape=(days2,)), tf.keras.layers.Dense(units=40, activation='relu'), tf.keras.layers.Dense(units=30, activation='relu'), tf.keras.layers.Dense(units=10, activation='relu'), tf.keras.layers.Dense(units=5, activation='relu'), tf.keras.layers.Dense(units=1, activation='relu')])
        NN.summary()
        NN.compile(optimizer=tf.keras.optimizers.Adagrad(), loss=tf.keras.losses.MeanSquaredError(), metrics=['MAPE'])
        hist = NN.fit(dataset, epochs=ep2)
        while hist.history['MAPE'][-1] >= 10:
            NN = tf.keras.Sequential([tf.keras.layers.Input(shape=(days2,)), tf.keras.layers.Dense(units=40, activation='relu'), tf.keras.layers.Dense(units=30, activation='relu'), tf.keras.layers.Dense(units=10, activation='relu'), tf.keras.layers.Dense(units=5, activation='relu'), tf.keras.layers.Dense(units=1, activation='relu')])
            NN.summary()
            NN.compile(optimizer=tf.keras.optimizers.Adagrad(), loss=tf.keras.losses.MeanSquaredError(), metrics=['MAPE'])
            hist = NN.fit(dataset, epochs=ep2)
        for j in range(365):
            pred = NN.predict(np.array([data_.values[-days2:]]))
            pred = int(pred * (pred - np.floor(pred) <= 0.5) + (int(pred) + 1) * (pred - np.floor(pred) > 0.5))
            data_ = data_.append(pd.Series(pred))
            print(pred)
            ss['num_sold'].iloc[i + 48 * j] = pred
display(ss)