Kaggle competition: Riiid Answer Correctness Prediction
<SOS> metric: AUC Kaggle data source: riiid-answer-correctness-prediction<drop_column>
SCALING = 5
train = train.drop(['Fare'], axis = 1)
 test = test.drop(['Fare'], axis = 1 )<feature_engineering>
random.seed(42)
 TQDM_INT = 8
EPOCHS = 10
MAX_SEQ = 150
NUM_EMBED = 128
NUM_HEADS = 8
WORKERS = 4
BATCH_SIZE = 1024
VAL_BATCH_SIZE = 4096
n_skill = 13523
LEARNING_RATE = 1e-3
train["FamilySize"] = train_data["SibSp"] + train_data["Parch"] + 1<feature_engineering>
TRAIN_DTYPES = {'timestamp':'int64',
'user_id':'int32' ,
'content_id':'int16',
'content_type_id':'int8',
'answered_correctly':'int8'}
TRAIN_COLS = TRAIN_DTYPES.keys()
test["FamilySize"] = test_data["SibSp"] + test_data["Parch"] + 1<categorify>
%%time
train_df = pd.read_parquet('.. /input/cv-strategy-in-the-kaggle-environment/cv3_train.parquet')
 train_df = train_df[TRAIN_COLS].astype(TRAIN_DTYPES)
 train_df = train_df[train_df["content_type_id"] == False]
train_df = train_df.sort_values(['timestamp'], ascending=True ).reset_index(drop = True)
train['Single'] = train['FamilySize'].map(lambda s: 1 if s == 1 else 0)
 train['SmallFam'] = train['FamilySize'].map(lambda s: 1 if s == 2 else 0)
 train['MedFam'] = train['FamilySize'].map(lambda s: 1 if 3 <= s <= 4 else 0)
 train['LargeFam'] = train['FamilySize'].map(lambda s: 1 if s >= 5 else 0 )<categorify>
SMOOTHING_FACTOR=0.2
train_df[['answered_correctly']] = train_df[['answered_correctly']]*(1-SMOOTHING_FACTOR)\
+ SMOOTHING_FACTOR/2
train_group = train_df[['user_id', 'content_id', 'answered_correctly']]\ 
.groupby('user_id' ).apply(lambda r:(
 r['content_id'].values,
r['answered_correctly'].values))
test['Single'] = test['FamilySize'].map(lambda s: 1 if s == 1 else 0)
 test['SmallFam'] = test['FamilySize'].map(lambda s: 1 if s == 2 else 0)
 test['MedFam'] = test['FamilySize'].map(lambda s: 1 if 3 <= s <= 4 else 0)
 test['LargeFam'] = test['FamilySize'].map(lambda s: 1 if s >= 5 else 0 )<categorify>
del train_df
gc.collect() ;
train = pd.get_dummies(train, columns = ["Embarked"], prefix="Em" )<categorify>
valid_df = pd.read_parquet('.. /input/cv-strategy-in-the-kaggle-environment/cv3_valid.parquet')
 valid_df = valid_df[TRAIN_COLS].astype(TRAIN_DTYPES)
 valid_df = valid_df[valid_df["content_type_id"] == False]
valid_group = valid_df[['user_id', 'content_id', 'answered_correctly']]\ 
.groupby('user_id' ).apply(lambda r:(
 r['content_id'].values,
r['answered_correctly'].values))
del valid_df
gc.collect() ;
test = pd.get_dummies(test, columns = ["Embarked"], prefix="Em")
<split>
class FFN(nn.Module):
def __init__(self, state_size=200):
super(FFN, self ).__init__()
self.state_size = state_size
self.lr1 = nn.Linear(state_size, state_size)
 self.relu = nn.ReLU()
self.lr2 = nn.Linear(state_size, state_size)
 self.dropout = nn.Dropout(0.2)
 def forward(self, x):
x = self.lr1(x)
 x = self.relu(x)
 x = self.lr2(x)
 return self.dropout(x)
 def future_mask(seq_length):
future_mask = np.triu(np.ones(( seq_length, seq_length)) , k=1 ).astype('bool')
 return torch.from_numpy(future_mask)
 class SAKTModel(nn.Module):
def __init__(self, n_skill,
max_seq=MAX_SEQ,
embed_dim=NUM_EMBED,
num_heads=NUM_HEADS,
num_layers=1):
super(SAKTModel, self ).__init__()
self.n_skill = n_skill
self.embed_dim = embed_dim
self.embedding = nn.Embedding(2*n_skill+1, embed_dim)
 self.pos_embedding = nn.Embedding(max_seq-1, embed_dim)
 self.e_embedding = nn.Embedding(n_skill+1, embed_dim)
 self.multi_att = nn.MultiheadAttention(embed_dim=embed_dim, num_heads=num_heads, dropout=0.2)
 self.dropout = nn.Dropout(0.2)
 self.layer_normal = nn.LayerNorm(embed_dim)
 self.ffn = FFN(embed_dim)
 self.pred = nn.Linear(embed_dim, 1)
 def forward(self, x, question_ids):
device = x.device
x = self.embedding(x)
 pos_id = torch.arange(x.size(1)).unsqueeze(0 ).to(device)
 pos_x = self.pos_embedding(pos_id)
 x = x + pos_x
e = self.e_embedding(question_ids)
 x = x.permute(1, 0, 2)
 e = e.permute(1, 0, 2)
 att_mask = future_mask(x.size(0)).to(device)
 att_output, att_weight = self.multi_att(e, x, x, attn_mask=att_mask)
 att_output = self.layer_normal(att_output + e)
 att_output = att_output.permute(1, 0, 2)
 x = self.ffn(att_output)
 x = self.layer_normal(x+att_output)
 x = self.pred(x)
 return x.squeeze(-1), att_weight
class SAKTDataset(Dataset):
def __init__(self, group, n_skill, subset="train", max_seq=MAX_SEQ):
super(SAKTDataset, self ).__init__()
self.max_seq = max_seq
self.n_skill = n_skill
self.samples = group
self.subset = subset
self.user_ids = []
for user_id in group.index:

 q, qa = group[user_id]
if len(q)< 2:
continue
self.user_ids.append(user_id)
 def __len__(self):
return len(self.user_ids)
 def __getitem__(self, index):
user_id = self.user_ids[index]
q_, qa_ = self.samples[user_id]
seq_len = len(q_)
 q = np.zeros(self.max_seq, dtype=int)
 qa = np.zeros(self.max_seq, dtype=np.float16)
 if seq_len >= self.max_seq:
if self.subset == "train":
if random.random() > 0.1:
random_start_index = random.randint(0, seq_len - self.max_seq)

end_index = random_start_index + self.max_seq
q[:] = q_[random_start_index:end_index]
qa[:] = qa_[random_start_index:end_index]
else:
q[:] = q_[-self.max_seq:]
qa[:] = qa_[-self.max_seq:]
else:
q[:] = q_[-self.max_seq:]
qa[:] = qa_[-self.max_seq:]
else:
if random.random() >0.1:
seq_len = random.randint(2,seq_len)
 q[-seq_len:] = q_[:seq_len]
qa[-seq_len:] = qa_[:seq_len]
else:
q[-seq_len:] = q_
qa[-seq_len:] = qa_
target_id = q[1:]
label = qa[1:]
x = q[:-1].copy()
x +=(qa[:-1] == 1)* self.n_skill
return x, target_id, label
def train_epoch(model, train_iterator, optim, criterion, device="cuda"):
model.train()
train_loss = []
num_corrects = 0
num_total = 0
labels = []
outs = []
len_dataset = len(train_iterator)
 for idx, item in enumerate(train_iterator):
x = item[0].to(device ).long()
target_id = item[1].to(device ).long()
label = item[2].to(device ).float()
optim.zero_grad()
output, atten_weight = model(x, target_id)
 loss = criterion(output, label)
 loss.backward()
optim.step()
train_loss.append(loss.item())
 output = output[:, -1]
label =(label[:, -1] >=0.5 ).long()
output = torch.sigmoid(output)
 pred =(output >= 0.5 ).long()
num_corrects +=(pred == label ).sum().item()
num_total += len(label)
 labels.extend(label.view(-1 ).data.cpu().numpy())
 outs.extend(output.view(-1 ).data.cpu().numpy())
 acc = num_corrects / num_total
auc = roc_auc_score(labels, outs)
 loss = np.mean(train_loss)
 return loss, acc, auc
def valid_epoch(model, valid_iterator, criterion, device="cuda", scaling=1):
model.eval()
valid_loss = []
num_corrects = 0
num_total = 0
labels = []
outs = []
len_dataset = len(valid_iterator)
 for idx, item in enumerate(valid_iterator):
x = item[0].to(device ).long()
target_id = item[1].to(device ).long()
label = item[2].to(device ).float()
with torch.no_grad() :
output, _ = model(x, target_id)
 loss = criterion(output, label)
 valid_loss.append(loss.item())
 output = scaling*output[:, -1]
output = torch.sigmoid(output)
 label = label[:, -1]
pred =(output >= 0.5 ).long()
num_corrects +=(pred == label ).sum().item()
num_total += len(label)
 labels.extend(label.view(-1 ).data.cpu().numpy())
 outs.extend(output.view(-1 ).data.cpu().numpy())
 acc = num_corrects / num_total
auc = roc_auc_score(labels, outs)
 loss = np.mean(valid_loss)
 return loss, acc, auc
predictors = train.drop(['Survived', 'PassengerId'], axis=1)
 target = train["Survived"]
x_train, x_test, y_train, y_test = train_test_split(predictors, target, test_size = 0.20, random_state = 0)
<compute_train_metric>
train_dataset = SAKTDataset(train_group, n_skill, subset="train")
 train_loader = DataLoader(train_dataset,
batch_size=BATCH_SIZE,
shuffle=True,
num_workers=WORKERS)
 valid_dataset = SAKTDataset(valid_group, n_skill, subset="valid")
 val_loader = DataLoader(valid_dataset,
batch_size=VAL_BATCH_SIZE,
shuffle=False,
num_workers=WORKERS )
logreg = LogisticRegression()
logreg.fit(x_train, y_train)
 y_pred = logreg.predict(x_test)
 acc_logreg = round(accuracy_score(y_pred, y_test)* 100, 2)
 print(acc_logreg)
<choose_model_class>
item = train_dataset.__getitem__(5)
 print("x", len(item[0]), item[0], '
')
 print("target_id", len(item[1]), item[1] , '
')
 print("label", len(item[2]), item[2], '
' )
randomforest = RandomForestClassifier()
randomforest.fit(x_train, y_train)
 y_pred = randomforest.predict(x_test)
 acc_randomforest = round(accuracy_score(y_pred, y_test)* 100, 2)
 print(acc_randomforest )<train_model>
def get_num_params(model):
model_parameters = filter(lambda p: p.requires_grad, model.parameters())
 no_params = sum([np.prod(p.size())for p in model_parameters])
 return no_params
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
 model = SAKTModel(n_skill, embed_dim=NUM_EMBED, num_heads=NUM_HEADS)
 optimizer = torch.optim.Adam(model.parameters() , lr=LEARNING_RATE)
 criterion = nn.BCEWithLogitsLoss()
model.to(device)
 criterion.to(device)
 num_params = get_num_params(model)
 print(f"
print(f"
print(f"seq len : {MAX_SEQ}")
 print(f"
gbk = GradientBoostingClassifier()
gbk.fit(x_train, y_train)
 y_pred = gbk.predict(x_test)
 acc_gbk = round(accuracy_score(y_pred, y_test)* 100, 2)
 print(acc_gbk)
<train_on_grid>
epochs = 10
for epoch in range(epochs):
loss, acc, auc = train_epoch(model, train_loader, optimizer, criterion, device)
 print(f"Epoch - [{epoch}/{epochs}]")
 print(f"Train with label smoothing: loss - {loss:.4f} acc - {acc:.4f} auc - {auc:.4f}")
 val_loss, val_acc, val_auc = valid_epoch(model, val_loader, criterion, device=device)
 print(f"Valid without scaling : loss - {val_loss:.4f} acc - {val_acc:.4f} auc - {val_auc:.4f}")
 val_loss, val_acc, val_auc = valid_epoch(model, val_loader, criterion, device=device, scaling=SCALING)
 print(f"Valid with a scaling of {SCALING} : loss - {val_loss:.4f} acc - {val_acc:.4f} auc - {val_auc:.4f}" )
xgb_params = {
'n_estimators': [200, 500],
'subsample': [0.6, 1.0],
'max_depth': [2,5,8],
'learning_rate': [0.1,0.01,0.02],
"min_samples_split": [2,5,10]}
xgb = GradientBoostingClassifier()
xgb_cv_model = GridSearchCV(xgb, xgb_params, cv = 10, n_jobs = -1, verbose = 2)
 xgb_cv_model.fit(x_train, y_train)
 xgb_cv_model.best_params_
xgb = GradientBoostingClassifier(learning_rate = xgb_cv_model.best_params_["learning_rate"],
max_depth = xgb_cv_model.best_params_["max_depth"],
min_samples_split = xgb_cv_model.best_params_["min_samples_split"],
n_estimators = xgb_cv_model.best_params_["n_estimators"],
subsample = xgb_cv_model.best_params_["subsample"])
 xgb_tuned = xgb.fit(x_train,y_train)
 y_pred = xgb_tuned.predict(x_test)
 acc_gbk = round(accuracy_score(y_pred, y_test)* 100, 2)
 print(acc_gbk)
<save_to_csv>
SCALING = 3.5
model_file = '.. /input/riiid-models/sakt_layer_1_head_8_embed_128_seq_150_auc_0.7605.pt'
test
ids = test['PassengerId']
predictions = xgb_tuned.predict(test.drop('PassengerId', axis=1))
output = pd.DataFrame({ 'PassengerId' : ids, 'Survived': predictions })
 output.to_csv('submission.csv', index=False)
 output.head() 
<install_modules>
env = riiideducation.make_env()
iter_test = env.iter_test()
!pip install neural-structured-learning
!pip install tensorflow-gpu==2.1.0<load_from_csv>
train_df = pd.read_parquet('.. /input/cv-strategy-in-the-kaggle-environment/cv3_train.parquet')
 train_df = train_df[TRAIN_COLS].astype(TRAIN_DTYPES)
 train_df = train_df[train_df["content_type_id"] == False]
train_df = train_df.sort_values(['timestamp'], ascending=True ).reset_index(drop = True)
 group = train_df[['user_id', 'content_id', 'answered_correctly']]\ 
.groupby('user_id' ).apply(lambda r:(
 r['content_id'].values,
r['answered_correctly'].values))
train = pd.read_csv('/kaggle/input/train.csv')
 train.head()<categorify>
%%time
model.eval()
prev_test_df = None
for(test_df, sample_prediction_df)in iter_test:
if(prev_test_df is not None)&(psutil.virtual_memory().percent<95):
prev_test_df['answered_correctly'] = eval(test_df['prior_group_answers_correct'].iloc[0])
 prev_test_df = prev_test_df[prev_test_df.content_type_id == False]
prev_group = prev_test_df[['user_id', 'content_id', 'answered_correctly']].groupby('user_id' ).apply(lambda r:(
 r['content_id'].values,
r['answered_correctly'].values))
for prev_user_id in prev_group.index:
prev_group_content = prev_group[prev_user_id][0]
prev_group_ac = prev_group[prev_user_id][1]
if prev_user_id in group.index:
group[prev_user_id] =(np.append(group[prev_user_id][0],prev_group_content),
np.append(group[prev_user_id][1],prev_group_ac))
else:
group[prev_user_id] =(prev_group_content,prev_group_ac)
 if len(group[prev_user_id][0])>MAX_SEQ:
new_group_content = group[prev_user_id][0][-MAX_SEQ:]
new_group_ac = group[prev_user_id][1][-MAX_SEQ:]
group[prev_user_id] =(new_group_content,new_group_ac)
 prev_test_df = test_df.copy()
test_df = test_df[test_df.content_type_id == False]
test_dataset = TestDataset(group, test_df, n_skill)
 test_dataloader = DataLoader(test_dataset, batch_size=25600, shuffle=False)
 outs = []
for item in test_dataloader:
x = item[0].to(device ).long()
target_id = item[1].to(device ).long()
with torch.no_grad() :
output, _ = model(x, target_id)
 output = torch.sigmoid(SCALING*output)
 output = output[:, -1]
output = 0.25 + 0.75*output
outs.extend(output.view(-1 ).data.cpu().numpy())
 test_df['answered_correctly'] = outs
env.predict(test_df.loc[test_df['content_type_id'] == 0,
['row_id', 'answered_correctly']] )
def get_labels(train):
return np.array(train['label'])
 def get_features(train):
features = train.drop(['label'], axis=1)
 features_normalized = features / 255
return features_normalized<create_dataframe>
sns.set()
sub = pd.read_csv('.. /working/submission.csv')
 sub['answered_correctly'].hist() ;
def get_generator_dict(in_gen, should_augment=True):
if should_augment:
image_gen = ImageDataGenerator(fill_mode='reflect',
data_format='channels_last',
brightness_range=[0.5, 1.5])
 else:
image_gen = ImageDataGenerator(fill_mode='reflect',
data_format='channels_last',
brightness_range=[1, 1])
 for items in in_gen:
if len(items)== 2:
in_x, in_y = items
else:
in_x, in_y, weights = items
g_x = image_gen.flow(255 * in_x, in_y, batch_size=in_x.shape[0])
 x, y = next(g_x)
 yield {'feature': x / 255.0, 'label': y}<choose_model_class>