{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Riiid! Answer Correctness Prediction\n\nTailoring education to a student's ability level is one of the many valuable things an AI tutor can do. Your challenge in this competition is a version of that overall task; you will predict whether students are able to answer their next questions correctly. You'll be provided with the same sorts of information a complete education app would have: that student's historic performance, the performance of other students on the same question, metadata about the question itself, and more.\n\n\n## Files\n### train.csv\n\nrow_id: (int64) ID code for the row.\n\ntimestamp: (int64) the time between this user interaction and the first event completion from that user.\n\nuser_id: (int32) ID code for the user.\n\ncontent_id: (int16) ID code for the user interaction\n\ncontent_type_id: (int8) 0 if the event was a question being posed to the user, 1 if the event was the user watching a lecture.\n\ntask_container_id: (int16) Id code for the batch of questions or lectures. For example, a user might see three questions in a row before seeing the explanations for any of them. Those three would all share a task_container_id.\n\nuser_answer: (int8) the user's answer to the question, if any. Read -1 as null, for lectures.\n\nanswered_correctly: (int8) if the user responded correctly. Read -1 as null, for lectures.\n\nprior_question_elapsed_time: (float32) The average time it took a user to answer each question in the previous question bundle, ignoring any lectures in between. Is null for a user's first question bundle or lecture. Note that the time is the average time a user took to solve each question in the previous bundle.\n\nprior_question_had_explanation: (bool) Whether or not the user saw an explanation and the correct response(s) after answering the previous question bundle, ignoring any lectures in between. The value is shared across a single question bundle, and is null for a user's first question bundle or lecture. Typically the first several questions a user sees were part of an onboarding diagnostic test where they did not get any feedback.\n\n### questions.csv: metadata for the questions posed to users.\n\nquestion_id: foreign key for the train/test content_id column, when the content type is question (0).\n\nbundle_id: code for which questions are served together.\n\ncorrect_answer: the answer to the question. Can be compared with the train user_answer column to check if the user was right.\n\npart: the relevant section of the TOEIC test.\n\ntags: one or more detailed tag codes for the question. The meaning of the tags will not be provided, but these codes are sufficient for clustering the questions together.\n\n### lectures.csv: metadata for the lectures watched by users as they progress in their education.\n\nlecture_id: foreign key for the train/test content_id column, when the content type is lecture (1).\n\npart: top level category code for the lecture.\n\ntag: one tag codes for the lecture. The meaning of the tags will not be provided, but these codes are sufficient for clustering the lectures together.\n\ntype_of: brief description of the core purpose of the lecture\n\nexample_test_rows.csv Three sample groups of the test set data as it will be delivered by the time-series API. The format is largely the same as train.csv. There are two different columns that mirror what information the AI tutor actually has available at any given time, but with the user interactions grouped together for the sake of API performance rather than strictly showing information for a single user at a time. Some questions will appear in the hidden test set that have NOT been presented in the train set, emulating the challenge of quickly adapting to modeling newly introduced questions. Their metadata is still in question.csv as usual.\n\nprior_group_responses (string) provides all of the user_answer entries for previous group in a string representation of a list in the first row of the group. All other rows in each group are null. If you are using Python, you will likely want to call eval on the non-null rows. Some rows may be null, or empty lists.\n\nprior_group_answers_correct (string) provides all the answered_correctly field for previous group, with the same format and caveats as prior_group_responses. Some rows may be null, or empty lists."},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 5GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_types_dict = {\n    'row_id': 'int64',\n    'timestamp': 'int64',\n    'user_id': 'int32',\n    'content_id': 'int16',\n    'content_type_id': 'int8',\n#     'task_container_id': 'int16',\n#     'user_answer': 'int8',\n    'answered_correctly': 'int8',\n    'prior_question_elapsed_time': 'float16',\n    'prior_question_had_explanation': 'boolean'\n}\n\nsample_size = (10**6)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('../input/riiid-test-answer-prediction/train.csv', nrows=sample_size, \n                    index_col='row_id', usecols = data_types_dict.keys(),\n                    dtype=data_types_dict)\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lecture = pd.read_csv('../input/riiid-test-answer-prediction/lectures.csv')\nlecture.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"question = pd.read_csv('../input/riiid-test-answer-prediction/questions.csv')\nquestion.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test = pd.read_csv('../input/riiid-test-answer-prediction/example_test.csv', index_col='row_id')\ntest.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"submission = pd.read_csv('../input/riiid-test-answer-prediction/example_sample_submission.csv', index_col='row_id')\nsubmission.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f'train shape: {train.shape}')\nprint(f'lecture shape: {lecture.shape}')\nprint(f'question shape: {question.shape}')\nprint(f'test shape: {test.shape}')\nprint(f'submission shape: {submission.shape}')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Feature Engineering"},{"metadata":{},"cell_type":"markdown","source":"### **Expanding on Simple LGBM** \n\nref: https://www.kaggle.com/thebigd8ta/lgbm-ii"},{"metadata":{"trusted":true},"cell_type":"code","source":"train = train[train.answered_correctly != -1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"user_group = train.groupby('user_id')\nuser_answers = user_group.agg({'answered_correctly': ['mean', 'count'],'timestamp': ['mean']})\nuser_answers.columns = ['mean_user_accuracy', 'questions_answered', 'mean_user_time']\nuser_answers.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"content_group = train.groupby('content_id')\ncontent_answer = content_group.agg({'answered_correctly': ['mean', 'count'],'timestamp': ['mean']})\ncontent_answer.columns = ['mean_content_accuracy', 'question_asked', 'mean_content_time']\ncontent_answer.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"questions = question.merge(content_answer, left_on = 'question_id', right_on = 'content_id', how = 'left')\nbundle_dict = questions['bundle_id'].value_counts().to_dict()\nquestions['right_answers'] = questions['mean_content_accuracy'] * questions['question_asked']\nquestions['bundle_size'] =questions['bundle_id'].apply(lambda x: bundle_dict[x])\nquestions.tail()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"grouped_by_bundle = questions.groupby('bundle_id')\nbundle_answers = grouped_by_bundle.agg({'right_answers': 'sum', 'question_asked': 'sum'})\nbundle_answers.columns = ['bundle_rignt_answers', 'bundle_questions_asked']\nbundle_answers['bundle_accuracy'] = bundle_answers['bundle_rignt_answers'] / bundle_answers['bundle_questions_asked']\nbundle_answers.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"grouped_by_part = questions.groupby('part')\npart_answers = grouped_by_part.agg({'right_answers': 'sum', 'question_asked': 'sum'})\npart_answers.columns = ['part_rignt_answers', 'part_questions_asked']\npart_answers['part_accuracy'] = part_answers['part_rignt_answers'] / part_answers['part_questions_asked']\npart_answers.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_train_df = train.merge(user_answers, how = 'left', on = 'user_id')\\\n                        .merge(questions, how = 'left', left_on = 'content_id', right_on = 'question_id')\\\n                        .merge(bundle_answers, how = 'left', on = 'bundle_id')\\\n                        .merge(part_answers, how = 'left', on = 'part')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_train_df['prior_question_had_explanation'].fillna(False, inplace=True)\nnew_train_df['prior_question_had_explanation'] = new_train_df['prior_question_had_explanation'].apply(lambda x: 1 if x=='True' else 0)\nnew_train_df[new_train_df==np.inf]=np.nan\nnew_train_df.fillna(value = -1, inplace = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_train_df.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Split Data into train&validation set"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"features = ['timestamp', 'content_type_id', 'prior_question_had_explanation', \n       'prior_question_elapsed_time', \n       'correct_answer', 'part',\n       'mean_content_accuracy', 'question_asked', 'mean_content_time',\n       'right_answers', 'bundle_size', 'bundle_rignt_answers',\n       'bundle_questions_asked', 'bundle_accuracy', 'part_rignt_answers',\n       'part_questions_asked', 'part_accuracy']\n# 'user_answer', 'prior_question_had_explanation_True', 'mean_user_accuracy', 'questions_answered', 'mean_user_time'\ntarget = 'answered_correctly'\n\nX = new_train_df[features]\ny = new_train_df[target]\n\nX_train, X_val, y_train, y_val = train_test_split(X, y, train_size=0.8, random_state=111)\nX_train.shape, X_val.shape, y_train.shape, y_val.shape","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Modeling"},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import GridSearchCV\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.ensemble import RandomForestClassifier\nfrom xgboost import XGBClassifier\nfrom lightgbm import LGBMClassifier","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"class model_selection(): \n    def __init__(self): \n        self.y_pred_FVC = pd.DataFrame()\n        self.best_param = None\n        self.scoring_train = 0\n        self.scoring_val = 0\n        \n        \n    def LogisticRegression(self, X, y, X_val, y_val): \n        params_logr = {'C': [1], 'solver': ['lbfgs'], 'max_iter': [100]}\n        clf = GridSearchCV(LogisticRegression(), \n                           param_grid=params_logr, scoring='roc_auc')\n        clf.fit(X, y)\n        self.best_param = clf.best_params_\n        self.scoring_train = clf.score(X, y)\n#         self.scoring_val = clf.score(X_val, y_val)\n        y_pred_logr_FVC = clf.predict_proba(X_val)\n\n        self.y_pred_FVC = pd.concat([pd.Series(y_pred_logr_FVC[:, 1])], axis=1)\n        return self.best_param, self.y_pred_FVC, self.scoring_train, self.scoring_val\n    \n    \n    def SVM(self, X, y, X_val, y_val): \n        params_svm = {'C': [1], 'kernel': ['rbf']}\n        clf = GridSearchCV(SVC(probability=True), \n                           param_grid=params_svm, scoring='roc_auc')\n        clf.fit(X, y)\n        self.best_param = clf.best_params_\n        self.scoring_train = clf.score(X, y)\n#         self.scoring_val = clf.score(X_val, y_val)\n        y_pred_svm_FVC = clf.predict_proba(X_val)\n\n        self.y_pred_FVC = pd.concat([pd.Series(y_pred_svm_FVC[:, 1])], axis=1)\n        return self.best_param, self.y_pred_FVC, self.scoring_train, self.scoring_val\n    \n    \n    def RandomForest(self, X, y, X_val, y_val): \n        params_rf = {'n_estimators': [100], 'criterion': ['gini']}\n        clf = GridSearchCV(RandomForestClassifier(), \n                           param_grid=params_rf, scoring='roc_auc')\n        clf.fit(X, y)\n        self.best_param = clf.best_params_\n        self.scoring_train = clf.score(X, y)\n#         self.scoring_val = clf.score(X_val, y_val)\n        y_pred_rf_FVC = clf.predict_proba(X_val)\n\n        self.y_pred_FVC = pd.concat([pd.Series(y_pred_rf_FVC[:, 1])], axis=1)\n        return self.best_param, self.y_pred_FVC, self.scoring_train, self.scoring_val\n    \n    \n    def XGBoost(self, X, y, X_val, y_val): \n        params_xgb = {'max_depth':[6]}\n        clf = GridSearchCV(XGBClassifier(), \n                           param_grid=params_xgb, scoring='roc_auc')\n        clf.fit(X, y)\n        self.best_param = clf.best_params_\n        self.scoring_train = clf.score(X, y)\n#         self.scoring_val = clf.score(X_val, y_val)\n        y_pred_xgb_FVC = clf.predict_proba(X_val)\n\n        self.y_pred_FVC = pd.concat([pd.Series(y_pred_xgb_FVC[:, 1])], axis=1)\n        return self.best_param, self.y_pred_FVC, self.scoring_train, self.scoring_val\n    \n\n    def LightGBM(self, X, y, X_val, y_val): \n        params_lgb = {'n_estimators':[100], 'num_iterations': [100, 300], 'learning_rate':[0.05, 0.1]}\n        clf = GridSearchCV(LGBMClassifier(), \n                           param_grid=params_lgb, scoring='roc_auc')\n        clf.fit(X, y)\n        self.best_param = clf.best_params_\n        self.scoring_train = clf.score(X, y)\n#         self.scoring_val = clf.score(X_val, y_val)\n        y_pred_lgb_FVC = clf.predict_proba(X_val)\n        \n        self.y_pred_FVC = pd.concat([pd.Series(y_pred_lgb_FVC[:, 1])], axis=1)\n        return self.best_param, self.y_pred_FVC, self.scoring_train, self.scoring_val","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model_sel = model_selection()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Random Forest"},{"metadata":{"trusted":true},"cell_type":"code","source":"# rf = model_sel.RandomForest(X_train, y_train, X_val, y_val)\n# rf","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Logistic Regression"},{"metadata":{"trusted":true},"cell_type":"code","source":"# logr = model_sel.LogisticRegression(X_train, y_train, X_val, y_val)\n# logr","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Support Vector Machine"},{"metadata":{"trusted":true},"cell_type":"code","source":"# svm = model_sel.SVM(X_train, y_train, X_val, y_val)\n# svm","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### XGBoost"},{"metadata":{"trusted":true},"cell_type":"code","source":"# xgb = model_sel.XGBoost(X_train, y_train, X_val, y_val)\n# xgb","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### LightGBM"},{"metadata":{"trusted":true},"cell_type":"code","source":"lgb = model_sel.LightGBM(X_train, y_train, X_val, y_val)\nlgb","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = LGBMClassifier(**lgb[0])\nmodel.fit(X_train, y_train)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Evaluation"},{"metadata":{"trusted":true},"cell_type":"code","source":"# # plot AUC\n# results = lgb.evals_result_ # evals_result()\n# epochs = len(results['auc'])\n# x_axis = range(0, epochs)\n# fig, ax = plt.subplots(figsize=(8,5))\n# ax.plot(x_axis, results['auc'], label='Train')\n# ax.plot(x_axis, results['auc'], label='Test')\n# ax.legend()\n# plt.ylabel('AUC')\n# plt.title('XGBoost AUC')\n# plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import riiideducation","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"env = riiideducation.make_env()\niter_test = env.iter_test()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for (test_df, sample_prediction_df) in iter_test:\n    test_df = test_df.merge(user_answers, how = 'left', on = 'user_id')\n    test_df = test_df.merge(questions, how = 'left', left_on = 'content_id', right_on = 'question_id')\n    test_df = test_df.merge(bundle_answers, how = 'left', on = 'bundle_id')\n    test_df = test_df.merge(part_answers, how = 'left', on = 'part')\n    \n    test_df['prior_question_had_explanation'] = test_df['prior_question_had_explanation'].fillna(value = False).astype(bool)\n    test_df.fillna(value = -1, inplace = True)\n\n    test_df['answered_correctly'] = model.predict_proba(test_df[features])[:, 1]\n#     test_df['answered_correctly'] = model_sel.LightGBM(X_train, y_train, test_df[features], y_val)[1]\n    env.predict(test_df.loc[test_df['content_type_id'] == 0, ['row_id', 'answered_correctly']])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"new_train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_df.head()","execution_count":null,"outputs":[]}],"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat":4,"nbformat_minor":4}