Kaggle competition: Santander Customer Transaction Prediction
all_data['_totalDistance'] = all_data['rideDistance'] + all_data['walkDistance'] + all_data['swimDistance']
all_data['_healthItems'] = all_data['heals'] + all_data['boosts']
all_data['_headshotKillRate'] = all_data['headshotKills'] / all_data['kills']
all_data['_killPlaceOverMaxPlace'] = all_data['killPlace'] / all_data['maxPlace']
all_data['_killsOverWalkDistance'] = all_data['kills'] / all_data['walkDistance']
fillInf(all_data, 0 )<feature_engineering>
random_state = 42
np.random.seed(random_state)
 df_train = pd.read_csv('.. /input/train.csv')
 df_test = pd.read_csv('.. /input/test.csv' )
match = all_data.groupby('matchId')
 all_data['killsPerc'] = match['kills'].rank(pct=True ).values
all_data['killPlacePerc'] = match['killPlace'].rank(pct=True ).values
all_data['walkDistancePerc'] = match['walkDistance'].rank(pct=True ).values
all_data['walkPerc_killsPerc'] = all_data['walkDistancePerc'] / all_data['killsPerc'] 
<drop_column>
def augment(x,y,t=2):
xs,xn = [],[]
for i in range(t):
mask = y>0
x1 = x[mask].copy()
ids = np.arange(x1.shape[0])
 for c in range(x1.shape[1]):
np.random.shuffle(ids)
 x1[:,c] = x1[ids][:,c]
xs.append(x1)
 for i in range(t//2):
mask = y==0
x1 = x[mask].copy()
ids = np.arange(x1.shape[0])
 for c in range(x1.shape[1]):
np.random.shuffle(ids)
 x1[:,c] = x1[ids][:,c]
xn.append(x1)
 xs = np.vstack(xs)
 xn = np.vstack(xn)
 ys = np.ones(xs.shape[0])
 yn = np.zeros(xn.shape[0])
 x = np.vstack([x,xs,xn])
 y = np.concatenate([y,ys,yn])
 return x,y
all_data.drop(['boosts','heals','revives','assists'], axis=1, inplace=True)
 all_data.drop(['headshotKills','roadKills','vehicleDestroys','teamKills'], axis=1, inplace=True)
 all_data.drop(['rideDistance','swimDistance','matchDuration'], axis=1, inplace=True)
 all_data.drop(['rankPoints','killPoints','winPoints'], axis=1, inplace=True )<groupby>
lgb_params = {
"objective" : "binary",
"metric" : "auc",
"boosting": 'gbdt',
"max_depth" : -1,
"num_leaves" : 13,
"learning_rate" : 0.01,
"bagging_freq": 5,
"bagging_fraction" : 0.4,
"feature_fraction" : 0.05,
"min_data_in_leaf": 80,
"min_sum_heassian_in_leaf": 10,
"tree_learner": "serial",
"boost_from_average": "false",
"bagging_seed" : random_state,
"verbosity" : 1,
"seed": random_state
}
match = all_data.groupby(['matchId'])
 group = all_data.groupby(['matchId','groupId','matchType'])
 agg_col = list(all_data.columns)
 exclude_agg_col = ['Id','matchId','groupId','matchType','maxPlace','numGroups','winPlacePerc']
for c in exclude_agg_col:
agg_col.remove(c)
 print(agg_col)
 sum_col = ['kills','killPlace','damageDealt','walkDistance','_healthItems']<categorify>
skf = StratifiedKFold(n_splits=5, shuffle=True, random_state=random_state)
 oof = df_train[['ID_code', 'target']]
oof['predict'] = 0
predictions = df_test[['ID_code']]
val_aucs = []
feature_importance_df = pd.DataFrame()
minKills = all_data.sort_values(['matchId','groupId','kills','killPlace'] ).groupby(
 ['matchId','groupId','kills'] ).first().reset_index().copy()
for n in np.arange(5):
c = 'kills_' + str(n)+ '_Place'
nKills =(minKills['kills'] == n)
 minKills.loc[nKills, c] = minKills[nKills].groupby(['matchId'])['killPlace'].rank().values
match_data = pd.merge(match_data, minKills[nKills][['matchId','groupId',c]], how='left')
 match_data[c].fillna(0, inplace=True)
 match_data = reduce_mem_usage(match_data)
 del minKills, nKills
print(match_data.shape )<merge>
features = [col for col in df_train.columns if col not in ['target', 'ID_code']]
X_test = df_test[features].values
all_data = pd.merge(all_data, match_data)
 del match_data
gc.collect()
all_data['enemy.players'] = all_data['m.players'] - all_data['players']
for c in sum_col:
all_data['enemy.' + c] =(all_data['m.sum.' + c] - all_data['sum.' + c])/ all_data['enemy.players']
all_data['p.max_msum.' + c] = all_data['max.' + c] / all_data['m.sum.' + c]
all_data['p.max_mmax.' + c] = all_data['max.' + c] / all_data['m.max.' + c]
all_data.drop(['m.sum.' + c, 'm.max.' + c], axis=1, inplace=True)
 fillInf(all_data, 0)
 print(all_data.shape )<feature_engineering>
for fold,(trn_idx, val_idx)in enumerate(skf.split(df_train, df_train['target'])) :
X_train, y_train = df_train.iloc[trn_idx][features], df_train.iloc[trn_idx]['target']
X_valid, y_valid = df_train.iloc[val_idx][features], df_train.iloc[val_idx]['target']
N = 5
p_valid,yp = 0,0
for i in range(N):
X_t, y_t = augment(X_train.values, y_train.values)
 X_t = pd.DataFrame(X_t)
 X_t = X_t.add_prefix('var_')
 trn_data = lgb.Dataset(X_t, label=y_t)
 val_data = lgb.Dataset(X_valid, label=y_valid)
 evals_result = {}
lgb_clf = lgb.train(lgb_params,
trn_data,
100000,
valid_sets = [trn_data, val_data],
early_stopping_rounds=3000,
verbose_eval = 1000,
evals_result=evals_result 
)
 p_valid += lgb_clf.predict(X_valid)
 yp += lgb_clf.predict(X_test)
 fold_importance_df = pd.DataFrame()
fold_importance_df["feature"] = features
fold_importance_df["importance"] = lgb_clf.feature_importance()
fold_importance_df["fold"] = fold + 1
feature_importance_df = pd.concat([feature_importance_df, fold_importance_df], axis=0)
 oof['predict'][val_idx] = p_valid/N
val_score = roc_auc_score(y_valid, p_valid)
 val_aucs.append(val_score)
 predictions['fold{}'.format(fold+1)] = yp/N
match = all_data.groupby('matchId')
 matchRank = match[numcols].rank(pct=True ).rename(columns=lambda s: 'rank.' + s)
 all_data = reduce_mem_usage(pd.concat([all_data, matchRank], axis=1))
rank_col = matchRank.columns
del matchRank
gc.collect()
match = all_data.groupby('matchId')
 matchRank = match[rank_col].max().rename(columns=lambda s: 'max.' + s ).reset_index()
all_data = pd.merge(all_data, matchRank)
 for c in numcols:
all_data['rank.' + c] = all_data['rank.' + c] / all_data['max.rank.' + c]
all_data.drop(['max.rank.' + c], axis=1, inplace=True)
 del matchRank
gc.collect()
print(all_data.shape )<merge>
mean_auc = np.mean(val_aucs)
 std_auc = np.std(val_aucs)
 all_auc = roc_auc_score(oof['target'], oof['predict'])
 print("Mean auc: %.9f, std: %.9f.All auc: %.9f." %(mean_auc, std_auc, all_auc))
killMinorRank = all_data[['matchId','min.kills','max.killPlace']].copy()
group = killMinorRank.groupby(['matchId','min.kills'])
 killMinorRank['rank.minor.maxKillPlace'] = group.rank(pct=True ).values
all_data = pd.merge(all_data, killMinorRank)
 killMinorRank = all_data[['matchId','max.kills','min.killPlace']].copy()
group = killMinorRank.groupby(['matchId','max.kills'])
 killMinorRank['rank.minor.minKillPlace'] = group.rank(pct=True ).values
all_data = pd.merge(all_data, killMinorRank)
 del killMinorRank
gc.collect()<count_unique_values>
predictions['target'] = np.mean(predictions[[col for col in predictions.columns if col not in ['ID_code', 'target']]].values, axis=1)
 predictions.to_csv('lgb_all_predictions.csv', index=None)
 sub_df = pd.DataFrame({"ID_code":df_test["ID_code"].values})
 sub_df["target"] = predictions['target']
sub_df.to_csv("lgb_submission.csv", index=False)
 oof.to_csv('lgb_oof.csv', index=False )