Kaggle competition: Digit Recognizer
skills = joblib.load("/kaggle/input/skills-pkl/skills.pkl.zip")
 n_skill = len(skills)
 group = joblib.load("/kaggle/input/group-pkl/group.pkl.zip")
 del joblib
gc.collect()<define_variables>
np.random.seed(1)
MAX_SEQ = 180
ACCEPTED_USER_CONTENT_SIZE = 4
EMBED_SIZE = 128
BATCH_SIZE = 64
DROPOUT = 0.1<choose_model_class>
X_train = pd.read_csv('/kaggle/input/digit-recognizer/train.csv')
 X_test = pd.read_csv('/kaggle/input/digit-recognizer/test.csv')
 print('Shape of the training data: ', X_train.shape)
 print('Shape of the test data: ', X_test.shape )
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()<categorify>
y_train = X_train['label']
X_train.drop(labels = ['label'], axis=1, inplace=True )
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 )<choose_model_class>
y_train = to_categorical(y_train, num_classes=10)
 X_train, X_val, y_train, y_val = train_test_split(X_train, y_train, test_size = 0.1 )
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<set_options>
model = Sequential()
model.add(Conv2D(filters = 32, kernel_size =(5,5),padding = 'Same',
activation ='relu', input_shape =(28,28,1)))
 model.add(Conv2D(filters = 64, kernel_size =(5,5),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2)))
 model.add(Dropout(0.25))
model.add(Conv2D(filters = 128, kernel_size =(3,3),padding = 'Same',
activation ='relu'))
model.add(Conv2D(filters = 256, kernel_size =(3,3),padding = 'Same',
activation ='relu'))
model.add(MaxPool2D(pool_size=(2,2), strides=(2,2)))
 model.add(Dropout(0.25))
model.add(Flatten())
 model.add(Dense(256, activation = "relu"))
model.add(Dropout(0.5))
model.add(Dense(10, activation = "softmax"))
model.summary()
del pickle
gc.collect()<set_options>
optimizer = Adam(learning_rate=0.001, epsilon=1e-07)
 model.compile(optimizer = optimizer, loss = 'categorical_crossentropy', metrics=['accuracy'])
 earlyStopping = EarlyStopping(monitor='val_accuracy', patience=10, verbose=0, mode='auto')
 mcp = ModelCheckpoint('.mdl_wts.hdf5', save_best_only=True, monitor='val_accuracy', mode='auto')
 reduce_lr_loss = ReduceLROnPlateau(monitor='val_accuracy', factor=0.1, patience=7, verbose=1, epsilon=1e-4, mode='auto')
torch.cuda.is_available()<set_options>
datagen = ImageDataGenerator(
 rotation_range=5,
width_shift_range=0.1,
height_shift_range=0.1,
shear_range=5,
zoom_range=0.1)
 datagen.fit(X_train )
device = torch.device("cuda" if torch.cuda.is_available() else "cpu" )<choose_model_class>
history = model.fit_generator(datagen.flow(X_train, y_train, batch_size=64),
epochs = 100,
validation_data =(X_val,y_val),
verbose = 1,
steps_per_epoch=X_train.shape[0]//64,
callbacks = [earlyStopping, mcp, reduce_lr_loss] )
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 )<load_pretrained>
model.load_weights(filepath = '.mdl_wts.hdf5' )
model_attention = create_model()
try:
model_attention.load_state_dict(torch.load("/kaggle/input/attention/attention.pth"))
except:
model_attention.load_state_dict(torch.load("/kaggle/input/attention/attention.pth", map_location='cpu'))
model_attention.to(device )<split>
scores = model.evaluate(X_val, y_val, callbacks = [earlyStopping, mcp, reduce_lr_loss] )
env = riiideducation.make_env()
iter_test = env.iter_test()
prior_test_df = None
prev_test_df = None<feature_engineering>
img_tensor = X_test[5].reshape(-1, 28, 28, 1 )
%%time
model_attention.eval()
for(test_df, sample_prediction_df)in(iter_test):
if(prev_test_df is not None)&(psutil.virtual_memory().percent < 95):
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_attention = test_df.copy()
test_df_attention = test_df_attention[test_df_attention.content_type_id == False]
test_dataset = TestDataset(group, test_df_attention, n_skill, max_seq=MAX_SEQ)
 test_dataloader = DataLoader(test_dataset, batch_size=len(test_df_attention), shuffle=False)
 attention_predictions = []
item = next(iter(test_dataloader))
x = item[0].to(device ).long()
target_id = item[1].to(device ).long()
with torch.no_grad() :
output, _ = model_attention(x, target_id)
 output = torch.sigmoid(output)
 output = output[:, -1]
attention_predictions.extend(output.cpu().numpy())
 if prior_test_df is not None:
prior_test_df[target] = eval(test_df['prior_group_answers_correct'].iloc[0])
 prior_test_df_lecture = prior_test_df[prior_test_df[target] == -1].reset_index(drop=True)
 if len(prior_test_df_lecture)> 0:
prior_test_df_lecture = pd.merge(prior_test_df_lecture, lectures_df, left_on='content_id', right_on='lecture_id', how='left')
 user_ids = prior_test_df_lecture['user_id'].values
lecture_tags = prior_test_df_lecture['tag'].values
for user_id, lecture_tag in zip(user_ids, lecture_tags):
user_lectures_count_dict[user_id] += 1
last_lecture_tag_dict[user_id] = lecture_tag
prior_test_df = prior_test_df[prior_test_df[target] != -1].reset_index(drop=True)
 user_ids = prior_test_df['user_id'].values
content_ids = prior_test_df['content_id'].values
targets = prior_test_df[target].values
prior_explanations = prior_test_df['prior_question_had_explanation'].values
prior_question_times = prior_test_df['prior_question_elapsed_time'].values
tags = prior_test_df['first_tag'].values
timestamps = prior_test_df['timestamp'].values
timestamp_diffs = prior_test_df['timestamp_diff_last'].values
for user_id, content_id, answered_correctly, explanation, prior_question_time, tag, timestamp, timestamp_diff in zip(user_ids, content_ids, targets, prior_explanations, prior_question_times, tags, timestamps, timestamp_diffs):
if answered_correctly != 1:
answered_correctly = 0
user_sum_dict[user_id] += answered_correctly
user_count_dict[user_id] += 1
content_sum_dict[content_id] += answered_correctly
content_count_dict[content_id] += 1
explanation_sum_dict[user_id] += explanation
explanation_count_dict[user_id] += 1
last_correct_dict[user_id] = answered_correctly
prior_questions_time_sum_dict[user_id] += prior_question_time
prior_questions_time_count_dict[user_id] += 1
user_tag_agg_sum_dict[user_id, tag] += answered_correctly
user_tag_agg_count_dict[user_id, tag] += 1
last_timestamp_dict[user_id] = timestamp
user_content_id = str(user_id)+ str(content_id)
 user_content_id_count_dict[user_content_id] += 1
change_next_out = True
if(user_id, 9)not in user_target_window_10_dict:
for k in range(10):
if(user_id, k)not in user_target_window_10_dict:
user_target_window_10_dict[user_id, k] = answered_correctly
change_next_out = False
break
if change_next_out:
next_out = user_target_next_out_window_10_dict[user_id]
user_target_window_10_dict[user_id, next_out] = answered_correctly
next_out += 1
if next_out > 9:
next_out = 0
user_target_next_out_window_10_dict[user_id] = next_out
else:
user_target_next_out_window_10_dict[user_id] = 0
change_next_out = True
if(user_id, 9)not in timestamp_diff_window_10_dict:
for k in range(10):
if(user_id, k)not in timestamp_diff_window_10_dict:
timestamp_diff_window_10_dict[user_id, k] = timestamp_diff
change_next_out = False
break
if change_next_out:
next_out = timestamp_diff_next_window_10_dict[user_id]
timestamp_diff_window_10_dict[user_id, next_out] = timestamp_diff
next_out += 1
if next_out > 9:
next_out = 0
timestamp_diff_next_window_10_dict[user_id] = next_out
else:
timestamp_diff_next_window_10_dict[user_id] = 0
test_df['content_id'] = test_df['content_id'].astype('int16')
 test_df['prior_question_elapsed_time'] = test_df['prior_question_elapsed_time'].apply(lambda x: x/1000)
 test_df['prior_question_elapsed_time'].fillna(25, inplace=True)
 test_df['prior_question_elapsed_time'] = test_df['prior_question_elapsed_time'].astype('int16')
 test_df['prior_question_had_explanation'] = test_df['prior_question_had_explanation'].fillna(False ).astype(int)
 test_df['timestamp'] = test_df['timestamp'].apply(lambda x: x/1000 ).astype('int32')
 prior_test_df = test_df.copy()
prior_test_df['first_tag'] = 0
prior_test_df['timestamp_diff_last'] = 0
test_df = test_df[test_df['content_type_id'] == 0].reset_index(drop=True)
 test_df = pd.merge(test_df, questions_df, left_on='content_id', right_on='question_id', how='left')
 prior_test_df.loc[prior_test_df['content_type_id'] == 0,'first_tag'] = test_df['first_tag'].values
user_sum = np.zeros(len(test_df), dtype=np.int32)
 user_count = np.zeros(len(test_df), dtype=np.int32)
 content_sum = np.zeros(len(test_df), dtype=np.int32)
 content_count = np.zeros(len(test_df), dtype=np.int32)
 user_content_id_count = np.zeros(len(test_df), dtype=np.int16)
 user_target_window_10_array = np.zeros(len(test_df))
timestamp_diff_window_10_array = np.zeros(len(test_df))
explanation_sum = np.zeros(len(test_df), dtype=np.int32)
 explanation_count = np.zeros(len(test_df), dtype=np.int32)
 user_lectures_count = np.zeros(len(test_df), dtype=np.int16)
 last_lecture_tag_array = np.zeros(len(test_df), dtype=np.int16)
 prior_questions_time_sum = np.zeros(len(test_df), dtype=np.int32)
 prior_questions_time_count = np.zeros(len(test_df), dtype=np.int32)
 last_correct_array = np.zeros(len(test_df), dtype=np.int8)
 user_tag_sum = np.zeros(len(test_df), dtype=np.int16)
 user_tag_count = np.zeros(len(test_df), dtype=np.int16)
 last_timestamp_array = np.zeros(len(test_df), dtype=np.int32)
 for i,(user_id, content_id, tag)in enumerate(zip(test_df['user_id'].values, test_df['content_id'].values, test_df['first_tag'].values)) :
user_sum[i] = user_sum_dict[user_id]
user_count[i] = user_count_dict[user_id]
content_sum[i] = content_sum_dict[content_id]
content_count[i] = content_count_dict[content_id]
explanation_sum[i] = explanation_sum_dict[user_id]
explanation_count[i] = explanation_count_dict[user_id]
user_tag_sum[i] = user_tag_agg_sum_dict[user_id, tag]
user_tag_count[i] = user_tag_agg_count_dict[user_id, tag]
last_timestamp_array[i] = last_timestamp_dict[user_id]
if(user_id)in last_lecture_tag_dict:
last_lecture_tag_array[i] = last_lecture_tag_dict[user_id]
else:
last_lecture_tag_array[i] = -9
if(user_id)in prior_questions_time_sum_dict:
prior_questions_time_sum[i] = prior_questions_time_sum_dict[user_id]
prior_questions_time_count[i] = prior_questions_time_count_dict[user_id]
else:
prior_questions_time_sum[i] = 0
prior_questions_time_count[i] = 0
if(user_id)in last_correct_dict:
last_correct_array[i] = last_correct_dict[user_id]
else:
last_correct_array[i] = -1
user_content_id = str(user_id)+ str(content_id)
 user_content_id_count[i] = user_content_id_count_dict[user_content_id]
user_target_10 = 0
for k in range(10):
if(user_id, k)in user_target_window_10_dict:
user_target_10 += user_target_window_10_dict[user_id, k]
else:
k -= 1
break
if k >= 0:
user_target_window_10_array[i] = user_target_10 /(k + 1)
 else:
user_target_window_10_array[i] = -1
timestamp_diff_10 = 0
for k in range(10):
if(user_id, k)in timestamp_diff_window_10_dict:
timestamp_diff_10 += timestamp_diff_window_10_dict[user_id, k]
else:
k -= 1
break
if k >= 0:
timestamp_diff_window_10_array[i] = timestamp_diff_10 /(k + 1)
 else:
timestamp_diff_window_10_array[i] = -1
test_df['timestamp_diff_last'] = test_df['timestamp'].values - last_timestamp_array
test_df['timestamp_diff_last'] = test_df['timestamp_diff_last'].astype('int32')
 prior_test_df.loc[prior_test_df['content_type_id'] == 0,'timestamp_diff_last'] = test_df['timestamp_diff_last'].values
test_df['last_correct'] = last_correct_array
test_df['last_correct'].fillna(-1, inplace=True)
 test_df['last_correct'] = test_df['last_correct'].astype('int8')
 test_df['task_container_id'] = test_df['task_container_id'].astype('int16')
 test_df['prior_questions_mean_time'] =(prior_questions_time_sum + test_df['prior_question_elapsed_time'].values)/(prior_questions_time_count + 1)
 test_df['prior_questions_mean_time'].fillna(25, inplace=True)
 test_df['prior_questions_mean_time'] = test_df['prior_questions_mean_time'].astype('int16')
 test_df['last_lecture_tag'] = last_lecture_tag_array
test_df['last_lecture_tag'].fillna(-9, inplace=True)
 test_df['last_lecture_tag'] = test_df['last_lecture_tag'].astype('int16')
 test_df['user_count_lectures'] = user_lectures_count
test_df['user_count_lectures'] = test_df['user_count_lectures'].astype('int16')
 test_df['user_correctness'] = user_sum / user_count
test_df['content_id_correctness_total'] = content_sum / content_count
test_df['user_correctness'].fillna(-1, inplace=True)
 test_df['user_correctness'] = test_df['user_correctness'].astype('float32')
 test_df['content_id_correctness_total'].fillna(0.600382459, inplace=True)
 test_df['content_id_correctness_total'] = test_df['content_id_correctness_total'].astype('float32')
 test_df['user_count_questions'] = user_count
test_df['user_count_questions'].fillna(0, inplace=True)
 test_df['user_count_questions'] = test_df['user_count_questions'].astype('int32')
 test_df['explanation_mean_user'] =(explanation_sum + test_df['prior_question_had_explanation'].values)/(explanation_count + 1)
 test_df['explanation_mean_user'].fillna(0, inplace=True)
 test_df['explanation_mean_user'] = test_df['explanation_mean_user'].astype('float32')
 test_df['content_count'] = content_count
test_df['content_sum'] = content_sum
test_df['repeated_times'] = user_content_id_count
test_df['repeated_times'] = test_df['repeated_times'].astype('int16')
 test_df['repeated_times_tag'] = user_tag_count
test_df['repeated_times_tag'] = test_df['repeated_times_tag'].astype('int16')
 test_df['user_tag_correctness'] = user_tag_sum / user_tag_count
test_df['user_tag_correctness'].fillna(-1, inplace=True)
 test_df['user_tag_correctness'] = test_df['user_tag_correctness'].astype('float32')
 test_df['user_correctness_window_10_mean'] = user_target_window_10_array
test_df['user_correctness_window_10_mean'].fillna(-1, inplace=True)
 test_df['user_correctness_window_10_mean'] = test_df['user_correctness_window_10_mean'].astype('float32')
 test_df['timestamp_diff_last_window_10_mean'] = timestamp_diff_window_10_array
test_df['timestamp_diff_last_window_10_mean'].fillna(-1, inplace=True)
 test_df['timestamp_diff_last_window_10_mean'] = test_df['timestamp_diff_last_window_10_mean'].astype('int32')
 test_df['user_count_lectures_mean'] = test_df['user_count_lectures'] / test_df['user_count_questions']
test_df['user_count_lectures_mean'].fillna(0, inplace=True)
 test_df['user_count_lectures_mean'] = test_df['user_count_lectures_mean'].astype('float32')
 lgbm_predictions = model.predict(test_df[features])
 test_df[target] = 0.2 * np.array(attention_predictions)+ 0.8 * lgbm_predictions
env.predict(test_df[['row_id', target]])
<import_modules>
for layer in model.layers:
if'conv' in layer.name:
filters, biases = layer.get_weights()
print('Layer: ', layer.name, filters.shape)
 f_min, f_max = filters.min() , filters.max()
filters =(filters - f_min)/(f_max - f_min)
 print('Filter size:(', filters.shape[0], ',', filters.shape[1], ')')
 print('Channels in this layer: ', filters.shape[2])
 print('Number of filters: ', filters.shape[3])
 count = 1
plt.figure(figsize =(18, 4))
for i in range(filters.shape[3]):
ax= plt.subplot(4, filters.shape[3]/4, count)
 ax.set_xticks([])
 ax.set_yticks([])
 plt.imshow(filters[:,:,0, i], cmap=plt.cm.binary)
 count+=1
plt.show()
for dirname, _, filenames in os.walk('/kaggle/input'):
for filename in filenames:
print(os.path.join(dirname, filename)) 
<define_variables>
layer_outputs = [layer.output for layer in model.layers[0:8]]
activation_model = models.Model(inputs = model.input, outputs = layer_outputs )
path = Path('/kaggle/input')
 assert path.exists()<data_type_conversions>
activations = activation_model.predict(img_tensor )
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, update=True):
answered_correctly_u_avg = np.zeros(len(df), dtype = np.float32)
 elapsed_time_u_avg = np.zeros(len(df), dtype = np.float32)
 explanation_u_avg = np.zeros(len(df), dtype = np.float32)
 timestamp_u_recency_1 = np.zeros(len(df), dtype = np.float32)
 timestamp_u_recency_2 = np.zeros(len(df), dtype = np.float32)
 timestamp_u_recency_3 = np.zeros(len(df), dtype = np.float32)
 timestamp_u_incorrect_recency = np.zeros(len(df), dtype = np.float32)
 answered_correctly_q_avg = np.zeros(len(df), dtype = np.float32)
 elapsed_time_q_avg = np.zeros(len(df), dtype = np.float32)
 explanation_q_avg = np.zeros(len(df), dtype = np.float32)
 answered_correctly_uq_count = np.zeros(len(df), dtype = np.int32)
 for num, row in enumerate(df[['user_id', 'answered_correctly', 'content_id', 'prior_question_elapsed_time', 'prior_question_had_explanation', 'timestamp']].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] = np.nan
elapsed_time_u_avg[num] = np.nan
explanation_u_avg[num] = np.nan
print(timestamp_u[row[0]])
 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]]
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
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]
user_df = pd.DataFrame({'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})
 df.reset_index(drop=True, inplace=True)
 user_df.reset_index(drop=True, inplace=True)
 df = pd.concat([df, user_df], axis=1)
 return df 
<feature_engineering>
results = np.argmax(model.predict(X_test), axis=1)
 results = pd.Series(results, name = "Label")
 results.head(2 )
<load_from_csv><EOS> 
submission.to_csv("CNN_MNIST_results.csv",index=False )