Kaggle competition: University of Liverpool - Ion Switching
<SOS> metric: MacroFScore Kaggle data source: university-of-liverpool-ion-switching<drop_column>
sns.set_style("whitegrid")
 ROW_PER_BATCH = 500000
df1.drop('Cabin',axis=1,inplace=True)
 df2.drop('Cabin',axis=1,inplace=True )<feature_engineering>
train = pd.read_csv('/kaggle/input/liverpool-ion-switching/train.csv')
 test = pd.read_csv('/kaggle/input/liverpool-ion-switching/test.csv')
 print('Shape of train is ',train.shape)
 print('Shape of test is ',test.shape )
df1['Age']=np.where(df1['Age']<18,'child','Adult')
 df2['Age']=np.where(df2['Age']<18,'child','Adult' )<feature_engineering>
train['batch'] = 0
for i in range(0, train.shape[0]//ROW_PER_BATCH):
train.iloc[i * ROW_PER_BATCH:(i+1)* ROW_PER_BATCH,3] = i
df1['Fare']=np.where(df1['Fare']<80,'low_cost','High_cost')
 df2['Fare']=np.where(df2['Fare']<80,'low_cost','High_cost' )<save_to_csv>
test['batch'] = 0
for i in range(0, test.shape[0]//ROW_PER_BATCH):
test.iloc[i * ROW_PER_BATCH:(i+1)* ROW_PER_BATCH,2] = i
y = df1["Survived"]
features = ["Pclass","Sex","Age","Fare","family_members","Cabin_Alotted"]
X = pd.get_dummies(df1[features])
 X_test = pd.get_dummies(df2[features])
 model = RandomForestClassifier(n_estimators=100, max_depth=5, random_state=1)
 model.fit(X, y)
 predictions = model.predict(X_test)
 output = pd.DataFrame({'PassengerId': df2.PassengerId, 'Survived': predictions})
 output.to_csv('my_submission.csv', index=False)
 print("Your submission was successfully saved!" )<load_from_csv>
train['type'] = 0
for i in range(train['batch'].nunique()):
median = train.iloc[i*ROW_PER_BATCH :(i+1)* ROW_PER_BATCH].signal.median()
if(median < 0):
train.iloc[i*ROW_PER_BATCH :(i+1)* ROW_PER_BATCH, train.columns.get_loc('type')] = 0
else:
train.iloc[i*ROW_PER_BATCH :(i+1)* ROW_PER_BATCH, train.columns.get_loc('type')] = 1
test['type'] = 0
ROW_PER_BATCH = 100000
for i in range(test['batch'].nunique()):
median = test.iloc[i*ROW_PER_BATCH :(i+1)*ROW_PER_BATCH].signal.median()
if(median < 0):
test.iloc[i*ROW_PER_BATCH :(i+1)* ROW_PER_BATCH, test.columns.get_loc('type')] = 0
else:
test.iloc[i*ROW_PER_BATCH :(i+1)* ROW_PER_BATCH, test.columns.get_loc('type')] = 1
train_data = pd.read_csv("/kaggle/input/titanic/train.csv")
 test_data = pd.read_csv("/kaggle/input/titanic/test.csv" )<count_missing_values>
a = 500000; b = a *2
print('Before: mean: {} std: {} median: {}'.format(train.signal[a:b].mean() , train.signal[a:b].std() ,train.signal[a:b].median()))
a=500000; b=600000
train['signal_undrifted'] = train.signal
train.loc[train.index[a:b],'signal_undrifted'] = train.signal[a:b].values - 3*(train.time.values[a:b] - 50)/10.
 a = 500000; b = a *2
print('After: mean: {} std: {} median: {}'.format(train.signal_undrifted[a:b].mean() , train.signal_undrifted[a:b].std() ,train.signal_undrifted[a:b].median()))
train_data.isna().sum()<drop_column>
def f(x,low,high,mid): return -(( -low+high)/625)*(x-mid)**2+high -low
batch = 7; a = 500000*(batch-1); b = 500000*batch
train.loc[train.index[a:b],'signal_undrifted'] = train.signal.values[a:b] - f(train.time[a:b].values,-1.817,3.186,325)
 batch = 8; a = 500000*(batch-1); b = 500000*batch
train.loc[train.index[a:b],'signal_undrifted'] = train.signal.values[a:b] - f(train.time[a:b].values,-0.094,4.936,375)
 batch = 9; a = 500000*(batch-1); b = 500000*batch
train.loc[train.index[a:b],'signal_undrifted'] = train.signal.values[a:b] - f(train.time[a:b].values,1.715,6.689,425)
 batch = 10; a = 500000*(batch-1); b = 500000*batch
train.loc[train.index[a:b],'signal_undrifted'] = train.signal.values[a:b] - f(train.time[a:b].values,3.361,8.45,475 )
train_data = train_data.drop(labels=["Cabin"], axis="columns")
 test_data = test_data.drop(labels=["Cabin"], axis="columns" )<feature_engineering>
test['signal_undrifted'] = test.signal
start=500
a = 0; b = 100000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - 3*(test.time.values[a:b]-start)/10.
 start=510
a = 100000; b = 200000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - 3*(test.time.values[a:b]-start)/10.
 start=540
a = 400000; b = 500000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - 3*(test.time.values[a:b]-start)/10.
 start=560
a = 600000; b = 700000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - 3*(test.time.values[a:b]-start)/10.
 start=570
a = 700000; b = 800000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - 3*(test.time.values[a:b]-start)/10.
 start=580
a = 800000; b = 900000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - 3*(test.time.values[a:b]-start)/10.
 def f(x):
return -(0.00788)*(x-625)**2+2.345 +2.58
a = 1000000; b = 1500000
test.loc[test.index[a:b],'signal_undrifted'] = test.signal.values[a:b] - f(test.time[a:b].values )
train_data["Age"] = train_data["Age"].fillna(28)
 test_data["Age"] = test_data["Age"].fillna(28 )<count_missing_values>
%%time
def features(df):
df = df.sort_values(by=['time'] ).reset_index(drop=True)
 df.index =(( df.time * 10_000)- 1 ).values
df['batch'] = df.index // 50_000
df['batch_index'] = df.index -(df.batch * 50_000)
 df['batch_slices'] = df['batch_index'] // 5_000
df['batch_slices2'] = df.apply(lambda r: '_'.join([str(r['batch'] ).zfill(3), str(r['batch_slices'] ).zfill(3)]), axis=1)
 for c in ['batch','batch_slices2']:
d = {}
d['mean'+c] = df.groupby([c])['signal_undrifted'].mean()
d['median'+c] = df.groupby([c])['signal_undrifted'].median()
d['max'+c] = df.groupby([c])['signal_undrifted'].max()
d['min'+c] = df.groupby([c])['signal_undrifted'].min()
d['std'+c] = df.groupby([c])['signal_undrifted'].std()
d['mean_abs_chg'+c] = df.groupby([c])['signal_undrifted'].apply(lambda x: np.mean(np.abs(np.diff(x))))
d['abs_max'+c] = df.groupby([c])['signal_undrifted'].apply(lambda x: np.max(np.abs(x)))
 d['abs_min'+c] = df.groupby([c])['signal_undrifted'].apply(lambda x: np.min(np.abs(x)))
 for v in d:
df[v] = df[c].map(d[v].to_dict())
 df['range'+c] = df['max'+c] - df['min'+c]
df['maxtomin'+c] = df['max'+c] / df['min'+c]
df['abs_avg'+c] =(df['abs_min'+c] + df['abs_max'+c])/ 2
df['signal_shift_+1'] = [0,] + list(df['signal_undrifted'].values[:-1])
 df['signal_shift_-1'] = list(df['signal_undrifted'].values[1:])+ [0]
for i in df[df['batch_index']==0].index:
df['signal_shift_+1'][i] = np.nan
for i in df[df['batch_index']==49999].index:
df['signal_shift_-1'][i] = np.nan
df['signal_shift_+2'] = [0,] + [1,] + list(df['signal_undrifted'].values[:-2])
 df['signal_shift_-2'] = list(df['signal_undrifted'].values[2:])+ [0] + [1]
for i in df[df['batch_index']==0].index:
df['signal_shift_+2'][i] = np.nan
for i in df[df['batch_index']==1].index:
df['signal_shift_+2'][i] = np.nan
for i in df[df['batch_index']==49999].index:
df['signal_shift_-2'][i] = np.nan
for i in df[df['batch_index']==49998].index:
df['signal_shift_-2'][i] = np.nan
for c in [c1 for c1 in df.columns if c1 not in ['time', 'signal_undrifted', 'open_channels', 'batch', 'batch_index', 'batch_slices', 'batch_slices2']]:
df[c+'_msignal'] = df[c] - df['signal_undrifted']
return df
train = features(train)
 test = features(test )
test_data.isna().sum()<feature_engineering>
def f1_score_calc(y_true, y_pred):
return f1_score(y_true, y_pred, average="macro")
 def lgb_Metric(preds, dtrain):
labels = dtrain.get_label()
preds = np.round(np.clip(preds, 0, 10)).astype(int)
 score = f1_score(labels, preds, average="macro")
 return('KaggleMetric', score, True)
 def train_model_classification(X, X_test, y, params, model_type='lgb', eval_metric='f1score',
columns=None, plot_feature_importance=False, model=None,
verbose=50, early_stopping_rounds=200, n_estimators=2000):
columns = X.columns if columns == None else columns
X_test = X_test[columns]
metrics_dict = {
'f1score': {'lgb_metric_name': lgb_Metric,}
}
result_dict = {}
oof = np.zeros(len(X))
prediction = np.zeros(( len(X_test)))
 scores = []
feature_importance = pd.DataFrame()

 if True:
X_train, X_valid, y_train, y_valid = model_selection.train_test_split(X, y, test_size=0.3, random_state=7)
 if model_type == 'lgb':
model = lgb.train(params, lgb.Dataset(X_train, y_train),
n_estimators, lgb.Dataset(X_valid, y_valid),
verbose_eval=verbose, early_stopping_rounds=early_stopping_rounds, feval=lgb_Metric)
 preds = model.predict(X, num_iteration=model.best_iteration)
 y_pred = model.predict(X_test, num_iteration=model.best_iteration)
 if model_type == 'xgb':
train_set = xgb.DMatrix(X_train, y_train)
 val_set = xgb.DMatrix(X_valid, y_valid)
 model = xgb.train(params, train_set, num_boost_round=2222, evals=[(train_set, 'train'),(val_set, 'val')],
verbose_eval=verbose, early_stopping_rounds=early_stopping_rounds)
 preds = model.predict(xgb.DMatrix(X))
y_pred = model.predict(xgb.DMatrix(X_test))
if model_type == 'cat':
model = CatBoostRegressor(params)
 model.fit(X_train, y_train)
 y_pred_valid = np.round(np.clip(preds, 0, 10)).astype(int)
 y_pred = model.predict(X_test, num_iteration=model.best_iteration)
 y_pred = np.round(np.clip(y_pred, 0, 10)).astype(int)
 oof = preds
scores.append(f1_score_calc(y, np.round(np.clip(preds,0,10)).astype(int)))
 prediction += y_pred
if model_type == 'lgb' and plot_feature_importance:
fold_importance = pd.DataFrame()
fold_importance["feature"] = columns
fold_importance["importance"] = model.feature_importances_
fold_importance["fold"] = fold_n + 1
feature_importance = pd.concat([feature_importance, fold_importance], axis=0)
 print('FINAL score: {0:.4f}, std: {1:.4f}.'.format(np.mean(scores), np.std(scores)))
 result_dict['oof'] = oof
result_dict['prediction'] = prediction
result_dict['scores'] = scores
result_dict['model'] = model
if model_type == 'lgb':
if plot_feature_importance:
feature_importance["importance"] /= folds.n_splits
cols = feature_importance[["feature", "importance"]].groupby("feature" ).mean().sort_values(
 by="importance", ascending=False)[:50].index
best_features = feature_importance.loc[feature_importance.feature.isin(cols)]
plt.figure(figsize=(16, 12)) ;
sns.barplot(x="importance", y="feature", data=best_features.sort_values(by="importance", ascending=False)) ;
plt.title('LGB Features(avg over folds)');
result_dict['feature_importance'] = feature_importance
return result_dict
test_data["Fare"] = test_data["Fare"].fillna(14.454200 )<categorify>
good_columns = [c for c in train.columns if c not in ['time', 'signal','open_channels', 'batch', 'batch_index', 'batch_slices', 'batch_slices2']]
X = train[good_columns].copy()
y = train['open_channels']
X_test = test[good_columns].copy()
label_encoder = LabelEncoder()
train_data["Sex"] = label_encoder.fit_transform(train_data["Sex"])
 test_data["Sex"] = label_encoder.fit_transform(test_data["Sex"] )<data_type_conversions>
del train, test
train_data["Embarked"] = train_data["Embarked"].fillna("X")
 test_data["Embarked"] = test_data["Embarked"].fillna("X" )<categorify>
params_xgb = {'colsample_bytree': 0.375,'learning_rate': 0.1,'max_depth': 10, 'subsample': 1, 'objective':'reg:squarederror',
'eval_metric':'rmse'}
result_dict_xgb = train_model_classification(X=X[0:500000*8-1], X_test=X_test, y=y[0:500000*8-1], params=params_xgb, model_type='xgb', eval_metric='f1score', plot_feature_importance=False,
verbose=50, early_stopping_rounds=250 )
train_data["Embarked"] = label_encoder.fit_transform(train_data["Embarked"])
 test_data["Embarked"] = label_encoder.fit_transform(test_data["Embarked"] )<feature_engineering>
params_lgb = {'learning_rate': 0.1, 'max_depth': 7, 'num_leaves':2**7+1, 'metric': 'rmse', 'random_state': 7, 'n_jobs':-1}
result_dict_lgb = train_model_classification(X=X[0:500000*8-1], X_test=X_test, y=y[0:500000*8-1], params=params_lgb, model_type='lgb', eval_metric='f1score', plot_feature_importance=False,
verbose=50, early_stopping_rounds=250, n_estimators=3000 )
Ticket1 = []
for i in list(train_data.Ticket):
if not i.isdigit() :
Ticket1.append(i.replace(".","" ).replace("/","" ).strip().split(' ')[0])
 else:
Ticket1.append("X")
 train_data["Ticket"] = Ticket1
Ticket2 = []
for j in list(test_data.Ticket):
if not j.isdigit() :
Ticket2.append(j.replace(".","" ).replace("/","" ).strip().split(' ')[0])
 else:
Ticket2.append("X")
 test_data["Ticket"] = Ticket2<define_variables>
def weight_opt(oof_lgb, oof_xgb, y_true):
weight_lgb = np.inf
best_f1 = np.inf
for i in np.arange(0, 1.01, 0.10):
combined_oof = i * oof_lgb +(1-i)* oof_xgb
blend = np.round(np.clip(combined_oof,0,10)).astype(int)
 f1_blend = metrics.f1_score(y_true, blend, average = 'macro')
 if np.mean(f1_blend)< best_f1:
best_f1 = np.mean(f1_blend)
 weight_lgb = round(i, 2)
 print(str(round(i, 2)) + ' : mean F1(Blend)is ', round(np.mean(f1_blend), 6))
print('-'*36)
 print('Best weight for LGB: ', weight_lgb)
 print('Best weight for XGB: ', round(1-weight_lgb, 2))
print('Best mean F1(Blend): ', round(best_f1, 6))
return weight_lgb, round(1-weight_lgb, 2 )
unique1 = ["Ticket_" + s for s in unique1]
unique2 = ["Ticket_" + s for s in unique2]<categorify>
weight_lgb, weight_xgb = weight_opt(result_dict_lgb['oof'], result_dict_xgb['oof'], y[0:500000*8-1] )
train_data = pd.get_dummies(train_data, columns = ["Ticket"])
 test_data = pd.get_dummies(test_data, columns = ["Ticket"] )<drop_column>
preds_ensemble = 0.50 * result_dict_lgb['prediction'] + 0.50 * result_dict_xgb['prediction']
train_data = train_data.drop(labels = unique1 , axis = "columns")
 test_data = test_data.drop(labels = unique2 , axis = "columns" )<feature_engineering>
sub = pd.read_csv('/kaggle/input/liverpool-ion-switching/sample_submission.csv')
 sub['open_channels'] = np.array(np.round(preds_ensemble,0), np.int)
 sub.to_csv('submission_unshifted_70p.csv', index=False, float_format='%.4f')
 sub.head(10 )