Kaggle competition: M5 Forecasting - Uncertainty
<SOS> metric: WeightedRowwisePinballLoss Kaggle data source: m5-forecasting-uncertainty<init_hyperparams>
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import lightgbm as lgb
from sklearn.metrics import mean_squared_error
from tqdm import tqdm
import gc
params = {
'max_depth': -1,
'num_leaves': 3,
'min_data_in_leaf': 4,
} 
<compute_test_metric>
def preprocess_sales(sales, start=1400, upper=1970):
if start is not None:
print("dropping...")
 to_drop = [f"d_{i+1}" for i in range(start-1)]
print(sales.shape)
 sales.drop(to_drop, axis=1, inplace=True)
 print(sales.shape)
 print("adding...")
 new_columns = ['d_%i'%i for i in range(1942, upper, 1)]
for col in new_columns:
sales[col] = np.nan
print("melting...")
 sales = sales.melt(id_vars=["id", "item_id", "dept_id", "cat_id", "store_id", "state_id","scale1",
"sales1","start","sales2","scale2"],
var_name='d', value_name='demand')
 return sales
def preprocess_calendar(calendar):
global maps, mods
calendar["event_name"] = calendar["event_name_1"]
calendar["event_type"] = calendar["event_type_1"]
map1 = {mod:i for i,mod in enumerate(calendar['event_name'].unique())}
calendar['event_name'] = calendar['event_name'].map(map1)
 map2 = {mod:i for i,mod in enumerate(calendar['event_type'].unique())}
calendar['event_type'] = calendar['event_type'].map(map2)
 calendar['nday'] = calendar['date'].str[-2:].astype(int)
 maps["event_name"] = map1
maps["event_type"] = map2
mods["event_name"] = len(map1)
 mods["event_type"] = len(map2)
 calendar["wday"] -=1
calendar["month"] -=1
calendar["year"] -= 2011
mods["month"] = 12
mods["year"] = 6
mods["wday"] = 7
mods['snap_CA'] = 2
mods['snap_TX'] = 2
mods['snap_WI'] = 2
calendar["nb"] = calendar.index + 1
calendar.drop(["event_name_1", "event_name_2", "event_type_1", "event_type_2", "date", "weekday"],
axis=1, inplace=True)
 return calendar
def make_dataset(categorize=False ,start=1400, upper= 1970):
global maps, mods
print("loading calendar...")
 calendar = pd.read_csv(".. /input/m5-forecasting-uncertainty/calendar.csv")
 print("loading sales...")
 sales = pd.read_csv(".. /input/walmartadd/sales_aug.csv")
 cols = ["item_id", "dept_id", "cat_id","store_id","state_id"]
if categorize:
for col in cols:
temp_dct = {mod:i for i, mod in enumerate(sales[col].unique())}
mods[col] = len(temp_dct)
 maps[col] = temp_dct
for col in cols:
sales[col] = sales[col].map(maps[col])
 sales =preprocess_sales(sales, start=start, upper= upper)
 calendar = preprocess_calendar(calendar)
 calendar = reduce_mem_usage(calendar)
 print("merge with calendar...")
 sales = sales.merge(calendar, on='d', how='left')
 print("reordering...")
 sales.sort_values(by=["id","nb"], inplace=True)
 print("re-indexing.. ")
 sales.reset_index(inplace=True, drop=True)
 gc.collect()
sales['n_week'] =(sales['nb']-1)//7
sales["nday"] -= 1
mods['nday'] = 31
sales = reduce_mem_usage(sales)
 calendar = calendar.loc[calendar.nb>=start]
gc.collect()
return sales, calendar
def metric(y_true, y_pred):
return np.mean(np.sum(np.abs(y_true - y_pred), axis=0)/np.sum(y_true, axis=0))<import_modules>
def qloss_np(y_true, y_pred):
qs = [0.005, 0.025, 0.165, 0.250, 0.500, 0.750, 0.835, 0.975, 0.995]
q = np.array([qs])
 e = y_true - y_pred
v = np.maximum(q*e,(q-1)*e)
 return np.mean(v )
from sklearn.svm import SVR<prepare_x_and_y>
%%time
CATEGORIZE = True;
START = 1400; UPPER = 1970;
maps = {}
mods = {}
sales, calendar = make_dataset(categorize=CATEGORIZE ,start=START, upper= UPPER )
NUM_FOLDS = 5
kf = KFold(n_splits=NUM_FOLDS, shuffle=True, random_state=0)
 overal_score = 0
for target, c, w in [("age", 100, 0.3),("domain1_var1", 10, 0.175),("domain1_var2", 10, 0.175),("domain2_var1", 10, 0.175),("domain2_var2", 10, 0.175)]:
df = extract_algo(df_pred, target)
 df = df.merge(score_pd, on="Id", how="left")
 test_df = extract_algo(df_sub, target)
 y_oof = np.zeros(df.shape[0])
 y_test = np.zeros(( test_df.shape[0], NUM_FOLDS))
for f,(train_ind, val_ind)in enumerate(kf.split(df, df)) :
train_df, val_df = df.iloc[train_ind], df.iloc[val_ind]
train_df = train_df[train_df[target].notnull() ]
model = SVR(kernel='rbf')
 model.fit(train_df[algorithm], train_df[target])
 y_oof[val_ind] = model.predict(val_df[algorithm])
 y_test[:, f] = model.predict(test_df[algorithm])
 df["pred_{}".format(target)] = y_oof
sub_df[target] = y_test.mean(axis=1)
 score = metric(df[df[target].notnull() ][target].values, df[df[target].notnull() ]["pred_{}".format(target)].values)
 overal_score += w*score
print(target, np.round(score, 4))
print()
print("Overal score:", np.round(overal_score, 4))<data_type_conversions>
sales["x"] = sales["demand"] / sales["scale1"]
sub_df = pd.melt(sub_df[["Id", "age", "domain1_var1", "domain1_var2", "domain2_var1", "domain2_var2"]], id_vars=["Id"], value_name="Predicted")
 sub_df["Id"] = sub_df["Id"].astype("str")+ "_" + sub_df["variable"].astype("str")
 sub_df = sub_df.drop("variable", axis=1 ).sort_values("Id" )<save_to_csv>
NITEMS = 42840
scale = sales['scale1'].values.reshape(( NITEMS, -1))
ids = sales['id'].values.reshape(( NITEMS, -1))
ys = sales[['x','sales1']].values.reshape(( NITEMS, -1, 2))
Z = sales[FEATS].values.reshape(( NITEMS, -1, len(FEATS)) )
sub_df.to_csv("submission.csv", index=False )<import_modules>
LEN = 1969 - START + 1
MAX_LAG = max(LAGS)
 print(LEN, MAX_LAG )
from fastai.vision import *<install_modules>
CATCOLS = ['snap_CA', 'snap_TX', 'snap_WI', 'wday', 'month', 'year', 'event_name', 'nday',
'item_id', 'dept_id', 'cat_id', 'store_id', 'state_id']
pip install chainer<install_modules>
import tensorflow.keras.layers as L
import tensorflow.keras.models as M
import tensorflow.keras.backend as K
from tensorflow.keras.callbacks import ModelCheckpoint, ReduceLROnPlateau, EarlyStopping
import tensorflow as tf
import itertools as it
pip install cupy --no-cache-dir -vvvv<compute_test_metric>
def make_data(c, z, y):
x = {"snap_CA":c[:,:,0], "snap_TX":c[:,:,1], "snap_WI":c[:,:,2], "wday":c[:,:,3],
"month":c[:,:,4], "year":c[:,:,5], "event":c[:,:,6], "nday":c[:,:,7],
"item":c[:,:,8], "dept":c[:,:,9], "cat":c[:,:,10], "store":c[:,:,11],
"state":c[:,:,12], "num":z}
t = y
return x, t
def metric(y_true, y_pred):
return np.mean(np.sum(np.abs(y_true - y_pred), axis=0)/np.sum(y_true, axis=0))<load_from_csv>
class DataGenerator(tf.keras.utils.Sequence):
'Generates data for Keras'
def __init__(self, x, brks, batch_size=32, shuffle=True):
'Initialization'
self.batch_size = batch_size
self.c = x[0]
self.z = x[1]
self.y = x[2]
self.brks = brks.copy()
self.list_IDs = np.array(range(42840))
self.shuffle = shuffle
self.nb_batch = int(np.ceil(len(self.list_IDs)/ self.batch_size))
self.n_windows = brks.shape[0]
self.on_epoch_end()
def __len__(self):
'Denotes the number of batches per epoch'
return int(np.ceil(len(self.list_IDs)/ self.batch_size)) *(self.n_windows)
 def __getitem__(self, index):
'Generate one batch of data'
idx, kx = self.ids[index]
batch_ids = self.list_IDs[idx*self.batch_size:(idx+1)*self.batch_size]
X, y = self.__data_generation(batch_ids, kx)
 return X, y
def on_epoch_end(self):
'Updates indexes after each epoch'
self.ids = list(it.product(np.arange(0, self.nb_batch), self.brks))
if self.shuffle == True:
np.random.shuffle(self.ids)
 def __data_generation(self, batch_ids, kx):
'Generates data containing batch_size samples'
x_batch, y_batch = make_data(self.c[batch_ids, kx-28:kx], self.z[batch_ids,kx-28:kx],
self.y[batch_ids, kx-28:kx])
 return x_batch, y_batch
fnc_df = cudf.read_csv(".. /input/trends-assessment-prediction/fnc.csv")
 loading_df = cudf.read_csv(".. /input/trends-assessment-prediction/loading.csv")
 fnc_features, loading_features = list(fnc_df.columns[1:]), list(loading_df.columns[1:])
 df = fnc_df.merge(loading_df, on="Id")
 labels_df = cudf.read_csv(".. /input/trends-assessment-prediction/train_scores.csv")
 labels_df["is_train"] = True
df = df.merge(labels_df, on="Id", how="left")
 test_df = df[df["is_train"] != True].copy()
df = df[df["is_train"] == True].copy()
df.shape, test_df.shape<normalization>
xv, yv = make_data(C[:,LEN-56:LEN-28,:], Z[:,LEN-56:LEN-28,:], ys[:,LEN-56:LEN-28])
 xe, ye = make_data(C[:,LEN-28:LEN,:], Z[:,LEN-28:LEN,:], ys[:,LEN-28:LEN] )
FNC_SCALE = 1/500
df[fnc_features] *= FNC_SCALE
test_df[fnc_features] *= FNC_SCALE<prepare_x_and_y>
def wqloss(y_true, y_pred):
qs = [0.005, 0.025, 0.165, 0.250, 0.500, 0.750, 0.835, 0.975, 0.995]
q = tf.constant(np.array([qs]), dtype=tf.float32)
 e = y_true[:,:,:1] - y_pred
v = tf.maximum(q*e,(q-1)*e)
 psl = tf.reduce_mean(v, axis=[1,2])
 weights = y_true[:,0,1] / K.sum(y_true[:,0,1])
 return tf.reduce_sum(psl * weights)
 def qloss(y_true, y_pred):
qs = [0.005, 0.025, 0.165, 0.250, 0.500, 0.750, 0.835, 0.975, 0.995]
q = tf.constant(np.array([[qs]]), dtype=tf.float32)
 e = y_true - y_pred
v = tf.maximum(q*e,(q-1)*e)
 return K.mean(v)
 def make_model(n_in):
seq_len = 28
num = L.Input(( seq_len, n_in,), name="num")
 ca = L.Input(( seq_len,), name="snap_CA")
 tx = L.Input(( seq_len,), name="snap_TX")
 wi = L.Input(( seq_len,), name="snap_WI")
 wday = L.Input(( seq_len,), name="wday")
 month = L.Input(( seq_len,), name="month")
 year = L.Input(( seq_len,), name="year")
 event = L.Input(( seq_len,), name="event")
 nday = L.Input(( seq_len,), name="nday")
 item = L.Input(( seq_len,), name="item")
 dept = L.Input(( seq_len,), name="dept")
 cat = L.Input(( seq_len,), name="cat")
 store = L.Input(( seq_len,), name="store")
 state = L.Input(( seq_len,), name="state")
 inp = {"snap_CA":ca, "snap_TX":tx, "snap_WI":wi, "wday":wday,
"month":month, "year":year, "event":event, "nday":nday,
"item":item, "dept":dept, "cat":cat, "store":store,
"state":state, "num":num}
ca_ = L.Embedding(mods["snap_CA"], mods["snap_CA"], name="ca_3d" )(ca)
 tx_ = L.Embedding(mods["snap_TX"], mods["snap_TX"], name="tx_3d" )(tx)
 wi_ = L.Embedding(mods["snap_WI"], mods["snap_WI"], name="wi_3d" )(wi)
 wday_ = L.Embedding(mods["wday"], mods["wday"], name="wday_3d" )(wday)
 month_ = L.Embedding(mods["month"], mods["month"], name="month_3d" )(month)
 year_ = L.Embedding(mods["year"], mods["year"], name="year_3d" )(year)
 event_ = L.Embedding(mods["event_name"], mods["event_name"], name="event_3d" )(event)
 nday_ = L.Embedding(mods["nday"], mods["nday"], name="nday_3d" )(nday)
 item_ = L.Embedding(mods["item_id"], 10, name="item_3d" )(item)
 dept_ = L.Embedding(mods["dept_id"], mods["dept_id"], name="dept_3d" )(dept)
 cat_ = L.Embedding(mods["cat_id"], mods["cat_id"], name="cat_3d" )(cat)
 store_ = L.Embedding(mods["store_id"], mods["store_id"], name="store_3d" )(store)
 state_ = L.Embedding(mods["state_id"], mods["state_id"], name="state_3d" )(state)
 p = [ca_, tx_, wi_, wday_, month_, year_, event_, nday_, item_, dept_, cat_, store_, state_]
context = L.Concatenate(name="context" )(p)
 x = L.Concatenate(name="x1" )([context, num])
 x = L.GRU(100, return_sequences=True, name="d1" )(x)
 x = L.Dropout(0.3 )(x)
 x = L.Concatenate(name="m1" )([x, context])
 x = L.GRU(100, return_sequences=True, name="d2" )(x)
 x = L.Dropout(0.3 )(x)
 x = L.Concatenate(name="m2" )([x, context])
 x = L.GRU(100, return_sequences=True, name="d3" )(x)
 preds = L.Dense(9, activation="linear", name="preds" )(x)
 model = M.Model(inp, preds, name="M1")
 model.compile(loss=wqloss, optimizer="adam")
 return model
NUM_FOLDS = 7
kf = KFold(n_splits=NUM_FOLDS, shuffle=True, random_state=0)
 features = loading_features + fnc_features
overal_score = 0
for target, c, w, ff in [("age", 60, 0.3, 0.55),("domain1_var1", 12, 0.175, 0.2),("domain1_var2", 8, 0.175, 0.2),("domain2_var1", 9, 0.175, 0.22),("domain2_var2", 12, 0.175, 0.22)]:
y_oof = np.zeros(df.shape[0])
 y_test = np.zeros(( test_df.shape[0], NUM_FOLDS))
for f,(train_ind, val_ind)in enumerate(kf.split(df, df)) :
train_df, val_df = df.iloc[train_ind], df.iloc[val_ind]
train_df = train_df[train_df[target].notnull() ]
model_1 = SVR(C=c, cache_size=3000.0)
 model_1.fit(train_df[features].values, train_df[target].values)
 model_2 = Ridge(alpha = 0.0001)
 model_2.fit(train_df[features].values, train_df[target].values)
 val_pred_1 = model_1.predict(val_df[features])
 val_pred_2 = model_2.predict(val_df[features])
 test_pred_1 = model_1.predict(test_df[features])
 test_pred_2 = model_2.predict(test_df[features])
 val_pred =(1-ff)*val_pred_1+ff*val_pred_2
val_pred = cp.asnumpy(val_pred.values.flatten())
 test_pred =(1-ff)*test_pred_1+ff*test_pred_2
test_pred = cp.asnumpy(test_pred.values.flatten())
 y_oof[val_ind] = val_pred
y_test[:, f] = test_pred
df["pred_{}".format(target)] = y_oof
test_df[target] = y_test.mean(axis=1)
 score = metric(df[df[target].notnull() ][target].values, df[df[target].notnull() ]["pred_{}".format(target)].values)
 mae = mean_absolute_error(df[df[target].notnull() ][target].values, df[df[target].notnull() ]["pred_{}".format(target)].values)
 rmse = np.sqrt(mean_squared_error(df[df[target].notnull() ][target].values, df[df[target].notnull() ]["pred_{}".format(target)].values))
overal_score += w*score
print(target, np.round(score, 8))
print(target, np.round(score, 4))
print(target, 'mean absolute error:', np.round(mae, 8))
print(target, ' root mean square error:', np.round(rmse, 8))
print()
print("Overal score:", np.round(overal_score, 8))
print("Overal score:", np.round(overal_score, 4))<data_type_conversions>
net = make_model(Z.shape[2])
 ckpt = ModelCheckpoint("w.h5", monitor='val_loss', verbose=1, save_best_only=True,mode='min')
 reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2,
patience=5, min_lr=0.0005)
 es = EarlyStopping(monitor='val_loss', patience=20)
 print(net.summary() )
sub_df = cudf.melt(test_df[["Id", "age", "domain1_var1", "domain1_var2", "domain2_var1", "domain2_var2"]], id_vars=["Id"], value_name="Predicted")
 sub_df["Id"] = sub_df["Id"].astype("str")+ "_" + sub_df["variable"].astype("str")
 sub_df = sub_df.drop("variable", axis=1 ).sort_values("Id")
 assert sub_df.shape[0] == test_df.shape[0]*5
sub_df.head(10 )<save_to_csv>
net.fit_generator(DataGenerator(( C, Z, ys), brks[:-1], batch_size=10_000), epochs=100,
validation_data=(xv, yv), callbacks=[ckpt, reduce_lr, es] )
sub_df.to_csv("submission_rapids_ensemble.csv", index=False )<import_modules>
nett = make_model(Z.shape[2])
 nett.load_weights("w.h5" )
import numpy as np
import pandas as pd
from os.path import join as opj
from tqdm.notebook import tqdm<set_options>
pv = nett.predict(xv, batch_size=500, verbose=1)
 pe = nett.predict(xe, batch_size=500, verbose=1 )
%matplotlib inline
sns.set_style('darkgrid')
 sns.set_context('notebook' )<import_modules>
nett.evaluate(xv, yv, batch_size=5000 )
from sklearn.decomposition import PCA
from sklearn.preprocessing import StandardScaler, RobustScaler
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.linear_model import Ridge
from sklearn.svm import SVR<define_variables>
sv = scale[:,LEN-56:LEN-28]
se = scale[:,LEN-28:LEN]
path = '/kaggle/input/trends-feature-exploration-engineering/datasets'<load_pretrained>
names = [f"F{i+1}" for i in range(28)]
scaler_targets = joblib.load(opj(path, 'targets_scaler.pkl'))
targets = pd.read_hdf(opj(path, 'targets.h5'))
targets.head()<prepare_x_and_y>
piv = pd.DataFrame(ids[:, 0], columns=["id"] )
def load_dataset_and_scale(target, dataset_id='merge', scale_values=[1, 1, 1, 1]):
X_tr = pd.read_hdf(opj(path, '%s_train.h5' % dataset_id))
X_te = pd.read_hdf(opj(path, '%s_test.h5' % dataset_id))
y = pd.read_hdf(opj(path, 'targets.h5'))
y_tr = y.loc[X_tr.index, target]
missval = y_tr.isnull().values
idx = ~missval
X_tr = X_tr[idx]
X_te = X_te
y_tr = y_tr[idx]
print('Removing %s missing values from target dataset.' % missval.sum())
 median_offset = X_tr.iloc[:, X_tr.columns.str.contains('corr_coef')].median().mean()
X_tr.iloc[:, X_tr.columns.str.contains('corr_coef')] -= median_offset
X_te.iloc[:, X_te.columns.str.contains('corr_coef')] -= median_offset
mask_ids = []
for m in ['IC_', '_vs_', 'corr_coef', '^c[0-9]+_c[0-9]+']:
mask_ids.append(X_tr.columns.str.contains(m))
mask_ids = np.array(mask_ids)
 for i, m in enumerate(mask_ids):
if m.sum() ==0:
continue
scale_value = scale_values[i]
unify_mask_scale = np.percentile(X_tr.iloc[:, m].abs() , 90)
 X_te.iloc[:, m] /= unify_mask_scale
X_tr.iloc[:, m] /= unify_mask_scale
X_te.iloc[:, m] *= scale_value
X_tr.iloc[:, m] *= scale_value
X_tr.dropna(axis=1, inplace=True)
 X_te.dropna(axis=1, inplace=True)
 X_tr = X_tr.T.drop_duplicates().T
X_te = X_te.T.drop_duplicates().T
print('Size of dataset(train/test): ', X_tr.shape, X_te.shape)
 X_tr = X_tr.values
X_te = X_te.values
y_tr = y_tr.values
return X_tr, X_te, y_tr<prepare_x_and_y>
QUANTILES = ["0.005", "0.025", "0.165", "0.250", "0.500", "0.750", "0.835", "0.975", "0.995"]
VALID = []
EVAL = []
for i, quantile in tqdm(enumerate(QUANTILES)) :
t1 = pd.DataFrame(pv[:,:, i]*sv, columns=names)
 t1 = piv.join(t1)
 t1["id"] = t1["id"] + f"_{quantile}_validation"
t2 = pd.DataFrame(pe[:,:, i]*se, columns=names)
 t2 = piv.join(t2)
 t2["id"] = t2["id"] + f"_{quantile}_evaluation"
VALID.append(t1)
 EVAL.append(t2)
target = 'age'
tidx = 0
scale_values = [1,
1,
np.nan,
np.nan]
X_tr, X_te, y_tr = load_dataset_and_scale(target, scale_values=scale_values )<train_on_grid>
sub = pd.DataFrame()
sub = sub.append(VALID + EVAL)
 del VALID, EVAL, t1, t2
<predict_on_test><EOS> 
sub.to_csv("submission.csv", index=False )