Kaggle competition: M5 Forecasting - Uncertainty
df_total_sales_customers = pd.DataFrame({'Sales': total_sales_customers['Sales'],
'Customers': total_sales_customers['Customers']},
index = total_sales_customers.index)
 df_total_sales_customers = df_total_sales_customers.reset_index()
df_total_sales_customers.head()<groupby>
price=pd.read_csv("/kaggle/input/m5-forecasting-uncertainty/sell_prices.csv")
 calen=pd.read_csv("/kaggle/input/m5-forecasting-uncertainty/calendar.csv" )
avg_sales_customers = df_train.groupby('Store')['Sales', 'Customers'].mean()
avg_sales_customers.head()<merge>
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","scale","start"],
var_name='d', value_name='demand')
 print("generating order")
 if start is not None:
skip = start
else:
skip = 1
sales["nb"] =sales.index // 42840 + skip
return sales
df_avg_sales_customers = pd.DataFrame({'Sales': avg_sales_customers['Sales'],
'Customers': avg_sales_customers['Customers']},
index = avg_sales_customers.index)
 df_avg_sales_customers = df_avg_sales_customers.reset_index()
df_stores_avg = df_avg_sales_customers.join(df_store.set_index('Store'), on='Store')
 df_stores_avg.head()<merge>
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.drop(["event_name_1", "event_name_2", "event_type_1", "event_type_2", "date", "weekday"],
axis=1, inplace=True)
 return calendar
df_stores_new = df_total_sales_customers.join(df_store.set_index('Store'), on='Store')
 df_stores_new.head()<groupby>
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.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')
 del calendar
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)
 gc.collect()
return sales
average_storetype = df_stores_new.groupby('StoreType')['Sales', 'Customers', 'CompetitionDistance'].mean()
fig,(axis1,axis2,axis3)= plt.subplots(1,3,figsize=(15,4))
sns.barplot(average_storetype.index, average_storetype['Sales'], ax=axis1)
 sns.barplot(average_storetype.index, average_storetype['Customers'], ax=axis2)
 sns.barplot(average_storetype.index, average_storetype['CompetitionDistance'], ax=axis3 )<load_from_csv>
import time
import gc
df_train = pd.read_csv(".. /input/train.csv")
 df_store = pd.read_csv(".. /input/store.csv")
 df_test = pd.read_csv(".. /input/test.csv" )<feature_engineering>
%%time
CATEGORIZE = True;
START = 1400; UPPER = 1970;
maps = {}
mods = {}
sales = make_dataset(categorize=CATEGORIZE ,start=START, upper= UPPER )
closed_store_ids = df_test["Id"][df_test["Open"] == 0].values
df_train['Year'] = df_train['Date'].apply(lambda x: int(x[:4]))
df_train['Month'] = df_train['Date'].apply(lambda x: int(x[5:7]))
df_train["HolidayBin"] = df_train.StateHoliday.map({"0": 0, "a": 1, "b": 1, "c": 1})
 del df_train['Date']
del df_train['StateHoliday']
df_train.head()<feature_engineering>
from tqdm import tqdm
df_test['Year'] = df_test['Date'].apply(lambda x: int(x[:4]))
df_test['Month'] = df_test['Date'].apply(lambda x: int(x[5:7]))
df_test["HolidayBin"] = df_test.StateHoliday.map({"0": 0, "a": 1, "b": 1, "c": 1})
 del df_test['Date']
del df_test['StateHoliday']
df_test.head()<feature_engineering>
sales = sales.loc[sales.nb>sales.start]
print(sales.shape)
 nb = sales['nb'].values
MAX_LAG = max(LAGS)
 tr_mask = np.logical_and(nb>START + MAX_LAG, nb<=1941)
 val_mask = np.logical_and(nb>1913, nb<=1941)
 te_mask = np.logical_and(nb>1941, nb<=1969 )
a = list()
for i in df_test['Store']:
a.append(float(df_store['CompetitionDistance'][df_store['Store'] == i]))
df_test['CompetitionDistance'] = a
df_test.head()<feature_engineering>
scale = sales['scale'].values
ids = sales['id'].values
ys = sales['x'].values
Z = sales[FEATS].values
a = list()
for i in df_train['Store']:
a.append(float(df_store['CompetitionDistance'][df_store['Store'] == i]))
df_train['CompetitionDistance'] = a
df_train['CompetitionDistance'] = df_train['CompetitionDistance'].fillna(df_train['CompetitionDistance'].mean())
 df_train.head()<feature_engineering>
sv = scale[val_mask]
se = scale[te_mask]
ids = ids[te_mask]
ids = ids.reshape(( -1, 28))
df_train['CompetitionDistance'] = np.log(df_train['CompetitionDistance'])
 df_test ['CompetitionDistance'] = np.log(df_test ['CompetitionDistance'] )<compute_test_metric>
ca = sales[['snap_CA']].values
tx = sales[['snap_TX']].values
wi = sales[['snap_WI']].values
wday = sales[['wday']].values
month = sales[['month']].values
year = sales[['year']].values
event = sales[['event_name']].values
nday = sales[['nday']].values
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>
item = sales[['item_id']].values
dept = sales[['dept_id']].values
cat = sales[['cat_id']].values
store = sales[['store_id']].values
state = sales[['state_id']].values
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>
def make_data(mask):
x = {"snap_CA":ca[mask], "snap_TX":tx[mask], "snap_WI":wi[mask], "wday":wday[mask],
"month":month[mask], "year":year[mask], "event":event[mask], "nday":nday[mask],
"item":item[mask], "dept":dept[mask], "cat":cat[mask], "store":store[mask],
"state":state[mask], "num":Z[mask]}
t = ys[mask]
return x, t
FNC_SCALE = 1/600
df[fnc_features] *= FNC_SCALE
test_df[fnc_features] *= FNC_SCALE<prepare_x_and_y>
xt, yt = make_data(tr_mask)
 xv, yv = make_data(val_mask)
 xe, ye = make_data(te_mask )
%%time
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.00008)
 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>
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
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>
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 )
sub_df.to_csv("submission_rapids_ensemble.csv", index=False )<import_modules>
def make_model(n_in):
num = L.Input(( n_in,), name="num")
 ca = L.Input(( 1,), name="snap_CA")
 tx = L.Input(( 1,), name="snap_TX")
 wi = L.Input(( 1,), name="snap_WI")
 wday = L.Input(( 1,), name="wday")
 month = L.Input(( 1,), name="month")
 year = L.Input(( 1,), name="year")
 event = L.Input(( 1,), name="event")
 nday = L.Input(( 1,), name="nday")
 item = L.Input(( 1,), name="item")
 dept = L.Input(( 1,), name="dept")
 cat = L.Input(( 1,), name="cat")
 store = L.Input(( 1,), name="store")
 state = L.Input(( 1,), 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_]
emb = L.Concatenate(name="embds" )(p)
 context = L.Flatten(name="context" )(emb)
 x = L.Concatenate(name="x1" )([context, num])
 x = L.Dense(500, activation="relu", name="d1" )(x)
 x = L.Dropout(0.3 )(x)
 x = L.Concatenate(name="m1" )([x, context])
 x = L.Dense(500, activation="relu", name="d2" )(x)
 x = L.Dropout(0.3 )(x)
 x = L.Concatenate(name="m2" )([x, context])
 x = L.Dense(500, activation="relu", name="d3" )(x)
 preds = L.Dense(9, activation="linear", name="preds" )(x)
 model = M.Model(inp, preds, name="M1")
 model.compile(loss=qloss, optimizer="adam")
 return model
import numpy as np
import pandas as pd<define_variables>
net = make_model(len(FEATS))
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.001)
 es = EarlyStopping(monitor='val_loss', patience=3)
 print(net.summary() )
algorithm = ['lasso', 'elastic', 'ridge', 'lightgbm', 'xgboost', 'svr', 'linear', 'tweedie']
columns = ['age', 'domain1_var1', 'domain1_var2', 'domain2_var1', 'domain2_var2']<load_from_csv>
net.fit(xt, yt, batch_size=50_000, epochs=20, validation_data=(xv, yv), callbacks=[ckpt, reduce_lr, es] )
DATA_PATH = '.. /input/brain-models/'
df_pred = pd.read_csv(DATA_PATH + 'training_ridge.csv')['Id']<load_from_csv>
nett = make_model(len(FEATS))
nett.load_weights("w.h5" )
for a in algorithm:
p = pd.read_csv(DATA_PATH + 'training_{}.csv'.format(a))
for c in p.columns[1:]:
p['{}_{}'.format(a,c[5:])] = p[c]
p = p.drop(c, axis=1)
 df_pred = pd.merge(df_pred, p, on='Id' )<load_from_csv>
pv = nett.predict(xv, batch_size=50_000, verbose=1)
 pe = nett.predict(xe, batch_size=50_000, verbose=1 )
df_sub = pd.read_csv(DATA_PATH + 'submission_ridge.csv')['Id']
for a in algorithm:
p = pd.read_csv(DATA_PATH + 'submission_{}.csv'.format(a))
for c in p.columns[1:]:
p['{}_{}'.format(a,c)] = p[c]
p = p.drop(c, axis=1)
 df_sub = pd.merge(df_sub, p, on='Id' )<drop_column>
nett.evaluate(xv, yv, batch_size=50_000 )
def extract_algo(df, col):
for c in df.columns[1:]:
if col not in c:
df = df.drop(c, axis=1)
 for c in df.columns[1:]:
s = c.split('_')[0]
df[s] = df[c]
df = df.drop(c, axis=1)
 return df<features_selection>
import matplotlib.pyplot as plt
extract_algo(df_pred, 'age' )<load_from_csv>
names = [f"F{i+1}" for i in range(28)]
piv = pd.DataFrame(ids[:, 0], columns=["id"])
 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 )
<merge><EOS> 
sub = pd.DataFrame()
sub = sub.append(VALID + EVAL)
 del VALID, EVAL, t1, t2
sub.to_csv("submission.csv", index=False )