Kaggle competition: Jane Street Market Prediction
<SOS> metric: JaneStreetPnl Kaggle data source: jane-street-market-prediction<load_from_csv>
import os, gc
import numpy as np
from numba import njit
import datatable as dtable
import pandas as pd
import janestreet
import xgboost as xgb
from hyperopt import hp, fmin, tpe, Trials
from hyperopt.pyll.base import scope
from sklearn.metrics import roc_auc_score, roc_curve
from sklearn.model_selection import GroupKFold
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
from tqdm.notebook import tqdm
from joblib import dump, load
<feature_engineering>
def weighted_average(a):
w = []
n = len(a)
 for j in range(1, n + 1):
j = 2 if j == 1 else j
w.append(1 /(2**(n + 1 - j)))
 return np.average(a, weights = w )
old_train = old_train[['image','level']]
old_train.columns = new_train.columns
old_train.diagnosis.value_counts()
new_train['id_code'] = '.. /input/aptos2019-blindness-detection/train_images/' + new_train['id_code'].astype(str)+ '.png'
old_train['id_code'] = '.. /input/retinopathy-train-2015/rescaled_train_896/rescaled_train_896/' + old_train['id_code'].astype(str)+ '.png'
train_df = old_train[:992].copy()
val_df = new_train[:480].copy()
train_df.head
print(train_df.shape)
 print(val_df.shape )<import_modules>
%%time
print('Loading...')
 train = dtable.fread('/kaggle/input/jane-street-market-prediction/train.csv' ).to_pandas()
features = [c for c in train.columns if 'feature' in c]
print('Filling...')
 train = train.query('weight > 0' ).reset_index(drop = True)
 train[features] = train[features].fillna(method = 'ffill' ).fillna(0)
 train['action'] =(train['resp'] > 0 ).astype('int')
 print('Finish.' )
import cv2
import matplotlib.pyplot as plt
import matplotlib
import os<load_from_csv>
n_splits = 5
group_gap = 31
root = '/kaggle/input/aptos2019-blindness-detection/'
train_df = pd.read_csv(os.path.join(root, 'train.csv'))<prepare_x_and_y>
class GroupTimeSeriesSplit(_BaseKFold):

 @_deprecate_positional_args
def __init__(self,
n_splits=5,
*,
max_train_size=None 
):
super().__init__(n_splits, shuffle=False, random_state=None)
 self.max_train_size = max_train_size
def split(self, X, y=None, groups=None):

 if groups is None:
raise ValueError(
 "The 'groups' parameter should not be None")
 X, y, groups = indexable(X, y, groups)
 n_samples = _num_samples(X)
 n_splits = self.n_splits
n_folds = n_splits + 1
group_dict = {}
u, ind = np.unique(groups, return_index=True)
 unique_groups = u[np.argsort(ind)]
n_samples = _num_samples(X)
 n_groups = _num_samples(unique_groups)
 for idx in np.arange(n_samples):
if(groups[idx] in group_dict):
group_dict[groups[idx]].append(idx)
 else:
group_dict[groups[idx]] = [idx]
if n_folds > n_groups:
raise ValueError(
("Cannot have number of folds={0} greater than"
" the number of groups={1}" ).format(n_folds,
n_groups))
group_test_size = n_groups // n_folds
group_test_starts = range(n_groups - n_splits * group_test_size,
n_groups, group_test_size)
 for group_test_start in group_test_starts:
train_array = []
test_array = []
for train_group_idx in unique_groups[:group_test_start]:
train_array_tmp = group_dict[train_group_idx]
train_array = np.sort(np.unique(
 np.concatenate(( train_array,
train_array_tmp)) ,
axis=None), axis=None)
 train_end = train_array.size
if self.max_train_size and self.max_train_size < train_end:
train_array = train_array[train_end -
self.max_train_size:train_end]
for test_group_idx in unique_groups[group_test_start:
group_test_start +
group_test_size]:
test_array_tmp = group_dict[test_group_idx]
test_array = np.sort(np.unique(
 np.concatenate(( test_array,
test_array_tmp)) ,
axis=None), axis=None)
 yield [int(i)for i in train_array], [int(i)for i in test_array]
class MyDataset(Dataset):
def __init__(self, dataframe, transform=None,train = True):
self.df = dataframe
self.transform = transform
self.train = train
def __len__(self):
return len(self.df)
 def __getitem__(self, idx):
label = self.df.diagnosis.values[idx]
label = np.expand_dims(label, -1)
 label = torch.tensor(label ).float()
p = self.df.id_code.values[idx]
if self.train:
image = preprocess_image_old(str(p))
else:
image = preprocess_image(str(p))
image = transforms.ToPILImage()(image)
 if self.transform:
image = self.transform(image)
 return image, label<create_dataframe>
class PurgedGroupTimeSeriesSplit(_BaseKFold):

 @_deprecate_positional_args
def __init__(self,
n_splits=5,
*,
max_train_group_size=np.inf,
max_test_group_size=np.inf,
group_gap=None,
verbose=False 
):
super().__init__(n_splits, shuffle=False, random_state=None)
 self.max_train_group_size = max_train_group_size
self.group_gap = group_gap
self.max_test_group_size = max_test_group_size
self.verbose = verbose
def split(self, X, y=None, groups=None):

 if groups is None:
raise ValueError(
 "The 'groups' parameter should not be None")
 X, y, groups = indexable(X, y, groups)
 n_samples = _num_samples(X)
 n_splits = self.n_splits
group_gap = self.group_gap
max_test_group_size = self.max_test_group_size
max_train_group_size = self.max_train_group_size
n_folds = n_splits + 1
group_dict = {}
u, ind = np.unique(groups, return_index=True)
 unique_groups = u[np.argsort(ind)]
n_samples = _num_samples(X)
 n_groups = _num_samples(unique_groups)
 for idx in np.arange(n_samples):
if(groups[idx] in group_dict):
group_dict[groups[idx]].append(idx)
 else:
group_dict[groups[idx]] = [idx]
if n_folds > n_groups:
raise ValueError(
("Cannot have number of folds={0} greater than"
" the number of groups={1}" ).format(n_folds,
n_groups))
group_test_size = min(n_groups // n_folds, max_test_group_size)
 group_test_starts = range(n_groups - n_splits * group_test_size,
n_groups, group_test_size)
 for group_test_start in group_test_starts:
train_array = []
test_array = []
group_st = max(0, group_test_start - group_gap - max_train_group_size)
 for train_group_idx in unique_groups[group_st:(group_test_start - group_gap)]:
train_array_tmp = group_dict[train_group_idx]
train_array = np.sort(np.unique(
 np.concatenate(( train_array,
train_array_tmp)) ,
axis=None), axis=None)
 train_end = train_array.size
for test_group_idx in unique_groups[group_test_start:
group_test_start +
group_test_size]:
test_array_tmp = group_dict[test_group_idx]
test_array = np.sort(np.unique(
 np.concatenate(( test_array,
test_array_tmp)) ,
axis=None), axis=None)
 test_array = test_array[group_gap:]
if self.verbose > 0:
pass
yield [int(i)for i in train_array], [int(i)for i in test_array]
train_transform = transforms.Compose([
transforms.RandomHorizontalFlip() ,
transforms.RandomRotation(( -120, 120)) ,
transforms.ToTensor() ,
transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])])
<define_variables>
def optimise(params):
print(params)
 p = {'learning_rate': params['learning_rate'],
'max_depth': params['max_depth'],
'gamma': params['gamma'],
'min_child_weight': params['min_child_weight'],
'subsample': params['subsample'],
'colsample_bytree': params['colsample_bytree'],
'verbosity': 0,
'objective': 'binary:logistic',
'eval_metric': 'auc',
'tree_method': 'gpu_hist',
'random_state': 42,
}
scores = []
gkf = PurgedGroupTimeSeriesSplit(n_splits = n_splits, group_gap = group_gap)
 for fold,(tr, te)in enumerate(gkf.split(train['action'].values, train['action'].values, train['date'].values)) :
X_tr, X_val = train.loc[tr, features].values, train.loc[te, features].values
y_tr, y_val = train.loc[tr, 'action'].values, train.loc[te, 'action'].values
d_tr = xgb.DMatrix(X_tr, y_tr)
 d_val = xgb.DMatrix(X_val, y_val)
 clf = xgb.train(p, d_tr, params['n_round'], [(d_val, 'eval')], verbose_eval = False)
 val_pred = clf.predict(d_val)
 score = roc_auc_score(y_val, val_pred)
 scores.append(score)
 del clf, val_pred, d_tr, d_val, X_tr, X_val, y_tr, y_val, score
rubbish = gc.collect()
score_avg = weighted_average(scores)
 print(score_avg)
 return - score_avg
<define_variables>
%%time
p_best = {'learning_rate': 0.014106988708201764,
'max_depth': 8,
'gamma': 9.800749651802157,
'min_child_weight': 0.3032862674190433,
'subsample': 0.4648851101943981,
'colsample_bytree': 0.994909039539885,
'objective': 'binary:logistic',
'eval_metric': 'auc',
'tree_method': 'gpu_hist',
}
X_tr, y_tr = train.loc[train['date'] > 85, features].values, train.loc[train['date'] > 85, 'action'].values
d_tr = xgb.DMatrix(X_tr, y_tr)
 models = []
for seed in range(5):
p_best['random_state'] = seed
clf = xgb.train(p_best, d_tr, 950)
 models.append(clf)
 rubbish = gc.collect()
PRETRAINED_DIR = Path('.. /input/pytorch-pretrained-models')
 EFFICIENTNET_PRETRAINED_DIR = Path('.. /input/efficientnet-pytorch')
 os.listdir('.. /input/efficientnet-pytorch/')
 PRETRAINED_MAPPING = {
'resnet18': PRETRAINED_DIR / 'resnet18-5c106cde.pth',
'resnet34': PRETRAINED_DIR / 'resnet34-333f7ec4.pth',
'resnet50': PRETRAINED_DIR / 'resnet50-19c8e357.pth',
'resnet101': PRETRAINED_DIR / 'resnet101-5d3b4d8f.pth',
'resnet152': PRETRAINED_DIR / 'resnet152-b121ed2d.pth',
'resnext101_32x4d': PRETRAINED_DIR / 'resnext101_32x4d-29e315fa.pth',
'resnext101_64x4d': PRETRAINED_DIR / 'resnext101_64x4d-e77a0586.pth',
'densenet121': PRETRAINED_DIR / 'densenet121-fbdb23505.pth',
'densenet169': PRETRAINED_DIR / 'densenet169-f470b90a4.pth',
'densenet201': PRETRAINED_DIR / 'densenet201-5750cbb1e.pth',
'densenet161': PRETRAINED_DIR / 'densenet161-347e6b360.pth',
'se_resnet50': PRETRAINED_DIR / 'se_resnet50-ce0d4300.pth',
'se_resnet101': PRETRAINED_DIR / 'se_resnet101-7e38fcc6.pth',
'se_resnet152': PRETRAINED_DIR / 'se_resnet152-d17c99b7.pth',
'se_resnext50_32x4d': PRETRAINED_DIR / 'se_resnext50_32x4d-a260b3a4.pth',
'se_resnext101_32x4d': PRETRAINED_DIR / 'se_resnext101_32x4d-3b2fe3d8.pth',
'senet154': PRETRAINED_DIR / 'senet154-c7b49a05.pth',
'inceptionv3': PRETRAINED_DIR / 'inception_v3_google-1a9a5a14.pth',
'inceptionv4': PRETRAINED_DIR / 'inceptionv4-8e4777a0.pth',
'bninception': PRETRAINED_DIR / 'bn_inception-52deb4733.pth',
'inceptionresnetv2': PRETRAINED_DIR / 'inceptionresnetv2-520b38e4.pth',
'xception': PRETRAINED_DIR / 'xception-43020ad28.pth',
'dpn68': PRETRAINED_DIR / 'dpn68-4af7d88d2.pth',
'dpn98': PRETRAINED_DIR / 'dpn98-722954780.pth',
'dpn131': PRETRAINED_DIR / 'dpn131-7af84be88.pth',
'dpn68b': PRETRAINED_DIR / 'dpn68b_extra-363ab9c19.pth',
'dpn92': PRETRAINED_DIR / 'dpn92_extra-fda993c95.pth',
'dpn107': PRETRAINED_DIR / 'dpn107_extra-b7f9f4cc9.pth',
'polynet': PRETRAINED_DIR / 'polynet-f71d82a5.pth',
'nasnetalarge': PRETRAINED_DIR / 'nasnetalarge-a1897284.pth',
'pnasnet5large': PRETRAINED_DIR / 'pnasnet5large-bf079911.pth',
'efficientnet-b0': EFFICIENTNET_PRETRAINED_DIR / 'efficientnet-b0-08094119.pth',
'efficientnet-b1': EFFICIENTNET_PRETRAINED_DIR / 'efficientnet-b1-dbc7070a.pth',
'efficientnet-b2': EFFICIENTNET_PRETRAINED_DIR / 'efficientnet-b2-27687264.pth',
'efficientnet-b3': EFFICIENTNET_PRETRAINED_DIR / 'efficientnet-b3-c8376fa2.pth',
'efficientnet-b4': EFFICIENTNET_PRETRAINED_DIR / 'efficientnet-b4-e116e8b3.pth',
'efficientnet-b5': EFFICIENTNET_PRETRAINED_DIR / 'efficientnet-b5-586e6cc6.pth',
}<define_variables>
@njit
def fast_fillna(array, values):
if np.isnan(array.sum()):
array = np.where(np.isnan(array), values, array)
 return array
train.loc[0, features[1:]] = fast_fillna(train.loc[0, features[1:]].values, 0 )
<choose_model_class>
env = janestreet.make_env()
env_iter = env.iter_test()
<choose_model_class><EOS> 
opt_th = 0.505
tmp = np.zeros(len(features))
for(test_df, pred_df)in tqdm(env_iter):
if test_df['weight'].item() > 0:
x_tt = test_df.loc[:, features].values
x_tt[0, :] = fast_fillna(x_tt[0, :], tmp)
 tmp = x_tt[0, :]
d_tt = xgb.DMatrix(x_tt)
 pred = 0.
 for clf in models:
pred += clf.predict(d_tt)/ len(models)
 pred_df.action = np.where(pred >= opt_th, 1, 0 ).astype(int)
 else:
pred_df.action = 0
env.predict(pred_df )