application_vnd.jupyter.stderr_output_2.png text_plain_output_3.png text_plain_output_1.png
from datetime import datetime

from gluonts.dataset.common import ListDataset

from gluonts.dataset.common import ListDataset

from gluonts.dataset.field_names import FieldName

from gluonts.model.deepar import DeepAREstimator

from gluonts.model.deepar import DeepAREstimator

from gluonts.mx import Trainer

from gluonts.mx.trainer import Trainer

import matplotlib.pyplot as plt

import matplotlib.pyplot as plt

import pandas as pd

import pandas as pd

def convert_to_date(x):
    return datetime.strptime(x, '%Y %m')
make = pd.read_csv('../input/newcarsalesnorway/norway_new_car_sales_by_make.csv', parse_dates=[['Year', 'Month']], date_parser=convert_to_date)
make = make[['Year_Month', 'Quantity', 'Make']]

def subset_data(dataframe=make, subset=['Toyota', 'Ford', 'BMW', 'Honda', 'Peugeot']):
    """
    Function to subset the data 
    INPUT : dataframe to subset and car type list 
    OUTPUT : 5 different dataframes with the subset data
    """
    dataframe.set_index('Year_Month', inplace=True)
    toyota = dataframe[dataframe['Make'] == subset[0]]
    ford = dataframe[dataframe['Make'] == subset[1]]
    honda = dataframe[dataframe['Make'] == subset[3]]
    BMW = dataframe[dataframe['Make'] == subset[2]]
    peugeot = dataframe[dataframe['Make'] == subset[4]]
    df = pd.concat([toyota['Quantity'], ford['Quantity'], BMW['Quantity'], honda['Quantity'], peugeot['Quantity']], axis=1)
    df.columns = [subset[0], subset[1], subset[2], subset[3], subset[4]]
    return df
df = subset_data()

### How the time series is for each Car model 
### Some show upward trend some show downward trend 

fig, axs = plt.subplots(2, 2, figsize=(20, 20), sharex=True)
axx = axs.ravel()
for i in range(0, 4):
    df[df.columns[i]].plot(ax=axx[i])
    axx[i].set_xlabel("date")    
    axx[i].set_ylabel(f"{df.columns[i]} Car Sales")   
    axx[i].grid(which='minor', axis='x')

df_input = df.reset_index(drop=True).T.reset_index()
ts_code = df_input['index'].astype('category').cat.codes.values
df_train = df_input.iloc[:, 1:116].values
df_test = df_input.iloc[:, 116:].values

df_test.shape

df_train.shape

freq = 'M'
start_train = pd.Timestamp('2007-01-01', freq=freq)
start_test = pd.Timestamp('2016-07-01', freq=freq)
prediction_length = 2

estimator = DeepAREstimator(freq=freq, context_length=12, prediction_length=prediction_length, use_feat_static_cat=True, cardinality=[1], num_layers=2, num_cells=8, cell_type='lstm', trainer=Trainer(epochs=300, learning_rate=0.01, learning_rate_decay_factor=0.1))

from gluonts.dataset.common import ListDataset
from gluonts.dataset.field_names import FieldName
train_ds = ListDataset([{FieldName.TARGET: target, FieldName.START: start_train, FieldName.FEAT_STATIC_CAT: fsc} for target, fsc in zip(df_train, ts_code.reshape(-1, 1))], freq=freq)
test_ds = ListDataset([{FieldName.TARGET: target, FieldName.START: start_test, FieldName.FEAT_STATIC_CAT: fsc} for target, fsc in zip(df_test, ts_code.reshape(-1, 1))], freq=freq)

predictor = estimator.train(training_data=train_ds)

def convert_to_date(x):
    return datetime.strptime(x, '%Y %m')
make = pd.read_csv('../input/newcarsalesnorway/norway_new_car_sales_by_make.csv', parse_dates=[['Year', 'Month']], date_parser=convert_to_date)
make = make[['Year_Month', 'Quantity', 'Make']]

make = make[make['Make'] == 'Ford']

df_input = make[['Year_Month', 'Quantity']]

df_input = df_input.set_index('Year_Month')

train_time = '2016-08-01'
prediction_length = 6

estimator = DeepAREstimator(freq='1M', context_length=12, prediction_length=prediction_length, num_layers=2, num_cells=128, cell_type='lstm', trainer=Trainer(epochs=20))

from gluonts.dataset.common import ListDataset
training_data = ListDataset([{'start': df_input.index[0], 'target': df_input.Quantity[:train_time]}], freq='1M')

predictor = estimator.train(training_data=training_data)