Kaggle competition: Restaurant Revenue Prediction
def run_k_fold(NFOLDS, seed_id):
oof = np.zeros(( len(train), len(target_cols)))
 predictions = np.zeros(( len(test), len(target_cols)))
 for fold_id in range(NFOLDS):
oof_, pred_ = run_training(fold_id, seed_id)
 predictions += pred_ / NFOLDS
oof += oof_
score = 0
for i in range(len(target_cols)) :
_score = log_loss(train.loc[:,target_cols[i]].values, oof[:,i])
 score += _score / len(target_cols)
 print(f"
return oof, predictions, score<categorify>
df_train = pd.read_csv(f'{PATH}train.csv', parse_dates=['Open Date'])
 df_test = pd.read_csv(f'{PATH}test.csv', parse_dates=['Open Date'])
 df_joined = pd.concat([df_train.drop('revenue', axis=1), df_test], axis=0 )
SEED = [0, 1, 2, 3, 4, 5, 6]
oof = np.zeros(( len(train), len(target_cols)))
 predictions = np.zeros(( len(test), len(target_cols)))
 scores = []
time_begin = time()
for seed_id in SEED:
oof_, predictions_, score_ = run_k_fold(NFOLDS, seed_id)
 oof += oof_ / len(SEED)
 predictions += predictions_ / len(SEED)
 scores.append(score_)
 print('-'*80)
 for i in range(len(scores)) :
print(f'
score = 0
for i in range(len(target_cols)) :
_score = log_loss(train.loc[:,target_cols[i]].values, oof[:,i])
 score += _score / len(target_cols)
 print(f"
time_diff = time() - time_begin
train[target_cols] = oof
test[target_cols] = predictions<feature_engineering>
def score(model, X_train, y_train, X_valid = [], y_valid = []):
rms = sqrt(mean_squared_error(np.square(np.exp(y_train)) , np.square(np.exp(model.predict(X_train)))))
 score = [rms, model.score(X_train, y_train)]
if len(X_valid)!= 0 and len(y_valid)!= 0:
score.append(sqrt(mean_squared_error(np.square(np.exp(y_valid)) , np.square(np.exp(model.predict(X_valid))))))
if model.oob_score:
score.append(model.oob_score_)
 return score
n_train = df_train.shape[0]
def prcs(df, fe=[]):
add_datepart(df, 'Open Date')
 if 'city' in fe:
df = df.drop('City', axis=1)
 if 'outlier' in fe:
df = df.drop(index=16, axis=0)
 if 'MB' in fe:
df['Type'] = df['Type'].replace('MB', 'DT')
 if 'city_group' in fe:
df = df.drop('City Group', axis=1)
 if 'dummies' in fe:
p_cols = [ f'P{n}' for n in range(1,38)]
df = pd.get_dummies(df, columns=p_cols)
 if 'city_group' not in fe:
df = pd.get_dummies(df, columns=['City Group'], drop_first=True)
 df = pd.get_dummies(df, columns=['Type'])
 train_cats(df)
 X, _, _ = proc_df(df, None)
 drop_cols = ['Open Year', 'Open Month', 'Open Week', 'Open Day', 'Open Dayofweek',
'Open Dayofyear', 'Open Is_month_end', 'Open Is_month_start',
'Open Is_quarter_end', 'Open Is_quarter_start', 'Open Is_year_end',
'Open Is_year_start']
X = X.drop(drop_cols, axis=1)
 if 'id' in fe:
X = X.drop('Id', axis=1)
 if 'scale_open' in fe:
X['Open Elapsed'] =(X['Open Elapsed']/1000 ).apply(np.log)
 X_train = X[:n_train]
X_test = X[n_train:]
return X_train, X_test
def train_cv(X, y):
models = []
scores = []
kf = KFold(n_splits=4, random_state=12, shuffle=False)
 for train_index, val_index in kf.split(X):
X_train_ = X.iloc[train_index]
y_train_ = y.iloc[train_index]
X_val_ = X.iloc[val_index]
y_val_ = y.iloc[val_index]
m = RandomForestRegressor(n_jobs=-1, n_estimators=100, max_features=0.5, oob_score=True)
 m.fit(X_train_, y_train_)
 models.append(m)
 scores.append(score(m, X_train_, y_train_, X_val_, y_val_))
return models, np.array(scores ).mean(axis=0)
 def predict(models, X):
f = 1 / len(models)
 pred = 0
for m in models:
pred += f * m.predict(X)
 return pred
str(timedelta(seconds=time_diff))<save_to_csv>
X_train, X_test = prcs(df_joined.copy())
 y_train = df_train['revenue'].copy().apply(np.log )
train[['sig_id']+target_cols].to_csv(f'oof_{MDL_NAME}.csv', index=False )<compute_test_metric>
m = RandomForestRegressor(n_jobs=-1, n_estimators=150, oob_score=True, max_features=0.5)
 m.fit(X_train, y_train)
 score(m,X_train, y_train )
valid_results = train_targets_scored.drop(columns=target_cols ).merge(train[['sig_id']+target_cols], on='sig_id', how='left' ).fillna(0)
 y_true = train_targets_scored[target_cols].values
y_pred = valid_results[target_cols].values
score = 0
for i in range(len(target_cols)) :
score += log_loss(y_true[:, i], y_pred[:, i])
 print("CV log_loss: ", score / y_pred.shape[1] )<save_to_csv>
df_preds = pd.DataFrame(columns=['Prediction'],index=X_test.index, data=np.exp(predict(m, X_test)))
 df_preds.to_csv('submission0.csv', index=True, index_label='Id')
 df_preds.head()
sub = sample_submission.drop(columns=target_cols ).merge(test[['sig_id']+target_cols], on='sig_id', how='left' ).fillna(0)
 sub.to_csv(f'submission.csv', index=False )<set_options>
models, scores = train_cv(X_train, y_train)
 print(scores )
warnings.filterwarnings("ignore", category=FutureWarning )<import_modules>
df_preds = pd.DataFrame(columns=['Prediction'],index=X_test.index, data=np.exp(predict(models, X_test)))
 df_preds.to_csv('submission1.csv', index=True, index_label='Id')
 df_preds.head()
from tensorflow.keras.callbacks import ReduceLROnPlateau, ModelCheckpoint, EarlyStopping
import numpy as np
import pandas as pd
import tensorflow as tf
from tensorflow.keras import layers
from tensorflow.keras import activations
from tensorflow.keras.models import Sequential,load_model
import gc
import os
from scipy import stats
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.model_selection import KFold
from sklearn.metrics import log_loss
import tensorflow_addons as tfa
import matplotlib.pyplot as plt
from tqdm import tqdm
from xgboost import XGBClassifier
from sklearn.model_selection import KFold
from category_encoders import CountEncoder
from sklearn.pipeline import Pipeline
from sklearn.multioutput import MultiOutputClassifier<load_from_csv>
X_train, X_test = prcs(df_joined.copy() , fe=['id'])
 y_train = df_train['revenue'].copy().apply(np.sqrt ).apply(np.log )
train_features = pd.read_csv('.. /input/lish-moa/train_features.csv')
 train_targets = pd.read_csv('.. /input/lish-moa/train_targets_scored.csv')
 test_features = pd.read_csv('.. /input/lish-moa/test_features.csv')
 ss = pd.read_csv('.. /input/lish-moa/sample_submission.csv')
 train_features.shape<feature_engineering>
models, scores = train_cv(X_train, y_train)
 print(scores )
print(set(train_features['cp_time']), set(test_features['cp_time']))
train_features['cp_time_24'] =(train_features['cp_time'] == 24)+ 0
train_features['cp_time_48'] =(train_features['cp_time'] == 48)+ 0
test_features['cp_time_24'] =(test_features['cp_time'] == 24)+ 0
test_features['cp_time_48'] =(test_features['cp_time'] == 48)+ 0
train_features.drop('cp_time', axis = 1, inplace = True)
 test_features.drop('cp_time', axis = 1, inplace = True)
 print(set(train_features['cp_dose']), set(test_features['cp_dose']))
train_features['cp_dose_D1'] =(train_features['cp_dose'] == 'D1')+ 0
test_features['cp_dose_D1'] =(test_features['cp_dose'] == 'D1')+ 0
train_features.drop('cp_dose', axis = 1, inplace = True)
 test_features.drop('cp_dose', axis = 1, inplace = True)
 train_features['cp_type_control'] =(train_features['cp_type'] == 'ctl_vehicle')+ 0
test_features['cp_type_control'] =(test_features['cp_type'] == 'ctl_vehicle')+ 0
train_features.drop('cp_type', axis = 1, inplace = True)
 test_features.drop('cp_type', axis = 1, inplace = True)
 train=train_features
test=test_features
del train_targets['sig_id']
del train['sig_id']
del test['sig_id'] 
<drop_column>
df_preds = pd.DataFrame(columns=['Prediction'],index=X_test.index, data=np.square(np.exp(predict(models, X_test))))
df_preds.to_csv('submission2.csv', index=True, index_label='Id')
 df_preds.head()
cols=train_features.columns
cols = ['cp_time_24','cp_time_48','cp_type_control'] + [col for col in cols if(col != 'cp_time_24')and(col != 'cp_time_48')and(col!='cp_type_control')]
train=train[cols]
test=test[cols]<categorify>
X_train, X_test = prcs(df_joined.copy() , fe=['id', 'dummies'])
 y_train = df_train['revenue'].copy().apply(np.sqrt ).apply(np.log )
<choose_model_class>
models, scores = train_cv(X_train, y_train)
 print(scores )
def mlp1(num_columns):
model = tf.keras.Sequential()
model.add(layers.Input(shape=(num_columns,)))
 model.add(layers.GaussianNoise(0.05))
model.add(layers.Dense(128))
model.add(tf.keras.layers.PReLU())
 model.add(layers.Dropout(0.25))
model.add(layers.GaussianNoise(0.01))
model.add(layers.Dense(128))
model.add(tf.keras.layers.PReLU())
 model.add(layers.Dropout(0.25))
model.add(layers.Dense(206, activation="sigmoid"))
model.compile(tfa.optimizers.AdamW(lr = 1e-3, weight_decay = 1e-5, clipvalue = 900),
loss='binary_crossentropy', 
)
 return model
def mlp2(num_columns):
model = tf.keras.Sequential()
model.add(layers.Input(shape=(num_columns,)))
 model.add(tfa.layers.WeightNormalization(layers.Dense(512,activation='relu',kernel_initializer='glorot_normal')))
 model.add(layers.Dropout(0.25))
model.add(tfa.layers.WeightNormalization(layers.Dense(1024,activation='relu',kernel_initializer='glorot_normal')))
 model.add(tf.keras.layers.BatchNormalization())
 model.add(layers.Dropout(0.25))
model.add(layers.Dense(206, activation="sigmoid"))
model.compile(tfa.optimizers.AdamW(lr = 1e-3, weight_decay = 1e-5, clipvalue = 900),
loss='binary_crossentropy', 
)
 return model
def mlp3(num_columns):
model = tf.keras.Sequential()
model.add(layers.Input(shape=(num_columns,)))
 model.add(tfa.layers.WeightNormalization(layers.Dense(1024,activation='sigmoid')))
 model.add(tf.keras.layers.BatchNormalization())
 model.add(layers.Dropout(0.25))
model.add(tfa.layers.WeightNormalization(layers.Dense(512,activation='sigmoid')))
 model.add(tf.keras.layers.BatchNormalization())
 model.add(layers.Dropout(0.25))
model.add(layers.Dense(206, activation="sigmoid"))
model.compile(tfa.optimizers.AdamW(lr = 1e-3, weight_decay = 1e-5, clipvalue = 900),
loss='binary_crossentropy', 
)
 return model
def mlp4(num_columns):
model = tf.keras.Sequential([
tf.keras.layers.Input(num_columns),
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.2),
tf.keras.layers.Dense(1024),
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.41),
tf.keras.layers.PReLU() ,
tf.keras.layers.Dense(512),
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.38),
tf.keras.layers.PReLU() ,
tf.keras.layers.Dense(256),
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.35),
tf.keras.layers.PReLU() ,
tf.keras.layers.Dense(206, activation="sigmoid")])
 model.compile(tfa.optimizers.AdamW(lr = 1e-3, weight_decay = 1e-5, clipvalue = 900),
loss='binary_crossentropy', 
)
 return model
def mlp5(num_columns):
model = tf.keras.Sequential([
tf.keras.layers.Input(num_columns),
tf.keras.layers.BatchNormalization() ,
tfa.layers.WeightNormalization(tf.keras.layers.Dense(6144, activation = "elu")) ,
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.4),
tfa.layers.WeightNormalization(tf.keras.layers.Dense(6144, activation = "elu")) ,
tf.keras.layers.BatchNormalization() ,
tf.keras.layers.Dropout(0.4),
tfa.layers.WeightNormalization(tf.keras.layers.Dense(206, activation = "sigmoid"))
])
 model.compile(tfa.optimizers.AdamW(lr = 1e-3, weight_decay = 1e-5, clipvalue = 900),
loss='binary_crossentropy', 
)
 return model<randomize_order>
df_preds = pd.DataFrame(columns=['Prediction'],index=X_test.index, data=np.square(np.exp(predict(models, X_test))))
df_preds.to_csv('submission3.csv', index=True, index_label='Id')
 df_preds.head()
<define_variables>
X_train, X_test = prcs(df_joined.copy() , fe=['id', 'dummies', 'city'])
 y_train = df_train['revenue'].copy().apply(np.sqrt ).apply(np.log )
top_feats = [ 0, 1, 2, 3, 5, 6, 8, 9, 10, 11, 12, 14, 15,
16, 18, 19, 20, 21, 23, 24, 25, 27, 28, 29, 30, 31,
32, 33, 34, 35, 36, 37, 39, 40, 41, 42, 44, 45, 46,
48, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61,
63, 64, 65, 66, 68, 69, 70, 71, 72, 73, 74, 75, 76,
78, 79, 80, 81, 82, 83, 84, 86, 87, 88, 89, 90, 92,
93, 94, 95, 96, 97, 99, 100, 101, 103, 104, 105, 106, 107,
108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120,
121, 122, 123, 124, 125, 126, 127, 128, 129, 130, 132, 133, 134,
135, 136, 137, 138, 139, 140, 141, 142, 143, 144, 145, 146, 147,
149, 150, 151, 152, 153, 154, 155, 157, 159, 160, 161, 163, 164,
165, 166, 167, 168, 169, 170, 172, 173, 175, 176, 177, 178, 180,
181, 182, 183, 184, 186, 187, 188, 189, 190, 191, 192, 193, 195,
197, 198, 199, 202, 203, 205, 206, 208, 209, 210, 211, 212, 213,
214, 215, 218, 219, 220, 221, 222, 224, 225, 227, 228, 229, 230,
231, 232, 233, 234, 236, 238, 239, 240, 241, 242, 243, 244, 245,
246, 248, 249, 250, 251, 253, 254, 255, 256, 257, 258, 259, 260,
261, 263, 265, 266, 268, 270, 271, 272, 273, 275, 276, 277, 279,
282, 283, 286, 287, 288, 289, 290, 294, 295, 296, 297, 299, 300,
301, 302, 303, 304, 305, 306, 308, 309, 310, 311, 312, 313, 315,
316, 317, 320, 321, 322, 324, 325, 326, 327, 328, 329, 330, 331,
332, 333, 334, 335, 338, 339, 340, 341, 343, 344, 345, 346, 347,
349, 350, 351, 352, 353, 355, 356, 357, 358, 359, 360, 361, 362,
363, 364, 365, 366, 368, 369, 370, 371, 372, 374, 375, 376, 377,
378, 379, 380, 382, 383, 384, 385, 386, 387, 388, 389, 390, 391,
392, 393, 394, 395, 397, 398, 399, 400, 401, 403, 405, 406, 407,
408, 410, 411, 412, 413, 414, 415, 417, 418, 419, 420, 421, 422,
423, 424, 425, 426, 427, 428, 429, 430, 431, 432, 433, 434, 435,
436, 437, 438, 441, 442, 443, 444, 445, 446, 447, 448, 449, 450,
452, 453, 454, 456, 457, 458, 459, 460, 461, 462, 463, 464, 465,
466, 468, 469, 471, 472, 473, 474, 475, 476, 477, 478, 479, 482,
483, 485, 486, 487, 488, 489, 491, 492, 494, 495, 496, 500, 501,
502, 503, 505, 506, 507, 509, 510, 511, 512, 513, 514, 516, 517,
518, 519, 521, 523, 525, 526, 527, 528, 529, 530, 531, 532, 533,
534, 536, 537, 538, 539, 540, 541, 542, 543, 544, 545, 546, 547,
549, 550, 553, 554, 555, 556, 557, 558, 559, 560, 561, 562, 563,
564, 565, 566, 567, 569, 570, 571, 572, 573, 574, 575, 577, 580,
581, 582, 583, 586, 587, 590, 591, 592, 593, 595, 596, 597, 598,
599, 600, 601, 602, 603, 605, 607, 608, 609, 611, 612, 613, 614,
615, 616, 617, 619, 622, 623, 625, 627, 630, 631, 632, 633, 634,
635, 637, 638, 639, 642, 643, 644, 645, 646, 647, 649, 650, 651,
652, 654, 655, 658, 659, 660, 661, 662, 663, 664, 666, 667, 668,
669, 670, 672, 674, 675, 676, 677, 678, 680, 681, 682, 684, 685,
686, 687, 688, 689, 691, 692, 694, 695, 696, 697, 699, 700, 701,
702, 703, 704, 705, 707, 708, 709, 711, 712, 713, 714, 715, 716,
717, 723, 725, 727, 728, 729, 730, 731, 732, 734, 736, 737, 738,
739, 740, 741, 742, 743, 744, 745, 746, 747, 748, 749, 750, 751,
752, 753, 754, 755, 756, 758, 759, 760, 761, 762, 763, 764, 765,
766, 767, 769, 770, 771, 772, 774, 775, 780, 781, 782, 783, 784,
785, 787, 788, 790, 793, 795, 797, 799, 800, 801, 805, 808, 809,
811, 812, 813, 816, 819, 820, 821, 822, 823, 825, 826, 827, 829,
831, 832, 833, 834, 835, 837, 838, 839, 840, 841, 842, 844, 845,
846, 847, 848, 850, 851, 852, 854, 855, 856, 858, 860, 861, 862,
864, 867, 868, 870, 871, 873, 874,875]
print(len(top_feats))<compute_test_metric>
models, scores = train_cv(X_train, y_train)
 print(scores )
def metric(y_true, y_pred):
metrics = []
for _target in train_targets.columns:
metrics.append(log_loss(y_true.loc[:, _target], y_pred.loc[:, _target].astype(float), labels=[0,1]))
return np.mean(metrics)
<feature_engineering>
df_preds = pd.DataFrame(columns=['Prediction'],index=X_test.index, data=np.square(np.exp(predict(models, X_test))))
df_preds.to_csv('submission4.csv', index=True, index_label='Id')
 df_preds.head()
models={'mlp1':mlp1,'mlp2':mlp2,'mlp3':mlp3,'mlp4':mlp4,'mlp5':mlp5}
paths=['mlp1.h5','mlp2.h5','mpl3.h5','mlp4.h5','mlp5.h5']
N_STARTS = 3
res = train_targets.copy()
ss.loc[:, train_targets.columns] = 0
res.loc[:, train_targets.columns] = 0
for seed in range(N_STARTS):
print('Seed: ',seed)
 for n,(tr, te)in enumerate(MultilabelStratifiedKFold(n_splits=5, random_state=seed, shuffle=True ).split(train_targets, train_targets)) :
print(f'Fold {n}')
 for m,model_path in zip(models,paths):
model=models[m](len(top_feats))
X_train, X_val = train.loc[tr,:], train.loc[te,:]
y_train, y_val = train_targets.loc[tr,:], train_targets.loc[te,:]
if m.startswith('LSTM'):
train_fe=train_fe[:,:,None]
val_fe=val_fe[:,:,None]
checkpoint_path = f'repeat:{seed}_Fold:{n}_model:{m}.hdf5'
reduce_lr_loss = ReduceLROnPlateau(monitor='val_loss', factor=0.1, patience=3, verbose=0, epsilon=1e-4, mode='min')
 cb_checkpt = ModelCheckpoint(checkpoint_path, monitor = 'val_loss', verbose = 0, save_best_only = True,
save_weights_only = True, mode = 'min')
 early = EarlyStopping(monitor="val_loss", mode="min", patience= 5)
 model.fit(X_train.values[:, top_feats],
y_train.values,
validation_data=(X_val.values[:, top_feats], y_val.values),
epochs=25, batch_size=128,
callbacks=[reduce_lr_loss,cb_checkpt, early], verbose=0 
)
 model.load_weights(checkpoint_path)
 print('Model: ',m,' val loss: ',model.evaluate(X_val.values[:, top_feats], y_val.values,verbose=0))
test_predict = model.predict(test.values[:, top_feats])
 val_predict = model.predict(X_val.values[:, top_feats])
 ss.loc[:, train_targets.columns] += test_predict
res.loc[te, train_targets.columns] += val_predict
del model
gc.collect()
os.remove(checkpoint_path)
 print('')
<compute_test_metric>
X_train, X_test = prcs(df_joined.copy() , fe=['id', 'dummies', 'city', 'city_group'])
 y_train = df_train['revenue'].copy().apply(np.sqrt ).apply(np.log )
print(f'OOF Metric({len(paths)} NN): {metric(train_targets, res)}' )<feature_engineering>
models, scores = train_cv(X_train, y_train)
 print(scores )
<save_to_csv><EOS> 
df_preds = pd.DataFrame(columns=['Prediction'],index=X_test.index, data=np.square(np.exp(predict(models, X_test))))
df_preds.to_csv('submission5.csv', index=True, index_label='Id')
 df_preds.head()