Kaggle competition: Tabular Playground Series - Feb 2021
user_lecture_agg = train_df.groupby('user_id')['content_type_id'].agg(['sum', 'count'])
 user_lecture_agg=user_lecture_agg.astype('int16' )<data_type_conversions>
BASE = ".. /input/tabular-playground-series-feb-2021"
Test = pd.read_csv(BASE + '/test.csv')
 train = pd.read_csv(BASE + '/train.csv')
 sample_sub = pd.read_csv(BASE + '/sample_submission.csv' )
cum = train_df.groupby('user_id')['content_type_id'].agg(['cumsum', 'cumcount'])
 cum['cumcount']=cum['cumcount']+1
train_df['user_interaction_count'] = cum['cumcount']
train_df['user_interaction_timestamp_mean'] = train_df['timestamp']/cum['cumcount']
train_df['user_lecture_sum'] = cum['cumsum']
train_df['user_lecture_lv'] = cum['cumsum'] / cum['cumcount']
train_df.user_lecture_lv=train_df.user_lecture_lv.astype('float16')
 train_df.user_lecture_sum=train_df.user_lecture_sum.astype('int16')
 train_df.user_interaction_count=train_df.user_interaction_count.astype('int16')
 train_df['user_interaction_timestamp_mean']=train_df['user_interaction_timestamp_mean']/(1000*3600)
 train_df.user_interaction_timestamp_mean=train_df.user_interaction_timestamp_mean.astype('float32')
<set_options>
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
del cum
gc.collect()<train_model>
sns.set_theme()
print('start handle train_df...' )<data_type_conversions>
print('Rows and Columns in train dataset:', sum(train.isnull().sum()))
print('Rows and Columns in test dataset:', sum(Test.isnull().sum()))
train_df['prior_question_had_explanation'].fillna(False, inplace=True)
 train_df = train_df.astype(data_types_dict)
 train_df = train_df[train_df[target] != -1].reset_index(drop=True )<groupby>
cat_features = [feature for feature in train.columns if 'cat' in feature]
cont_features = [feature for feature in train.columns if 'cont' in feature]
content_explation_agg=train_df[["content_id","prior_question_had_explanation",target]].groupby(["content_id","prior_question_had_explanation"])[target].agg(['mean'] )<rename_columns>
warnings.filterwarnings('ignore')
content_explation_agg=content_explation_agg.unstack()
content_explation_agg=content_explation_agg.reset_index()
content_explation_agg.columns = ['content_id', 'content_explation_false_mean','content_explation_true_mean']<data_type_conversions>
Count_diagram(train )
content_explation_agg.content_id=content_explation_agg.content_id.astype('int16')
 content_explation_agg.content_explation_false_mean=content_explation_agg.content_explation_false_mean.astype('float16')
 content_explation_agg.content_explation_true_mean=content_explation_agg.content_explation_true_mean.astype('float16' )<train_model>
Count_diagram(Test )
print('start handle attempt_no...' )<data_type_conversions>
shap.initjs()
train_df["attempt_no"] = 1
train_df.attempt_no=train_df.attempt_no.astype('int8')
 attempt_no_agg=train_df.groupby(["user_id","content_id"])["attempt_no"].agg(['sum'] ).astype('int8')
 train_df["attempt_no"] = train_df[["user_id","content_id",'attempt_no']].groupby(["user_id","content_id"])["attempt_no"].cumsum()<data_type_conversions>
target = train['target'].values
print('start handle timestamp...')
 prior_question_elapsed_time_mean=train_df['prior_question_elapsed_time'].mean()
train_df['prior_question_elapsed_time'].fillna(prior_question_elapsed_time_mean, inplace=True )<data_type_conversions>
for feature in cat_features:
le = LabelEncoder()
le.fit(train[feature])
 train[feature] = le.transform(train[feature])
 Test[feature] = le.transform(Test[feature] )
max_timestamp_u = train_df[['user_id','timestamp']].groupby(['user_id'] ).agg(['max'] ).reset_index()
max_timestamp_u.columns = ['user_id', 'max_time_stamp']
max_timestamp_u.user_id=max_timestamp_u.user_id.astype('int32' )<data_type_conversions>
!pip install --upgrade xgboost
xgb.__version__
train_df['lagtime'] = train_df.groupby('user_id')['timestamp'].shift()
max_timestamp_u2 = train_df[['user_id','lagtime']].groupby(['user_id'] ).agg(['max'] ).reset_index()
max_timestamp_u2.columns = ['user_id', 'max_time_stamp2']
max_timestamp_u2.user_id=max_timestamp_u2.user_id.astype('int32' )<feature_engineering>
xgb_params= {
"objective": "reg:squarederror",
"max_depth": 6,
"learning_rate": 0.01,
"colsample_bytree": 0.4,
"subsample": 0.6,
"reg_alpha" : 6,
"min_child_weight": 100,
"n_jobs": 2,
"seed": 2001,
'tree_method': "gpu_hist",
"gpu_id": 0,
}
train_df['lagtime']=train_df['timestamp']-train_df['lagtime']
lagtime_mean=train_df['lagtime'].mean()
train_df['lagtime'].fillna(lagtime_mean, inplace=True )<data_type_conversions>
train_oof = np.zeros(( 300000,))
test_preds = 0
train_oof.shape
train_df['lagtime']=train_df['lagtime']/(1000*3600)
 train_df.lagtime=train_df.lagtime.astype('float32' )<data_type_conversions>
Test = xgb.DMatrix(Test[columns] )
<data_type_conversions>
NUM_FOLDS = 10
kf = KFold(n_splits=NUM_FOLDS, shuffle=True, random_state=0)
 for f,(train_ind, val_ind)in tqdm(enumerate(kf.split(train, target))):
train_df, val_df = train.iloc[train_ind][columns], train.iloc[val_ind][columns]
train_target, val_target = target[train_ind], target[val_ind]
train_df = xgb.DMatrix(train_df, label=train_target)
 val_df = xgb.DMatrix(val_df, label=val_target)
 model = xgb.train(xgb_params, train_df, 3600)
 temp_oof = model.predict(val_df)
 temp_test = model.predict(Test)
 train_oof[val_ind] = temp_oof
test_preds += temp_test/NUM_FOLDS
print(mean_squared_error(temp_oof, val_target, squared=False))
train_df['lagtime2'] = train_df.groupby('user_id')['timestamp'].shift(2)
 max_timestamp_u3 = train_df[['user_id','lagtime2']].groupby(['user_id'] ).agg(['max'] ).reset_index()
max_timestamp_u3.columns = ['user_id', 'max_time_stamp3']
max_timestamp_u3.user_id=max_timestamp_u3.user_id.astype('int32')
 train_df['lagtime2']=train_df['timestamp']-train_df['lagtime2']
lagtime_mean2=train_df['lagtime2'].mean()
train_df['lagtime2'].fillna(lagtime_mean2, inplace=True)
<data_type_conversions>
mean_squared_error(train_oof, target, squared=False )
train_df['lagtime2']=train_df['lagtime2']/(1000*3600)
 train_df.lagtime2=train_df.lagtime2.astype('float32' )<data_type_conversions>
np.save('train_oof', train_oof)
 np.save('test_preds', test_preds )
train_df['lagtime3'] = train_df.groupby('user_id')['timestamp'].shift(3)
 train_df['lagtime3']=train_df['timestamp']-train_df['lagtime3']
lagtime_mean3=train_df['lagtime3'].mean()
train_df['lagtime3'].fillna(lagtime_mean3, inplace=True)
 train_df['lagtime3']=train_df['lagtime3']/(1000*3600)
 train_df.lagtime3=train_df.lagtime3.astype('float32' )<data_type_conversions>
%%time
shap_preds = model.predict(test, pred_contribs=True )
<data_type_conversions>
train = pd.read_csv('.. /input/tabular-playground-series-feb-2021/train.csv')
 test = pd.read_csv('.. /input/tabular-playground-series-feb-2021/test.csv')
 for feature in cat_features:
le = LabelEncoder()
le.fit(train[feature])
 train[feature] = le.transform(train[feature])
 test[feature] = le.transform(test[feature] )
<feature_engineering><EOS> 
sample_sub['target'] = test_preds
sample_sub.to_csv('submission.csv', index=False )