Kaggle competition: Mechanisms of Action (MoA) Prediction
ds = get_dataset(files_test, CFG, augment=False, repeat=False,
labeled=False, return_image_names=True)
 image_names = np.array([img_name.numpy().decode("utf-8")
 for img, img_name in iter(ds.unbatch())] )<save_to_csv>
warnings.filterwarnings('ignore' )
for i in range(CFG["net_count"]):
submission = pd.DataFrame(dict(
 image_name = image_names,
target = probs[i,:,0]))
submission = submission.sort_values('image_name')
 submission.to_csv(f'submission_model_{i}.csv', index=False )<save_to_csv>
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' )
submission = pd.DataFrame(dict(
 image_name = image_names,
target = np.mean(probs[:,:,0], axis=0)))
 submission = submission.sort_values('image_name')
 submission.to_csv('submission_models_blended.csv', index=False )<define_variables>
def preprocess(df):
df = df.copy()
df.loc[:, 'cp_type'] = df.loc[:, 'cp_type'].map({'trt_cp': 0, 'ctl_vehicle': 1})
 df.loc[:, 'cp_dose'] = df.loc[:, 'cp_dose'].map({'D1': 0, 'D2': 1})
 del df['sig_id']
return df
train = preprocess(train_features)
 test = preprocess(test_features)
 del train_targets['sig_id']
train_targets = train_targets.loc[train['cp_type']==0].reset_index(drop=True)
 train = train.loc[train['cp_type']==0].reset_index(drop=True )
train_pickle = '.. /input/riiid-cross-validation-files/cv1_train.pickle'
valid_pickle = '.. /input/riiid-cross-validation-files/cv1_valid.pickle'
question_file= '.. /input/riiid-test-answer-prediction/questions.csv'
contents_feat_file= '.. /input/riiid-offline-features/content_feats.pkl'
parts_feat_file = '.. /input/riiid-offline-features/part_feats.pkl'
question_tags_file='.. /input/riiid-offline-features/question_tags_feat.csv'
isDebug = False
feature_engineering_rows = 4000000 if isDebug else 40000000
training_rows = 150000 if isDebug else 10000000
print(f'Number of rows for feature engineering: {str(feature_engineering_rows)}')
 print(f'Number of rows for training: {str(training_rows)}')
 question_tags_df_dtypes = {
'question_id': np.int64,
'tags_lsi': np.int8,
'tag_acc_max': np.float16,
'tag_count': np.int8,
'tag_acc_min': np.float16
}<feature_engineering>
def set_seed(seed):
torch.manual_seed(seed)
 torch.backends.cudnn.deterministic = True
torch.backends.cudnn.benchmark = False
np.random.seed(seed )
SEED = 123
def seed_everything(seed):
random.seed(seed)
 np.random.seed(seed)
 os.environ['PYTHONHASHSEED'] = str(seed)
 seed_everything(SEED)
 def add_features(
 df, answered_correctly_u_count, answered_correctly_u_sum,
elapsed_time_u_sum, explanation_u_sum, timestamp_u, timestamp_u_incorrect,
answered_correctly_q_count, answered_correctly_q_sum, elapsed_time_q_sum,
explanation_q_sum, answered_correctly_uq, part_user_count, part_user_sum,
answered_correctly_ut, answered_correctly_ut_sum,
update=True 
):
answered_correctly_u_avg = np.zeros(len(df), dtype = np.float16)
 elapsed_time_u_avg = np.zeros(len(df), dtype = np.float16)
 explanation_u_avg = np.zeros(len(df), dtype = np.float16)
 timestamp_u_recency_1 = np.zeros(len(df), dtype = np.float16)
 timestamp_u_recency_2 = np.zeros(len(df), dtype = np.float16)
 timestamp_u_recency_3 = np.zeros(len(df), dtype = np.float16)
 timestamp_u_incorrect_recency = np.zeros(len(df), dtype = np.float16)
 answered_correctly_q_avg = np.zeros(len(df), dtype = np.float16)
 elapsed_time_q_avg = np.zeros(len(df), dtype = np.float16)
 explanation_q_avg = np.zeros(len(df), dtype = np.float16)
 answered_correctly_uq_count = np.zeros(len(df), dtype = np.int16)
 part_u_count= np.zeros(len(df), dtype = np.int32)
 part_u_mean = np.zeros(len(df), dtype = np.float16)
 answered_correctly_ut_count = np.zeros(len(df), dtype = np.int16)
 answered_correctly_ut_avg_max = np.zeros(len(df), dtype = np.float16)
 answered_correctly_ut_avg_min = np.zeros(len(df), dtype = np.float16)
 for num, row in enumerate(zip(*df[[
'user_id', 'answered_correctly', 'content_id', 'prior_question_elapsed_time',
'prior_question_had_explanation', 'timestamp', 'part', 'tags'
]].to_dict("list" ).values())) :
if answered_correctly_u_count[row[0]] != 0:
answered_correctly_u_avg[num] = answered_correctly_u_sum[row[0]] / answered_correctly_u_count[row[0]]
elapsed_time_u_avg[num] = elapsed_time_u_sum[row[0]] / answered_correctly_u_count[row[0]]
explanation_u_avg[num] = explanation_u_sum[row[0]] / answered_correctly_u_count[row[0]]
else:
answered_correctly_u_avg[num] =.637
elapsed_time_u_avg[num] = np.nan
explanation_u_avg[num] = np.nan
if len(timestamp_u[row[0]])== 0:
timestamp_u_recency_1[num] = np.nan
timestamp_u_recency_2[num] = np.nan
timestamp_u_recency_3[num] = np.nan
elif len(timestamp_u[row[0]])== 1:
timestamp_u_recency_1[num] = row[5] - timestamp_u[row[0]][0]
timestamp_u_recency_2[num] = np.nan
timestamp_u_recency_3[num] = np.nan
elif len(timestamp_u[row[0]])== 2:
timestamp_u_recency_1[num] = row[5] - timestamp_u[row[0]][1]
timestamp_u_recency_2[num] = row[5] - timestamp_u[row[0]][0]
timestamp_u_recency_3[num] = np.nan
elif len(timestamp_u[row[0]])== 3:
timestamp_u_recency_1[num] = row[5] - timestamp_u[row[0]][2]
timestamp_u_recency_2[num] = row[5] - timestamp_u[row[0]][1]
timestamp_u_recency_3[num] = row[5] - timestamp_u[row[0]][0]
if len(timestamp_u_incorrect[row[0]])== 0:
timestamp_u_incorrect_recency[num] = np.nan
else:
timestamp_u_incorrect_recency[num] = row[5] - timestamp_u_incorrect[row[0]][0]
if answered_correctly_q_count[row[2]] != 0:
answered_correctly_q_avg[num] = answered_correctly_q_sum[row[2]] / answered_correctly_q_count[row[2]]
elapsed_time_q_avg[num] = elapsed_time_q_sum[row[2]] / answered_correctly_q_count[row[2]]
explanation_q_avg[num] = explanation_q_sum[row[2]] / answered_correctly_q_count[row[2]]
else:
answered_correctly_q_avg[num] = np.nan
elapsed_time_q_avg[num] = np.nan
explanation_q_avg[num] = np.nan
answered_correctly_uq_count[num] = answered_correctly_uq[row[0]][row[2]]
if part_user_count[row[0]][row[6]]==0:
part_u_count[num] = 0
part_u_mean[num] =.637
else:
part_u_count[num] = part_user_count[row[0]][row[6]]
part_u_mean[num] = part_user_sum[row[0]][row[6]]/part_user_count[row[0]][row[6]]
tags = row[7].split()
tag_user_mean = []
for tag in tags:
tag_user_count = answered_correctly_ut[row[0]][tag]
tag_user_sum = answered_correctly_ut_sum[row[0]][tag]
if tag_user_count == 0:
tag_user_mean.append (.637)
 else:
tag_user_mean.append(tag_user_sum / tag_user_count)
 answered_correctly_ut_count[num] += tag_user_count
answered_correctly_ut_avg_max[num] = max(tag_user_mean)
 answered_correctly_ut_avg_min[num] = min(tag_user_mean)
 answered_correctly_u_count[row[0]] += 1
elapsed_time_u_sum[row[0]] += row[3]
explanation_u_sum[row[0]] += int(row[4])
 if len(timestamp_u[row[0]])== 3:
timestamp_u[row[0]].pop(0)
 timestamp_u[row[0]].append(row[5])
 else:
timestamp_u[row[0]].append(row[5])
 answered_correctly_q_count[row[2]] += 1
elapsed_time_q_sum[row[2]] += row[3]
explanation_q_sum[row[2]] += int(row[4])
 answered_correctly_uq[row[0]][row[2]] += 1
part_user_count[row[0]][row[6]] += 1
for tag in tags:
answered_correctly_ut[row[0]][tag] += 1
if update:
answered_correctly_u_sum[row[0]] += row[1]
if row[1] == 0:
if len(timestamp_u_incorrect[row[0]])== 1:
timestamp_u_incorrect[row[0]].pop(0)
 timestamp_u_incorrect[row[0]].append(row[5])
 else:
timestamp_u_incorrect[row[0]].append(row[5])
 answered_correctly_q_sum[row[2]] += row[1]
part_user_sum[row[0]][row[6]] += row[1]
for tag in tags:
answered_correctly_ut_sum[row[0]][tag] += row[1]
user_dict = {
'answered_correctly_u_avg': answered_correctly_u_avg,
'elapsed_time_u_avg': elapsed_time_u_avg,
'explanation_u_avg': explanation_u_avg,
'answered_correctly_q_avg': answered_correctly_q_avg,
'elapsed_time_q_avg': elapsed_time_q_avg,
'explanation_q_avg': explanation_q_avg,
'answered_correctly_uq_count': answered_correctly_uq_count,
'timestamp_u_recency_1': timestamp_u_recency_1,
'timestamp_u_recency_2': timestamp_u_recency_2,
'timestamp_u_recency_3': timestamp_u_recency_3,
'timestamp_u_incorrect_recency': timestamp_u_incorrect_recency,
'part_u_count': part_u_count,
'part_u_mean': part_u_mean,
'answered_correctly_ut_count': answered_correctly_ut_count,
'answered_correctly_ut_avg_max': answered_correctly_ut_avg_max,
'answered_correctly_ut_avg_min': answered_correctly_ut_avg_min,
}
for k, v in user_dict.items() :
df[k] = v
return df
def update_features(
 df, answered_correctly_u_sum, answered_correctly_q_sum, timestamp_u_incorrect,
part_user_sum, answered_correctly_ut_sum 
):
for row in df[[
'user_id', 'answered_correctly', 'content_id', 'content_type_id', 'timestamp', 'part', 'tags'
]].values:
if row[3] == 0:
answered_correctly_u_sum[row[0]] += row[1]
if row[1] == 0:
if len(timestamp_u_incorrect[row[0]])== 1:
timestamp_u_incorrect[row[0]].pop(0)
 timestamp_u_incorrect[row[0]].append(row[4])
 else:
timestamp_u_incorrect[row[0]].append(row[4])
 answered_correctly_q_sum[row[2]] += row[1]
part_user_sum[row[0]][row[5]] += row[1]
tags = row[6].split()
for tag in tags:
answered_correctly_ut_sum[row[0]][tag] += row[1]
return
def defaultdictInt() :
return defaultdict(int)
 def read_and_preprocess(feature_engineering=False):
feld_needed = ['timestamp', 'user_id', 'answered_correctly', 'content_id', 'content_type_id', 'prior_question_elapsed_time', 'prior_question_had_explanation']
train = pd.read_pickle(train_pickle)[feld_needed]
valid = pd.read_pickle(valid_pickle)[feld_needed]
if feature_engineering:
train = train.iloc[-feature_engineering_rows:]
train = train.loc[train.content_type_id == False].reset_index(drop=True)
 valid = valid.loc[valid.content_type_id == False].reset_index(drop=True)
 train['prior_question_elapsed_time'] = train['prior_question_elapsed_time'] / 10000.
 valid['prior_question_elapsed_time'] = valid['prior_question_elapsed_time'] / 10000.
 train['prior_question_had_explanation'] = train.prior_question_had_explanation.fillna(False ).astype('int8')
 valid['prior_question_had_explanation'] = valid.prior_question_had_explanation.fillna(False ).astype('int8')
 prior_question_elapsed_time_mean = train['prior_question_elapsed_time'].dropna().mean()
train['prior_question_elapsed_time'].fillna(prior_question_elapsed_time_mean, inplace=True)
 valid['prior_question_elapsed_time'].fillna(prior_question_elapsed_time_mean, inplace=True)
 questions_df = pd.read_csv(question_file)
 questions_df['part'] = questions_df['part'].astype(np.int32)
 questions_df['bundle_id'] = questions_df['bundle_id'].astype(np.int32)
 train = pd.merge(train, questions_df[['question_id', 'part', 'tags']], left_on='content_id', right_on='question_id', how='left')
 valid = pd.merge(valid, questions_df[['question_id', 'part', 'tags']], left_on='content_id', right_on='question_id', how='left')
 answered_correctly_u_count = defaultdict(int)
 answered_correctly_u_sum = defaultdict(int)
 elapsed_time_u_sum = defaultdict(int)
 explanation_u_sum = defaultdict(int)
 timestamp_u = defaultdict(list)
 timestamp_u_incorrect = defaultdict(list)
 answered_correctly_q_count = defaultdict(int)
 answered_correctly_q_sum = defaultdict(int)
 elapsed_time_q_sum = defaultdict(int)
 explanation_q_sum = defaultdict(int)
 answered_correctly_uq = defaultdict(defaultdictInt)
 part_user_count = defaultdict(defaultdictInt)
 part_user_sum = defaultdict(defaultdictInt)
 answered_correctly_ut = defaultdict(defaultdictInt)
 answered_correctly_ut_sum = defaultdict(defaultdictInt)
 print('User feature calculation started...')
 print('
')
 train = add_features(
 train, answered_correctly_u_count, answered_correctly_u_sum,
elapsed_time_u_sum, explanation_u_sum, timestamp_u, timestamp_u_incorrect,
answered_correctly_q_count, answered_correctly_q_sum, elapsed_time_q_sum,
explanation_q_sum, answered_correctly_uq, part_user_count, part_user_sum,
answered_correctly_ut, answered_correctly_ut_sum 
)
 valid = add_features(
 valid, answered_correctly_u_count, answered_correctly_u_sum,
elapsed_time_u_sum, explanation_u_sum, timestamp_u, timestamp_u_incorrect,
answered_correctly_q_count, answered_correctly_q_sum, elapsed_time_q_sum,
explanation_q_sum, answered_correctly_uq, part_user_count, part_user_sum,
answered_correctly_ut, answered_correctly_ut_sum 
)
 gc.collect()
print('User feature calculation completed...')
 print('
')
 train.set_index('content_id', inplace=True), valid.set_index('content_id', inplace=True)
 content_feat = pickle.load(open(contents_feat_file, 'rb'))
train = train.join(content_feat)
 valid = valid.join(content_feat)
 question_tags_df = pd.read_csv(question_tags_file, dtype=question_tags_df_dtypes)
 question_tags_df.set_index('question_id', inplace=True)
 train = train.join(question_tags_df)
 valid = valid.join(question_tags_df)
 train.reset_index(inplace=True), valid.reset_index(inplace=True)
 features_dicts = {
'answered_correctly_u_count': answered_correctly_u_count,
'answered_correctly_u_sum': answered_correctly_u_sum,
'elapsed_time_u_sum': elapsed_time_u_sum,
'explanation_u_sum': explanation_u_sum,
'answered_correctly_q_count': answered_correctly_q_count,
'answered_correctly_q_sum': answered_correctly_q_sum,
'elapsed_time_q_sum': elapsed_time_q_sum,
'explanation_q_sum': explanation_q_sum,
'answered_correctly_uq': answered_correctly_uq,
'timestamp_u': timestamp_u,
'timestamp_u_incorrect': timestamp_u_incorrect,
'part_user_count': part_user_count,
'part_user_sum': part_user_sum,
'answered_correctly_ut': answered_correctly_ut,
'answered_correctly_ut_sum': answered_correctly_ut_sum
}
return train, valid, questions_df, prior_question_elapsed_time_mean, features_dicts<set_options>
nfolds = 7
nstarts = 7
nepochs = 50
batch_size = 128
val_batch_size = batch_size * 4
ntargets = train_targets.shape[1]
targets = [col for col in train_targets.columns]
criterion = nn.BCELoss()
kfold = MultilabelStratifiedKFold(n_splits=7, random_state=42, shuffle=True)
 device = torch.device("cuda:0" if torch.cuda.is_available() else "cpu" )
gc.collect()<split>
class MoaModel(nn.Module):
def __init__(self, num_columns):
super(MoaModel, self ).__init__()
self.batch_norm1 = nn.BatchNorm1d(num_columns)
 self.dropout1 = nn.Dropout(0.2)
 self.dense1 = nn.utils.weight_norm(nn.Linear(num_columns, 2048))
self.batch_norm2 = nn.BatchNorm1d(2048)
 self.dropout2 = nn.Dropout(0.5)
 self.dense2 = nn.utils.weight_norm(nn.Linear(2048, 1048))
self.batch_norm3 = nn.BatchNorm1d(1048)
 self.dropout3 = nn.Dropout(0.5)
 self.dense3 = nn.utils.weight_norm(nn.Linear(1048, 206))
def forward(self, x):
x = self.batch_norm1(x)
 x = self.dropout1(x)
 x = F.relu(self.dense1(x))
x = self.batch_norm2(x)
 x = self.dropout2(x)
 x = F.relu(self.dense2(x))
x = self.batch_norm3(x)
 x = self.dropout3(x)
 x = F.sigmoid(self.dense3(x))
return x
%%time
train, valid, questions_df, prior_question_elapsed_time_mean, features_dicts = read_and_preprocess(feature_engineering=True )<feature_engineering>
top_feats = [ 1, 2, 3, 4, 5, 6, 7, 9, 11, 14, 15, 16, 17,
18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 29, 30, 31,
32, 33, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 46,
47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 58, 59, 60,
61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73,
74, 75, 76, 78, 79, 80, 81, 82, 83, 84, 86, 87, 88,
89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101,
102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114,
115, 116, 117, 118, 120, 121, 122, 123, 124, 125, 126, 127, 128,
129, 130, 131, 132, 133, 136, 137, 138, 139, 140, 141, 142, 143,
144, 145, 146, 147, 149, 150, 151, 152, 153, 154, 155, 156, 157,
158, 159, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170,
171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183,
184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 197,
198, 199, 200, 202, 203, 204, 205, 206, 208, 209, 210, 211, 212,
213, 214, 215, 216, 217, 218, 219, 220, 221, 223, 224, 225, 226,
227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239,
240, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253,
254, 255, 256, 257, 258, 259, 260, 261, 262, 263, 264, 265, 266,
267, 268, 269, 271, 272, 273, 274, 275, 276, 277, 278, 279, 280,
281, 282, 283, 284, 285, 286, 287, 288, 289, 290, 291, 292, 294,
295, 296, 298, 300, 301, 302, 303, 304, 305, 306, 307, 308, 309,
310, 311, 312, 314, 315, 316, 317, 318, 319, 320, 321, 322, 323,
324, 325, 326, 327, 328, 329, 330, 331, 332, 333, 334, 335, 336,
337, 338, 339, 340, 341, 342, 343, 344, 345, 346, 347, 348, 349,
350, 351, 352, 353, 354, 355, 356, 357, 358, 359, 360, 361, 362,
363, 364, 365, 366, 367, 368, 369, 370, 371, 374, 375, 376, 377,
378, 379, 380, 381, 382, 383, 384, 385, 386, 387, 388, 390, 391,
392, 393, 394, 395, 396, 397, 398, 399, 400, 401, 402, 403, 404,
405, 406, 407, 408, 409, 411, 412, 413, 414, 415, 416, 417, 418,
419, 420, 421, 422, 423, 424, 425, 426, 427, 428, 429, 430, 431,
432, 434, 435, 436, 437, 438, 439, 440, 442, 443, 444, 445, 446,
447, 448, 449, 450, 453, 454, 456, 457, 458, 459, 460, 461, 462,
463, 464, 465, 466, 467, 468, 469, 470, 471, 472, 473, 474, 475,
476, 477, 478, 479, 481, 482, 483, 484, 485, 486, 487, 488, 489,
490, 491, 492, 493, 494, 495, 496, 498, 500, 501, 502, 503, 505,
506, 507, 509, 510, 511, 512, 513, 514, 515, 518, 519, 520, 521,
522, 523, 524, 525, 526, 527, 528, 530, 531, 532, 534, 535, 536,
538, 539, 540, 541, 542, 543, 544, 545, 546, 547, 549, 550, 551,
552, 554, 557, 559, 560, 561, 562, 565, 566, 567, 568, 569, 570,
571, 572, 573, 574, 575, 577, 578, 580, 581, 582, 583, 584, 585,
586, 587, 588, 589, 590, 591, 592, 593, 594, 595, 596, 597, 599,
600, 601, 602, 606, 607, 608, 609, 611, 612, 613, 615, 616, 617,
618, 619, 620, 621, 622, 623, 624, 625, 626, 627, 628, 629, 630,
631, 632, 633, 634, 635, 636, 637, 638, 639, 641, 642, 643, 644,
645, 646, 647, 648, 649, 650, 651, 652, 654, 655, 656, 658, 659,
660, 661, 662, 663, 664, 665, 666, 667, 668, 669, 670, 671, 672,
673, 674, 675, 676, 677, 678, 679, 680, 681, 682, 683, 684, 685,
686, 687, 688, 689, 691, 692, 693, 694, 695, 696, 697, 699, 700,
701, 702, 704, 705, 707, 708, 709, 710, 711, 713, 714, 716, 717,
718, 720, 721, 723, 724, 725, 726, 727, 728, 729, 730, 731, 732,
733, 734, 735, 737, 738, 739, 740, 742, 743, 744, 745, 746, 747,
748, 749, 750, 751, 752, 753, 754, 755, 756, 757, 759, 760, 761,
762, 763, 764, 765, 766, 767, 768, 769, 770, 771, 772, 773, 774,
775, 776, 777, 779, 780, 781, 782, 783, 784, 785, 786, 787, 788,
789, 790, 792, 793, 794, 795, 796, 797, 798, 800, 801, 802, 803,
804, 805, 806, 808, 809, 811, 813, 814, 815, 816, 817, 818, 819,
821, 822, 823, 825, 826, 827, 828, 829, 830, 831, 832, 834, 835,
837, 838, 839, 840, 841, 842, 845, 846, 847, 848, 850, 851, 852,
854, 855, 856, 858, 859, 860, 861, 862, 864, 866, 867, 868, 869,
870, 871, 872, 873, 874]
print(len(top_feats))
def features4features(df):
df['correctness_u_q_avg_diff'] = df['answered_correctly_u_avg'] - df['answered_correctly_q_avg']
df['correctness_u_pu_avg_diff'] = df['answered_correctly_u_avg'] - df['part_u_mean']
df['correctness_u_uv_avg_max_diff'] = df['answered_correctly_u_avg'] - df['answered_correctly_ut_avg_max']
df['correctness_u_uv_avg_min_diff'] = df['answered_correctly_u_avg'] - df['answered_correctly_ut_avg_min']
df['correctness_uv_avg_max_min_diff'] = df['answered_correctly_ut_avg_max'] - df['answered_correctly_ut_avg_min']
df['correctness_u_t_avg_max_diff'] = df['answered_correctly_u_avg'] - df['tag_acc_max']
df['correctness_u_t_avg_min_diff'] = df['answered_correctly_u_avg'] - df['tag_acc_min']
df['elapsed_time_u_q_diff'] = df['elapsed_time_u_avg'] - df['elapsed_time_q_avg']
df['explanation_u_q_diff'] = df['explanation_u_avg'] - df['explanation_q_avg']
return df
def train_and_evaluate(train, valid, feature_engineering=False):
TARGET = 'answered_correctly'
FEATURES = [
'prior_question_elapsed_time', 'answered_correctly_u_avg', 'part',
'elapsed_time_u_avg', 'explanation_u_avg', 'answered_correctly_q_avg',
'elapsed_time_q_avg', 'explanation_q_avg', 'answered_correctly_uq_count',
'timestamp_u_recency_1', 'timestamp_u_recency_2', 'timestamp_u_recency_3',
'timestamp_u_incorrect_recency', 'part_u_count', 'part_u_mean',
'answered_correctly_ut_count', 'answered_correctly_ut_avg_max',
'answered_correctly_ut_avg_min',
'question_elapsed_time_mean', 'question_had_explanation_mean',
'question_correctly_q_count', 'question_correctly_q_mean',
'tags_lsi', 'tag_acc_max', 'tag_acc_min',
]
CATEGORICAL_FEATURES = [
'tags_lsi', 'part'
]
for col in CATEGORICAL_FEATURES:
train[col] = train[col].astype('category')
 valid[col] = valid[col].astype('category')
 if feature_engineering:
train = train.sample(training_rows, random_state=SEED)
 gc.collect()
print(f'Traning with {train.shape[0]} rows and {len(FEATURES)} features')
 drop_cols = list(set(train.columns)- set(FEATURES))
y_train = train[TARGET]
y_val = valid[TARGET]
for col in drop_cols:
del train[col], valid[col]
gc.collect()
train = features4features(train)
 valid = features4features(valid)
 FEATURES = train.columns
lgb_train = lgb.Dataset(train[FEATURES], y_train, categorical_feature=CATEGORICAL_FEATURES)
 lgb_valid = lgb.Dataset(valid[FEATURES], y_val, categorical_feature=CATEGORICAL_FEATURES)
 del y_train, train
gc.collect()
params = {
'objective': 'binary',
'seed': SEED,
'learning_rate':.1,
'max_depth': 15,
'metric': 'auc',
'num_leaves': 300,
'feature_fraction': 0.75,
'bagging_freq': 10,
'subsample': 0.80,
}
model = lgb.train(
 params=params,
train_set=lgb_train,
num_boost_round=10000,
valid_sets=[lgb_train, lgb_valid],
early_stopping_rounds=10,
verbose_eval=50, 
)
 print('Our Roc Auc score for the validation data is:', roc_auc_score(y_val, model.predict(valid[FEATURES])))
 feature_importance = model.feature_importance()
feature_importance = pd.DataFrame({'Features': FEATURES, 'Importance': feature_importance} ).sort_values('Importance', ascending = False)
 fig = plt.figure(figsize=(10, 10))
fig.suptitle('Feature Importance', fontsize=20)
 plt.tick_params(axis='x', labelsize=12)
 plt.tick_params(axis='y', labelsize=12)
 plt.xlabel('Importance', fontsize=15)
 plt.ylabel('Features', fontsize=15)
 sns.barplot(x=feature_importance['Importance'], y=feature_importance['Features'], orient='h')
 plt.show()
return TARGET, FEATURES, CATEGORICAL_FEATURES, model<train_model>
class MoaDataset(Dataset):
def __init__(self, df, targets, feats_idx, mode='train'):
self.mode = mode
self.feats = feats_idx
self.data = df[:, feats_idx]
if mode=='train':
self.targets = targets
def __len__(self):
return len(self.data)
 def __getitem__(self, idx):
if self.mode == 'train':
return torch.FloatTensor(self.data[idx]), torch.FloatTensor(self.targets[idx])
 elif self.mode == 'test':
return torch.FloatTensor(self.data[idx]), 0
<define_variables>
train = train.values
test = test.values
train_targets = train_targets.values
TARGET = 'answered_correctly'
FEATURES = [
'prior_question_elapsed_time', 'answered_correctly_u_avg', 'part',
'elapsed_time_u_avg', 'explanation_u_avg', 'answered_correctly_q_avg',
'elapsed_time_q_avg', 'explanation_q_avg', 'answered_correctly_uq_count',
'timestamp_u_recency_1', 'timestamp_u_recency_2', 'timestamp_u_recency_3',
'timestamp_u_incorrect_recency', 'part_u_count', 'part_u_mean',
'answered_correctly_ut_count', 'answered_correctly_ut_avg_max',
'answered_correctly_ut_avg_min',
'question_elapsed_time_mean', 'question_had_explanation_mean',
'question_correctly_q_count', 'question_correctly_q_mean',
'tags_lsi', 'tag_acc_max', 'tag_acc_min',
]
CATEGORICAL_FEATURES = [
'tags_lsi', 'part'
]
for col in CATEGORICAL_FEATURES:
train[col] = train[col].astype('category')
 valid[col] = valid[col].astype('category')
 train = train.sample(training_rows, random_state=SEED)
 gc.collect()
print(f'Traning with {train.shape[0]} rows and {len(FEATURES)} features')
 drop_cols = list(set(train.columns)- set(FEATURES))
y_train = train[TARGET]
y_val = valid[TARGET]
for col in drop_cols:
del train[col], valid[col]
gc.collect()
train = features4features(train)
 valid = features4features(valid)
 FEATURES = train.columns
lgb_train = lgb.Dataset(train[FEATURES], y_train, categorical_feature=CATEGORICAL_FEATURES)
 lgb_valid = lgb.Dataset(valid[FEATURES], y_val, categorical_feature=CATEGORICAL_FEATURES)
 del y_train, train
gc.collect()
params = {
'objective': 'binary',
'seed': SEED,
'learning_rate':.1,
'max_depth': 15,
'metric': 'auc',
'num_leaves': 300,
'feature_fraction': 0.75,
'bagging_freq': 10,
'subsample': 0.80,
}
model = lgb.train(
 params=params,
train_set=lgb_train,
num_boost_round=10000,
valid_sets=[lgb_train, lgb_valid],
early_stopping_rounds=10,
verbose_eval=50, 
)
 print('Our Roc Auc score for the validation data is:', roc_auc_score(y_val, model.predict(valid[FEATURES])))
 feature_importance = model.feature_importance()
feature_importance = pd.DataFrame({'Features': FEATURES, 'Importance': feature_importance} ).sort_values('Importance', ascending = False)
 fig = plt.figure(figsize=(10, 10))
fig.suptitle('Feature Importance', fontsize=20)
 plt.tick_params(axis='x', labelsize=12)
 plt.tick_params(axis='y', labelsize=12)
 plt.xlabel('Importance', fontsize=15)
 plt.ylabel('Features', fontsize=15)
 sns.barplot(x=feature_importance['Importance'], y=feature_importance['Features'], orient='h')
 plt.show()<split>
for seed in range(nstarts):
print(f'Train seed {seed}')
 set_seed(seed)
 for n,(tr, te)in enumerate(kfold.split(train_targets, train_targets)) :
print(f'Train fold {n+1}')
 xtrain, xval = train[tr], train[te]
ytrain, yval = train_targets[tr], train_targets[te]
train_set = MoaDataset(xtrain, ytrain, top_feats)
 val_set = MoaDataset(xval, yval, top_feats)
 dataloaders = {
'train': DataLoader(train_set, batch_size=batch_size, shuffle=True),
'val': DataLoader(val_set, batch_size=val_batch_size, shuffle=False)
 }
model = MoaModel(len(top_feats)).to(device)
 checkpoint_path = f'repeat:{seed}_Fold:{n+1}.pt'
optimizer = optim.Adam(model.parameters() , weight_decay=1e-5)
 scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode='min', factor=0.1, patience=3, eps=1e-4, verbose=True)
 best_loss = {'train': np.inf, 'val': np.inf}
for epoch in range(nepochs):
epoch_loss = {'train': 0.0, 'val': 0.0}
for phase in ['train', 'val']:
if phase == 'train':
model.train()
else:
model.eval()
running_loss = 0.0
for i,(x, y)in enumerate(dataloaders[phase]):
x, y = x.to(device), y.to(device)
 optimizer.zero_grad()
with torch.set_grad_enabled(phase=='train'):
preds = model(x)
 loss = criterion(preds, y)
 if phase=='train':
loss.backward()
optimizer.step()
running_loss += loss.item() / len(dataloaders[phase])
 epoch_loss[phase] = running_loss
print("Epoch {}/{} - loss: {:5.5f} - val_loss: {:5.5f}".format(epoch+1, nepochs, epoch_loss['train'], epoch_loss['val']))
scheduler.step(epoch_loss['val'])
 if epoch_loss['val'] < best_loss['val']:
best_loss = epoch_loss
torch.save(model.state_dict() , checkpoint_path )
def inference(TARGET, FEATURES, CATEGORICAL_FEATURES, model, questions_df, prior_question_elapsed_time_mean, features_dicts):
answered_correctly_u_count = features_dicts['answered_correctly_u_count']
answered_correctly_u_sum = features_dicts['answered_correctly_u_sum']
elapsed_time_u_sum = features_dicts['elapsed_time_u_sum']
explanation_u_sum = features_dicts['explanation_u_sum']
answered_correctly_q_count = features_dicts['answered_correctly_q_count']
answered_correctly_q_sum = features_dicts['answered_correctly_q_sum']
elapsed_time_q_sum = features_dicts['elapsed_time_q_sum']
explanation_q_sum = features_dicts['explanation_q_sum']
answered_correctly_uq = features_dicts['answered_correctly_uq']
timestamp_u = features_dicts['timestamp_u']
timestamp_u_incorrect = features_dicts['timestamp_u_incorrect']
part_user_count = features_dicts['part_user_count']
part_user_sum = features_dicts['part_user_sum']
answered_correctly_ut = features_dicts['answered_correctly_ut']
answered_correctly_ut_sum = features_dicts['answered_correctly_ut_sum']
env = riiideducation.make_env()
iter_test = env.iter_test()
set_predict = env.predict
content_feat = pickle.load(open(contents_feat_file, 'rb'))
question_tags_df = pd.read_csv(question_tags_file, dtype=question_tags_df_dtypes)
 question_tags_df.set_index('question_id', inplace=True)
 previous_test_df = None
for(test_df, sample_prediction_df)in iter_test:
if previous_test_df is not None:
previous_test_df[TARGET] = eval(test_df["prior_group_answers_correct"].iloc[0])
 update_features(
 previous_test_df, answered_correctly_u_sum, answered_correctly_q_sum, timestamp_u_incorrect,
part_user_sum, answered_correctly_ut_sum 
)
 test_df = pd.merge(test_df, questions_df[['question_id', 'part', 'tags']], left_on='content_id', right_on='question_id', how='left')
 previous_test_df = test_df.copy()
test_df = test_df[test_df['content_type_id'] == 0].reset_index(drop = True)
 test_df['prior_question_elapsed_time'] = test_df['prior_question_elapsed_time'] / 10000.
 test_df['prior_question_had_explanation'] = test_df.prior_question_had_explanation.fillna(False ).astype('int8')
 test_df['prior_question_elapsed_time'].fillna(prior_question_elapsed_time_mean, inplace=True)
 test_df.set_index('content_id', inplace=True)
 test_df = test_df.join(content_feat)
 test_df = test_df.join(question_tags_df)
 test_df.reset_index(inplace=True)
 test_df[TARGET] = 0
test_df = add_features(
 test_df, answered_correctly_u_count, answered_correctly_u_sum,
elapsed_time_u_sum, explanation_u_sum, timestamp_u, timestamp_u_incorrect,
answered_correctly_q_count, answered_correctly_q_sum, elapsed_time_q_sum,
explanation_q_sum, answered_correctly_uq, part_user_count, part_user_sum,
answered_correctly_ut, answered_correctly_ut_sum,
update=False 
)
 for col in CATEGORICAL_FEATURES:
test_df[col] = test_df[col].astype('category')
 test_df = features4features(test_df)
 test_df[TARGET] = model.predict(test_df[FEATURES])
 set_predict(test_df[['row_id', TARGET]])
 print('Job Done' )<import_modules>
oof = np.zeros(( len(train), nstarts, ntargets))
oof_targets = np.zeros(( len(train), ntargets))
preds = np.zeros(( len(test), ntargets))
import numpy as np
import pandas as pd
import lightgbm as lgb
import matplotlib.pyplot as plt
import seaborn as sns
from sklearn.metrics import roc_auc_score
from multiprocessing import cpu_count
from tqdm.notebook import tqdm
from memory_profiler import memory_usage
from cairosvg import svg2png
from PIL import Image
from io import BytesIO
from collections import deque
from glob import glob
from statistics import mean
import gc
import os
import sys
import re
import pickle
import math<define_variables>
def mean_log_loss(y_true, y_pred):
metrics = []
for i, target in enumerate(targets):
metrics.append(log_loss(y_true[:, i], y_pred[:, i].astype(float), labels=[0,1]))
return np.mean(metrics )
VERSION = 'V1G'
NUM_BOOST_ROUND = 5000
VERBOSE_EVAL = 10
METRICS = ['auc']
N_ROWS = 99271300
def get_index_np() :
return np.arange(N_ROWS )<data_type_conversions>
for seed in range(nstarts):
print(f"Inference for seed {seed}")
 seed_targets = []
seed_oof = []
seed_preds = np.zeros(( len(test), ntargets, nfolds))
for n,(tr, te)in enumerate(kfold.split(train_targets, train_targets)) :
xval, yval = train[te], train_targets[te]
fold_preds = []
val_set = MoaDataset(xval, yval, top_feats)
 test_set = MoaDataset(test, None, top_feats, mode='test')
 dataloaders = {
'val': DataLoader(val_set, batch_size=val_batch_size, shuffle=False),
'test': DataLoader(test_set, batch_size=val_batch_size, shuffle=False)
 }
checkpoint_path = f'repeat:{seed}_Fold:{n+1}.pt'
model = MoaModel(len(top_feats)).to(device)
 model.load_state_dict(torch.load(checkpoint_path))
model.eval()
for phase in ['val', 'test']:
for i,(x, y)in enumerate(dataloaders[phase]):
if phase == 'val':
x, y = x.to(device), y.to(device)
 elif phase == 'test':
x = x.to(device)
 with torch.no_grad() :
batch_preds = model(x)
 if phase == 'val':
seed_targets.append(y)
 seed_oof.append(batch_preds)
 elif phase == 'test':
fold_preds.append(batch_preds)
 fold_preds = torch.cat(fold_preds, dim=0 ).cpu().numpy()
seed_preds[:, :, n] = fold_preds
seed_targets = torch.cat(seed_targets, dim=0 ).cpu().numpy()
seed_oof = torch.cat(seed_oof, dim=0 ).cpu().numpy()
seed_preds = np.mean(seed_preds, axis=2)
 print("Score for this seed {:5.5f}".format(mean_log_loss(seed_targets, seed_oof)))
 oof_targets = seed_targets
oof[:, seed, :] = seed_oof
preds += seed_preds / nstarts
oof = np.mean(oof, axis=1)
 print("Overall score is {:5.5f}".format(mean_log_loss(oof_targets, oof)) )
<define_variables><EOS> 
ss[targets] = preds
ss.loc[test_features['cp_type']=='ctl_vehicle', targets] = 0
ss.to_csv('submission.csv', index=False )