Kaggle competition: Riiid Answer Correctness Prediction
learn.fit_one_cycle(5, slice(1e-5, lr/5))<train_model>
import gc
import random
from tqdm.notebook import tqdm
from sklearn.metrics import roc_auc_score
from sklearn.model_selection import train_test_split
import seaborn as sns
import matplotlib.pyplot as plt
import torch
import torch.nn as nn
import torch.nn.utils.rnn as rnn_utils
from torch.autograd import Variable
from torch.utils.data import Dataset, DataLoader
from pathlib import Path
import datatable as dt
learn.fit_one_cycle(10, 1e-05, wd=0.5 )<predict_on_test>
path = Path('/kaggle/input')
 assert path.exists()
class_score , y = learn.get_preds(DatasetType.Test )<define_variables>
%%time
data_types_dict = {
'content_type_id': 'bool',
'timestamp': 'int64',
'user_id': 'int32',
'content_id': 'int16',
'answered_correctly': 'int8',
'prior_question_elapsed_time': 'float32',
'prior_question_had_explanation': 'bool'
}
target = 'answered_correctly'
train_df = dt.fread(path/'riiid-test-answer-prediction/train.csv', columns=set(data_types_dict.keys())).to_pandas()
probabilities = class_score[0].tolist()
[f"{index}: {probabilities[index]}" for index in range(len(probabilities)) ]<prepare_output>
%%time
train_df = train_df[train_df.content_type_id == False]
train_df = train_df.sort_values(['timestamp'], ascending=True ).reset_index(drop = True )
class_score = np.argmax(class_score, axis=1 )<load_from_csv>
del train_df['timestamp']
del train_df['content_type_id']
sample_submission = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv')
 sample_submission.head()<define_variables>
n_skill = train_df["content_id"].nunique()
print("number skills", n_skill )
ImageId = [os.path.splitext(path)[0] for path in os.listdir(TEST)]
ImageId = [int(path)for path in ImageId]
ImageId = [ID+1 for ID in ImageId]<save_to_csv>
%%time
group = train_df[['user_id', 'content_id', 'answered_correctly']].groupby('user_id' ).apply(lambda r:(r['content_id'].values, r['answered_correctly'].values))
del train_df
submission = pd.DataFrame({
"ImageId": ImageId,
"Label": class_score
})
 submission.to_csv("submission.csv", index=False )<load_from_csv>
MAX_SEQ = 180
ACCEPTED_USER_CONTENT_SIZE = 4
EMBED_SIZE = 128
BATCH_SIZE = 64
DROPOUT = 0.1
train_df = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')
 test_df = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')
 sample_df = pd.read_csv('/kaggle/input/digit-recognizer/sample_submission.csv' )<data_type_conversions>
class SAKTDataset(Dataset):
def __init__(self, group, n_skill, max_seq=100):
super(SAKTDataset, self ).__init__()
self.samples, self.n_skill, self.max_seq = {}, n_skill, max_seq
self.user_ids = []
for i, user_id in enumerate(group.index):
if(i % 10000 == 0):
print(f'Processed {i} users')
 content_id, answered_correctly = group[user_id]
if len(content_id)>= ACCEPTED_USER_CONTENT_SIZE:
if len(content_id)> self.max_seq:
total_questions = len(content_id)
 last_pos = total_questions // self.max_seq
for seq in range(last_pos):
index = f"{user_id}_{seq}"
self.user_ids.append(index)
 start = seq * self.max_seq
end =(seq + 1)* self.max_seq
self.samples[index] =(content_id[start:end], answered_correctly[start:end])
 if len(content_id[end:])>= ACCEPTED_USER_CONTENT_SIZE:
index = f"{user_id}_{last_pos + 1}"
self.user_ids.append(index)
 self.samples[index] =(content_id[end:], answered_correctly[end:])
 else:
index = f'{user_id}'
self.user_ids.append(index)
 self.samples[index] =(content_id, answered_correctly)
 def __len__(self):
return len(self.user_ids)
 def __getitem__(self, index):
user_id = self.user_ids[index]
content_id, answered_correctly = self.samples[user_id]
seq_len = len(content_id)
 content_id_seq = np.zeros(self.max_seq, dtype=int)
 answered_correctly_seq = np.zeros(self.max_seq, dtype=int)
 if seq_len >= self.max_seq:
content_id_seq[:] = content_id[-self.max_seq:]
answered_correctly_seq[:] = answered_correctly[-self.max_seq:]
else:
content_id_seq[-seq_len:] = content_id
answered_correctly_seq[-seq_len:] = answered_correctly
target_id = content_id_seq[1:]
label = answered_correctly_seq[1:]
x = content_id_seq[:-1].copy()
x +=(answered_correctly_seq[:-1] == 1)* self.n_skill
return x, target_id, label
class MnistDataset(Dataset):
def __init__(self, df, transforms=None, train=True):
self.train = train
self.transforms = transforms
self.X = df.loc[:, df.columns != 'label'].to_numpy(float)
 self.X = torch.from_numpy(self.X)
 if train:
self.y = df.get('label' ).to_numpy()
self.y = torch.from_numpy(self.y)
 def __len__(self):
return self.X.shape[0]
def __getitem__(self, i):
x = self.X[i].view(1, 28, 28 ).expand(3, 28, 28)
 if self.transforms: x = self.transforms(x)
 if self.train: return x, self.y[i]
return x 
<normalization>
TEST_SIZE = 0.1
train, val = train_test_split(group, test_size = TEST_SIZE )
normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],
std=[0.229, 0.224, 0.225] )<create_dataframe>
train_dataset = SAKTDataset(train, n_skill, max_seq=MAX_SEQ)
 train_dataloader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=8)
 del train
ds = MnistDataset(train_df, normalize)
 len(ds )<split>
val_dataset = SAKTDataset(val, n_skill, max_seq=MAX_SEQ)
 val_dataloader = DataLoader(val_dataset, batch_size=BATCH_SIZE, shuffle=True, num_workers=8)
 del val
val_len = int(len(ds)*0.01)
 train_len = len(ds)- val_len
train_ds, val_ds = random_split(ds, [train_len, val_len])
 len(train_ds), len(val_ds )<load_pretrained>
class FFN(nn.Module):
def __init__(self, state_size = 200, forward_expansion = 1, bn_size=MAX_SEQ - 1, dropout=0.2):
super(FFN, self ).__init__()
self.state_size = state_size
self.lr1 = nn.Linear(state_size, forward_expansion * state_size)
 self.relu = nn.ReLU()
self.bn = nn.BatchNorm1d(bn_size)
 self.lr2 = nn.Linear(forward_expansion * state_size, state_size)
 self.dropout = nn.Dropout(dropout)
 def forward(self, x):
x = self.relu(self.lr1(x))
x = self.bn(x)
 x = self.lr2(x)
 return self.dropout(x)
 FFN()
bs = 512
num_workers = 2
train_dl = DataLoader(train_ds, bs, num_workers=num_workers)
 val_dl = DataLoader(val_ds, bs, num_workers=num_workers )<choose_model_class>
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)
 future_mask(5 )
resnet18 = models.resnet18(pretrained=True)
 resnet18.fc<normalization>
class TransformerBlock(nn.Module):
def __init__(self, embed_dim, heads = 8, dropout = DROPOUT, forward_expansion = 1):
super(TransformerBlock, self ).__init__()
self.multi_att = nn.MultiheadAttention(embed_dim=embed_dim, num_heads=heads, dropout=dropout)
 self.dropout = nn.Dropout(dropout)
 self.layer_normal = nn.LayerNorm(embed_dim)
 self.ffn = FFN(embed_dim, forward_expansion = forward_expansion, dropout=dropout)
 self.layer_normal_2 = nn.LayerNorm(embed_dim)
 def forward(self, value, key, query, att_mask):
att_output, att_weight = self.multi_att(value, key, query, attn_mask=att_mask)
 att_output = self.dropout(self.layer_normal(att_output + value))
att_output = att_output.permute(1, 0, 2)
 x = self.ffn(att_output)
 x = self.dropout(self.layer_normal_2(x + att_output))
return x.squeeze(-1), att_weight
class Encoder(nn.Module):
def __init__(self, n_skill, max_seq=100, embed_dim=128, dropout = DROPOUT, forward_expansion = 1, num_layers=1, heads = 8):
super(Encoder, self ).__init__()
self.n_skill, self.embed_dim = n_skill, 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.layers = nn.ModuleList([TransformerBlock(embed_dim, forward_expansion = forward_expansion)for _ in range(num_layers)])
 self.dropout = nn.Dropout(dropout)
 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 = self.dropout(x + pos_x)
 x = x.permute(1, 0, 2)
 e = self.e_embedding(question_ids)
 e = e.permute(1, 0, 2)
 for layer in self.layers:
att_mask = future_mask(e.size(0)).to(device)
 x, att_weight = layer(e, x, x, att_mask=att_mask)
 x = x.permute(1, 0, 2)
 x = x.permute(1, 0, 2)
 return x, att_weight
class SAKTModel(nn.Module):
def __init__(self, n_skill, max_seq=100, embed_dim=128, dropout = DROPOUT, forward_expansion = 1, enc_layers=1, heads = 8):
super(SAKTModel, self ).__init__()
self.encoder = Encoder(n_skill, max_seq, embed_dim, dropout, forward_expansion, num_layers=enc_layers)
 self.pred = nn.Linear(embed_dim, 1)
 def forward(self, x, question_ids):
x, att_weight = self.encoder(x, question_ids)
 x = self.pred(x)
 return x.squeeze(-1), att_weight
lin_in = resnet18.fc.in_features
resnet18.fc = nn.Sequential(
 nn.Linear(lin_in, 10)
 )<set_options>
device = torch.device("cuda" if torch.cuda.is_available() else "cpu" )
device = torch.device('cuda:0')if torch.cuda.is_available() else 'cpu'
net = net.to(device)
 device<choose_model_class>
def create_model() :
return SAKTModel(n_skill, max_seq=MAX_SEQ, embed_dim=EMBED_SIZE, forward_expansion=1, enc_layers=1, heads=8, dropout=0.1)
 model = create_model()
model
epochs = 10
loss_fn = nn.CrossEntropyLoss()
o = optim.Adam(net.parameters() ,lr=0.001 )<create_dataframe>
model(sample_batch[0], sample_batch[1])[0]
bs = 640
test_ds = MnistDataset(test_df, normalize, train = False)
 test_dl = DataLoader(test_ds, bs )<categorify>
LR = 2e-3
EPOCHS = 10
MODEL_PATH = '/kaggle/working/sakt.pth'
outputs = []
with torch.no_grad() :
for images in test_dl:
images = images.to(device, dtype=torch.float)
 out = net(images)
 outputs.extend(out.argmax(dim=1 ).tolist() )<save_to_csv>
def do_train() :
optimizer = torch.optim.Adam(model.parameters() , lr=LR)
 criterion = nn.BCEWithLogitsLoss()
scheduler = torch.optim.lr_scheduler.OneCycleLR(optimizer, max_lr=LR,
steps_per_epoch=len(train_dataloader), epochs=EPOCHS)
 model.to(device)
 criterion.to(device)
 best_auc = 0.0
for epoch in range(EPOCHS):
train_epoch(model, train_dataloader, optimizer, criterion, scheduler, device)
 val_loss, avl_acc, val_auc = val_epoch(model, val_dataloader, criterion, device)
 print(f"epoch - {epoch + 1} val_loss - {val_loss:.3f} acc - {avl_acc:.3f} auc - {val_auc:.3f}")
 if best_auc < val_auc:
print(f'epoch - {epoch + 1} best model with val auc: {val_auc}')
 best_auc = val_auc
torch.save(model.state_dict() , MODEL_PATH )
sample_df['Label'] = outputs
sample_df.to_csv('submission.csv', index=False )<set_options>
do_train()
%matplotlib inline
py.init_notebook_mode(connected=True)
 warnings.filterwarnings('ignore' )<import_modules>
LR = 2e-4
EPOCHS = 3
do_train()
from sklearn.model_selection import GridSearchCV, train_test_split
from sklearn.metrics import classification_report, confusion_matrix
from sklearn.linear_model import LogisticRegression
from sklearn.neighbors import KNeighborsClassifier
from sklearn.svm import SVC
from sklearn.tree import DecisionTreeClassifier
from sklearn.ensemble import RandomForestClassifier, AdaBoostClassifier, GradientBoostingClassifier
from xgboost import XGBClassifier<load_from_csv>
model = create_model()
model.load_state_dict(torch.load(MODEL_PATH))
model.to(device )
train_df = pd.read_csv('.. /input/titanic/train.csv')
 print(train_df.shape)
 train_df.head()<load_from_csv>
env = riiideducation.make_env()
iter_test = env.iter_test()
test_df = pd.read_csv('.. /input/titanic/test.csv')
 print(test_df.shape)
 test_df.head()<define_variables>
model.eval()
prev_test_df = None
for(test_df, sample_prediction_df)in tqdm(iter_test):
if(prev_test_df is not None)&(psutil.virtual_memory().percent<90):
print(psutil.virtual_memory().percent)
 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_answered_correctly = 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_answered_correctly))
else:
group[prev_user_id] =(prev_group_content, prev_group_answered_correctly)
 if len(group[prev_user_id][0])> MAX_SEQ:
new_group_content = group[prev_user_id][0][-MAX_SEQ:]
new_group_answered_correctly = group[prev_user_id][1][-MAX_SEQ:]
group[prev_user_id] =(new_group_content, new_group_answered_correctly)
 prev_test_df = test_df.copy()
test_df = test_df[test_df.content_type_id == False]
test_dataset = TestDataset(group, test_df, n_skill, max_seq=MAX_SEQ)
 test_dataloader = DataLoader(test_dataset, batch_size=len(test_df), shuffle=False)
 item = next(iter(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(output)
 output = output[:, -1]
test_df['answered_correctly'] = output.cpu().numpy()
env.predict(test_df.loc[test_df['content_type_id'] == 0, ['row_id', 'answered_correctly']] )
df = [train_df, test_df]<feature_engineering>
test_dataset = TestDataset(group, test_df, n_skill, max_seq=MAX_SEQ )
<categorify><EOS> 
group.to_pickle('/kaggle/working/group.pkl' )