Kaggle competition: Titanic - Machine Learning from Disaster
del X_train,y_train
gc.collect()<choose_model_class>
print("Important libraries loaded successfully" )
def LGB_bayesian(
 num_leaves,
seed, 
):
num_leaves = int(num_leaves)
 seed = int(seed)
 param = {
'objective': 'binary',
'seed': seed,
'metric': 'auc',
'learning_rate': 0.05,
'max_bin': 1000,
'num_leaves': num_leaves,
'num_iterations' : 20
}
clf = lgb.train(param, lgb_train, num_boost_round=50, valid_sets = [lgb_train, lgb_val], verbose_eval=0, early_stopping_rounds = 50)
 predictions = pd.DataFrame(clf.predict(X_test.iloc[:,1:]),index=X_test.index)
 score = roc_auc_score(y_test,predictions[0])
 return score<set_options>
ds_train=pd.read_csv("/kaggle/input/titanic/train.csv")
 ds_test=pd.read_csv("/kaggle/input/titanic/test.csv")
 ds_result=pd.read_csv("/kaggle/input/titanic/gender_submission.csv")
 print("Train and Test data sets are imported successfully" )
bounds_LGB = {
'num_leaves':(31, 500),
'seed':(0,1000)
 }
LGB_BO = BayesianOptimization(LGB_bayesian, bounds_LGB, random_state=42)
 init_points = 10
n_iter = 10
print('-' * 130)
 warnings.filterwarnings("ignore")
 with warnings.catch_warnings() :
warnings.filterwarnings('ignore')
 LGB_BO.maximize(init_points=init_points, n_iter=n_iter, acq='ucb', xi=0.0, alpha=1e-6 )<train_model>
ds_train=ds_train.drop(['Ticket','Cabin'],axis=1)
 print("Columns Dropped Successfully")
 ds_train.head()
param_lgb = {
'objective': 'binary',
'seed': int(LGB_BO.max['params']['seed']),
'metric': 'auc',
'learning_rate': 0.05,
'max_bin': 1000,
'num_leaves': int(LGB_BO.max['params']['num_leaves']),
'num_iterations' : 20
}
model = lgb.train(
 param_lgb,
lgb_train,
valid_sets=[lgb_train,lgb_val],
verbose_eval=1,
num_boost_round=100,
early_stopping_rounds=10
)<predict_on_test>
print("Number of teenagers and child passengers in ship are {}".format(len(ds_train[ds_train['Age'] < 20 ])) )
%%time
predictions = pd.DataFrame(model.predict(X_test.iloc[:,1:]),index=X_test.index)
<compute_test_metric>
ds_train=ds_train.drop(['Embarked','Name'],axis=1)
 print("Columns Dropped Successfully")
 ds_train.head()
roc_auc_score(y_test,predictions[0] )<predict_on_test>
ds_train['Family_Size'] = ds_train['SibSp'] + ds_train['Parch'] + 1
print("Family Size column created sucessfully")
 ds_train.head()
env = riiideducation.make_env()
iter_test = env.iter_test()
iter_nb = 0
for(current_df, sample_prediction_df)in iter_test:
if(iter_nb != 0):
prior_df = add_answers_to_prior_df(current_df,prior_df)
 question_df = build_question_df(prior_df,question_df)
 user_df = build_user_df(prior_df,user_df,question_df)
 prior_df = current_df.copy()
current_df = data_transform(current_df,False,False)
 current_df['answered_correctly'] = model.predict(current_df.iloc[:,1:])
 iter_nb = 1
env.predict(current_df.loc[:, ['row_id', 'answered_correctly']] )<import_modules>
age_by_pclass_sex = ds_train.groupby(['Sex', 'Pclass'] ).median() ['Age']
for pclass in range(1, 4):
for sex in ['female', 'male']:
print('Median age of Pclass {} {}s: {}'.format(pclass, sex, age_by_pclass_sex[sex][pclass]))
print('Median age of all passengers: {}'.format(ds_train['Age'].median()))
ds_train['Age'] = ds_train.groupby(['Sex', 'Pclass'])['Age'].apply(lambda x: x.fillna(x.median()))
import pandas as pd
import numpy as np
import gc
from sklearn.metrics import roc_auc_score
from collections import defaultdict
from tqdm.notebook import tqdm
import lightgbm as lgb
import riiideducation
import matplotlib.pyplot as plt
import seaborn as sns
import random
import os<feature_engineering>
ds_train=ds_train.replace(to_replace='male',value=0)
 ds_train=ds_train.replace(to_replace='female',value=1)
 ds_train.head()
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, 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
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 = pd.concat([df, user_df], axis = 1)
 return df
def update_features(df, answered_correctly_u_sum, answered_correctly_q_sum, timestamp_u_incorrect):
for row in df[['user_id', 'answered_correctly', 'content_id', 'content_type_id', 'timestamp']].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]
return
def read_and_preprocess(feature_engineering = False):
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'
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[-40000000:]
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_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']], left_on = 'content_id', right_on = 'question_id', how = 'left')
 valid = pd.merge(valid, questions_df[['question_id', 'part']], 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(lambda: defaultdict(int))
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)
 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)
 gc.collect()
print('User feature calculation completed...')
 print('
')
 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
}
return train, valid, questions_df, prior_question_elapsed_time_mean, features_dicts
def train_and_evaluate(train, valid, feature_engineering = False):
TARGET = 'answered_correctly'
FEATURES = ['prior_question_elapsed_time', 'prior_question_had_explanation', 'part', 'answered_correctly_u_avg', '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']
if feature_engineering:
train = train.sample(15000000, 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]
train.drop(drop_cols, axis = 1, inplace = True)
 valid.drop(drop_cols, axis = 1, inplace = True)
 gc.collect()
lgb_train = lgb.Dataset(train[FEATURES], y_train)
 lgb_valid = lgb.Dataset(valid[FEATURES], y_val)
 del train, y_train
gc.collect()
params = {'objective': 'binary',
'seed': SEED,
'metric': 'auc',
'num_leaves': 200,
'feature_fraction': 0.75,
'bagging_freq': 10,
'bagging_fraction': 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, model
def inference(TARGET, 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']
env = riiideducation.make_env()
iter_test = env.iter_test()
set_predict = env.predict
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)
 previous_test_df = test_df.copy()
test_df = test_df[test_df['content_type_id'] == 0].reset_index(drop = True)
 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 = pd.merge(test_df, questions_df[['question_id', 'part']], left_on = 'content_id', right_on = 'question_id', how = 'left')
 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, update = False)
 test_df[TARGET] = model.predict(test_df[FEATURES])
 set_predict(test_df[['row_id', TARGET]])
 print('Job Done')
 train, valid, questions_df, prior_question_elapsed_time_mean, features_dicts = read_and_preprocess(feature_engineering = True)
 TARGET, FEATURES, model = train_and_evaluate(train, valid, feature_engineering = True)
 inference(TARGET, FEATURES, model, questions_df, prior_question_elapsed_time_mean, features_dicts )<import_modules>
X_train=ds_train.drop(['Survived'],axis=1)
 y_train=ds_train['Survived'].values
print('X_train shape: {}'.format(X_train.shape))
print('y_train shape: {}'.format(y_train.shape))
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<define_variables>
classifier_rf=RandomForestClassifier(criterion='gini',
n_estimators=1100,
max_depth=5,
min_samples_split=4,
min_samples_leaf=5,
max_features='auto',
oob_score=True,
random_state=42,
n_jobs=-1,
verbose=1)
 classifier_rf.fit(X_train,y_train )
path = Path('/kaggle/input')
 assert path.exists()<load_from_csv>
classifier_xgb=XGBClassifier(max_depth=3, n_estimators=300, learning_rate=0.05)
 classifier_xgb.fit(X_train,y_train )
%%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()<sort_values>
age_by_pclass_sex = ds_test.groupby(['Sex', 'Pclass'] ).median() ['Age']
for pclass in range(1, 4):
for sex in ['female', 'male']:
print('Median age of Pclass {} {}s: {}'.format(pclass, sex, age_by_pclass_sex[sex][pclass]))
print('Median age of all passengers: {}'.format(ds_test['Age'].median()))
ds_test['Age'] = ds_test.groupby(['Sex', 'Pclass'])['Age'].apply(lambda x: x.fillna(x.median()))
%%time
train_df = train_df[train_df.content_type_id == False]
train_df = train_df.sort_values(['timestamp'], ascending=True ).reset_index(drop = True )<drop_column>
null_index=ds_test['Fare'].isnull().index
medianFare=ds_test['Fare'].median()
ds_test.at[null_index,'Fare'] = medianFare
print("Missing Fare updated as Median Fare :{}".format(medianFare))
del train_df['timestamp']
del train_df['content_type_id']<count_unique_values>
ds_test=ds_test.drop(['Ticket','Cabin','Embarked','Name'],axis=1)
 print("Columns Dropped Successfully")
 ds_test['Family_Size'] = ds_test['SibSp'] + ds_test['Parch'] + 1
print("Family Size column created sucessfully")
 ds_test=ds_test.replace(to_replace='male',value=0)
 ds_test=ds_test.replace(to_replace='female',value=1)
 X_test=ds_test
X_test.head()
n_skill = train_df["content_id"].nunique()
print("number skills", n_skill )<groupby>
y_pred_rf=classifier_rf.predict(X_test)
 y_pred_xgb=classifier_xgb.predict(X_test)
 y_pred_rf=y_pred_rf.ravel()
y_pred_xgb=y_pred_xgb.ravel()
submission_df_rf = pd.DataFrame(columns=['PassengerId', 'Survived'])
 submission_df_rf['PassengerId'] = X_test['PassengerId'].astype(int)
 submission_df_rf['Survived'] = y_pred_rf
submission_df_rf.to_csv('submissions_rf.csv', header=True, index=False)
 submission_df_xgb = pd.DataFrame(columns=['PassengerId', 'Survived'])
 submission_df_xgb['PassengerId'] = X_test['PassengerId'].astype(int)
 submission_df_xgb['Survived'] = y_pred_xgb
submission_df_xgb.to_csv('submissions_xgb.csv', header=True, index=False )
%%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<define_variables>
accuracies_rf = cross_val_score(estimator = classifier_rf, X = X_train, y = y_train, cv = 10)
 accuracies_xgb = cross_val_score(estimator = classifier_xgb, X = X_train, y = y_train, cv = 10 )
MAX_SEQ = 180
ACCEPTED_USER_CONTENT_SIZE = 4
EMBED_SIZE = 128
BATCH_SIZE = 64
DROPOUT = 0.1<create_dataframe>
print("Accuracies for 10 Fold in Random Forest Model is {}".format(accuracies_rf))
print("Accuracies for 10 Fold in XG Boost Model is {}".format(accuracies_xgb))
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<split>
print("Mean Accuracy for Random Forest Model is {}".format(accuracies_rf.mean()))
print("Mean Accuracy for XG Boost Model is {}".format(accuracies_xgb.mean()))
print("Standard Deviation for Random Forest Model is {}".format(accuracies_rf.std()))
print("Standard Deviation for XG Boost Model is {}".format(accuracies_xgb.std()))
TEST_SIZE = 0.1
train, val = train_test_split(group, test_size = TEST_SIZE )<create_dataframe>
param_grid = { 'bootstrap': [True],
'max_depth': [80, 90, 100, 110],
'max_features': [2, 3],
'min_samples_leaf': [3, 4, 5],
'min_samples_split': [8, 10, 12],
'n_estimators': [100, 300, 500, 1000] }
grid_search = GridSearchCV(estimator = classifier_rf, param_grid = param_grid,cv = 3, n_jobs = -1)
 grid_search = grid_search.fit(X_train, y_train )
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<create_dataframe>
best_accuracy = grid_search.best_score_
best_parameters = grid_search.best_params_
print("Best Accuracy for Random Forest Classifier is {}".format(best_accuracy))
print("Best Parameters for Random Forest Classifier is {}".format(best_parameters))
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<choose_model_class>
classifier_rf_new = RandomForestClassifier(n_estimators = 719,
bootstrap=False,
max_depth=464,
max_features=0.3,
min_samples_leaf=1,
min_samples_split=2,
random_state=42)
 classifier_rf_new.fit(X_train, y_train )
<categorify><EOS> 
print("Predicting Results from new Classifier and Converting into Submission file")
 y_pred_rf_new=classifier_rf_new.predict(X_test)
 y_pred_rf_new=y_pred_rf_new.ravel()
submission_df_rf_new = pd.DataFrame(columns=['PassengerId', 'Survived'])
 submission_df_rf_new['PassengerId'] = X_test['PassengerId'].astype(int)
 submission_df_rf_new['Survived'] = y_pred_rf_new
submission_df_rf_new.to_csv('submissions_rf_new.csv', header=True, index=False)
 print("Created Submission file from new classifier successfully" )