<jupyter_start><jupyter_text><jupyter_code># Commented out IPython magic to ensure Python compatibility.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline
import datetime as dt
import tensorflow as tf
from keras.models import Sequential
from keras.layers import Dense, Conv1D, MaxPooling1D, AveragePooling1D , Flatten, Input
from sklearn.model_selection import train_test_split
import pprint as pp
from google.colab import drive
drive.mount('/content/drive')
df = pd.read_csv("/content/drive/MyDrive/train.csv")
df = df[(df["item"]==1) & (df['store']==1)] # Store 1 and item 1 only
df['date'] = pd.to_datetime(df['date'], format="%Y-%m-%d")
plt.plot(df['date'],df['sales'])
plt.title('Sales')
plt.xlabel('Date')
plt.ylabel('Units')
plt.show()
raw_seq = df['sales']
# univariate data preparation
# split a univariate sequence into samples
def split_sequence(sequence, n_steps):
  X, y = list(), list()
  for i in range(len(sequence)):
    # find the end of this pattern
    end_ix = i + n_steps
    # check if we are beyond the sequence
    if end_ix > len(sequence)-1:
      break
    # gather input and output parts of the pattern
    seq_x, seq_y = sequence[i:end_ix], sequence[end_ix]
    X.append(seq_x)
    y.append(seq_y)
  return np.array(X), np.array(y)
from keras.layers.pooling import AveragePooling1D
def cnn_model(n_steps, n_features):
    inputs = Input(shape=(n_steps, n_features))
    X = Conv1D(64, 2, activation='relu')(inputs)
    X = AveragePooling1D()(X)
    X = Flatten()(X)
    X = Dense(50, activation='relu')(X)
    outputs = Dense(1)(X)
    model = tf.keras.Model(inputs=inputs, outputs=outputs, name="cnn_model")
    return model
def run_model(sequence, n_steps):
    X, y = split_sequence(sequence, n_steps)
    n_features = 1
    X = X.reshape((X.shape[0], X.shape[1], n_features))
    X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
    model = cnn_model(n_steps, n_features)
    model.compile(optimizer="adam", loss='mse', metrics=[tf.keras.metrics.RootMeanSquaredError(), tf.keras.metrics.MeanAbsolutePercentageError()])
    # fit model
    hist =  model.fit(X_train, y_train, batch_size=120, epochs=2000, verbose=0)
    score = model.evaluate(X_test, y_test, verbose=0,  return_dict=True)
    return (hist, score)
hist, score = run_model(raw_seq, 10)
pd.DataFrame(hist.history).plot(figsize=(8,5))
plt.show()
score<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.1346774193548387, 'fraction_numerical': 0.014919354838709677, 'mean_word_length': 4.921241050119332, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 6, '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': '1', 'dir': 'jupyter-structured-clean-dedup', 'id': '543547', 'license': 'Apache-2.0', 'n_tokens_mistral': 918, 'n_tokens_neox': 878, 'n_words': 219, 'path': 'notebook/cnn.ipynb', 'repo_name': 'asefshahriar/Cookbook', 'size': '2480'}