{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"import 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        \nimport seaborn as sns\nimport matplotlib.pyplot as plt","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"This notebook contains an elementary analysis of 'train.csv' and rule based baseline. I will further develop it during the competition.\nHere I analyze the distributions of different features, generate aggregeted features based on 90% of historical data and then train the model on the rest 10%."},{"metadata":{},"cell_type":"markdown","source":"My other materials on this competition:\n- Double validation (against target leakage): https://www.kaggle.com/ilialar/riiid-5-folds-double-validation\n- Dataset with pretrained models and feature generators: https://www.kaggle.com/ilialar/riiid-models"},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","collapsed":true,"_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":false},"cell_type":"markdown","source":"# Train data"},{"metadata":{},"cell_type":"markdown","source":"The `train.csv` file is too large for kaggle kernel. You will get a memory error if you try to load it all without specifying types. We will ignore some columns for now to save RAM and load only 10M rows."},{"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}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/train.csv', \n                       nrows=10**7,\n                       usecols = data_types_dict.keys(),\n                       dtype=data_types_dict, \n                       index_col = 0)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let's look at the data and main columns properties:"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.info()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.describe()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let's look at some columns more precisely."},{"metadata":{},"cell_type":"markdown","source":"## timestamp"},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['timestamp'].hist(bins = 100)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"`timestamp` represents the time from the first user interaction to the current one. It is expected that the distribution looks like this."},{"metadata":{"trusted":true},"cell_type":"code","source":"grouped_by_user_df = train_df.groupby('user_id')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"grouped_by_user_df.agg({'timestamp': 'max'}).hist(bins = 100)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"raw","source":"The distribution of the max timestamp for each user looks similar. It seems most users leave the platform quite soon (at least based on partial data we analyze)."},{"metadata":{},"cell_type":"markdown","source":"## Answered correctly"},{"metadata":{"trusted":true},"cell_type":"code","source":"(train_df['answered_correctly']==-1).mean()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"~2% of activities are lectures, we should exclude them for answers analysis."},{"metadata":{"trusted":true},"cell_type":"code","source":"train_questions_only_df = train_df[train_df['answered_correctly']!=-1]\ntrain_questions_only_df['answered_correctly'].mean()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"On average users answer ~66% questions correctly. Let's look how it is different from user to user."},{"metadata":{},"cell_type":"markdown","source":"### Answers by users"},{"metadata":{"trusted":true},"cell_type":"code","source":"grouped_by_user_df = train_questions_only_df.groupby('user_id')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"user_answers_df = grouped_by_user_df.agg({'answered_correctly': ['mean', 'count'] })\n\nuser_answers_df[('answered_correctly','mean')].hist(bins = 100)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Look's noisy, let's clear it a little bit"},{"metadata":{"trusted":true},"cell_type":"code","source":"user_answers_df[('answered_correctly','count')].hist(bins = 100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"(user_answers_df[('answered_correctly','count')]< 50).mean()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"54% of users answered less than 50 questions. Let's divide all users into novices and active users."},{"metadata":{"trusted":true},"cell_type":"code","source":"user_answers_df[user_answers_df[('answered_correctly','count')]< 50][('answered_correctly','mean')].mean()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"user_answers_df[user_answers_df[('answered_correctly','count')]< 50][('answered_correctly','mean')].hist(bins = 100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"user_answers_df[user_answers_df[('answered_correctly','count')] >= 50][('answered_correctly','mean')].hist(bins = 100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"user_answers_df[user_answers_df[('answered_correctly','count')] >= 50][('answered_correctly','mean')].mean()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We can see that active users do much better than novices. But anyway average user score is lower than the overall % of correct answers. It means heavy users have even better scores. Let's look at them."},{"metadata":{"trusted":true},"cell_type":"code","source":"user_answers_df[user_answers_df[('answered_correctly','count')] >= 500][('answered_correctly','mean')].hist(bins = 100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.scatter(x = user_answers_df[('answered_correctly','count')], y=user_answers_df[ ('answered_correctly','mean')])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Timestamp, the average score for the active user, and the number of questions answered can be useful for baseline."},{"metadata":{},"cell_type":"markdown","source":"### Answers by content"},{"metadata":{"trusted":true},"cell_type":"code","source":"grouped_by_content_df = train_questions_only_df.groupby('content_id')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"content_answers_df = grouped_by_content_df.agg({'answered_correctly': ['mean', 'count'] })","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"content_answers_df[('answered_correctly','count')].hist(bins = 100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"content_answers_df[('answered_correctly','mean')].hist(bins = 100)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Different questions have different popularity and complexity, and it can also be used in the baseline."},{"metadata":{"trusted":true},"cell_type":"code","source":"content_answers_df[content_answers_df[('answered_correctly','count')]>50][('answered_correctly','mean')].hist(bins = 100)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Questions.csv"},{"metadata":{},"cell_type":"markdown","source":"Let's look into the `questions.csv` file"},{"metadata":{"trusted":true},"cell_type":"code","source":"questions_df = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/questions.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"questions_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(f\"There are {len(questions_df['part'].unique())} different parts\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"questions_df['tags'].values[-1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"unique_tags = set().union(*[y.split() for y in questions_df['tags'].astype(str).values])\nprint(f\"There are {len(unique_tags)} different tags\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"(questions_df['question_id'] != questions_df['bundle_id']).mean()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"We can create aggregated features using the data from this file as well."},{"metadata":{},"cell_type":"markdown","source":"# Baseline"},{"metadata":{},"cell_type":"markdown","source":"Let's try to use discovered features and use them in model to predict the right answer probability."},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/train.csv',\n                       usecols = data_types_dict.keys(),\n                       dtype=data_types_dict, \n                       index_col = 0)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"features_part_df = train_df.iloc[:int(9 /10 * len(train_df))]\ntrain_part_df = train_df.iloc[int(9 /10 * len(train_df)):]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_questions_only_df = features_part_df[features_part_df['answered_correctly']!=-1]\ngrouped_by_user_df = train_questions_only_df.groupby('user_id')\nuser_answers_df = grouped_by_user_df.agg({'answered_correctly': ['mean', 'count']}).copy()\nuser_answers_df.columns = ['mean_user_accuracy', 'questions_answered']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"grouped_by_content_df = train_questions_only_df.groupby('content_id')\ncontent_answers_df = grouped_by_content_df.agg({'answered_correctly': ['mean', 'count'] }).copy()\ncontent_answers_df.columns = ['mean_accuracy', 'question_asked']","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Let's create additional features using `questions_df`"},{"metadata":{"trusted":true},"cell_type":"code","source":"questions_df = questions_df.merge(content_answers_df, left_on = 'question_id', right_on = 'content_id', how = 'left')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"bundle_dict = questions_df['bundle_id'].value_counts().to_dict()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"questions_df['right_answers'] = questions_df['mean_accuracy'] * questions_df['question_asked']\nquestions_df['bundle_size'] =questions_df['bundle_id'].apply(lambda x: bundle_dict[x])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"questions_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"grouped_by_bundle_df = questions_df.groupby('bundle_id')\nbundle_answers_df = grouped_by_bundle_df.agg({'right_answers': 'sum', 'question_asked': 'sum'}).copy()\nbundle_answers_df.columns = ['bundle_rignt_answers', 'bundle_questions_asked']\nbundle_answers_df['bundle_accuracy'] = bundle_answers_df['bundle_rignt_answers'] / bundle_answers_df['bundle_questions_asked']\nbundle_answers_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"grouped_by_part_df = questions_df.groupby('part')\npart_answers_df = grouped_by_part_df.agg({'right_answers': 'sum', 'question_asked': 'sum'}).copy()\npart_answers_df.columns = ['part_rignt_answers', 'part_questions_asked']\npart_answers_df['part_accuracy'] = part_answers_df['part_rignt_answers'] / part_answers_df['part_questions_asked']\npart_answers_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del train_df\ndel features_part_df\ndel grouped_by_user_df\ndel grouped_by_content_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import gc\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"features = ['timestamp','mean_user_accuracy', 'questions_answered','mean_accuracy', 'question_asked',\n            'prior_question_elapsed_time', 'prior_question_had_explanation',\n           'bundle_size', 'bundle_accuracy','part_accuracy', 'right_answers']\ntarget = 'answered_correctly'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_part_df = train_part_df[train_part_df[target] != -1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_part_df = train_part_df.merge(user_answers_df, how = 'left', on = 'user_id')\ntrain_part_df = train_part_df.merge(questions_df, how = 'left', left_on = 'content_id', right_on = 'question_id')\ntrain_part_df = train_part_df.merge(bundle_answers_df, how = 'left', on = 'bundle_id')\ntrain_part_df = train_part_df.merge(part_answers_df, how = 'left', on = 'part')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_part_df['prior_question_had_explanation'] = train_part_df['prior_question_had_explanation'].fillna(value = False).astype(bool)\ntrain_part_df.fillna(value = -1, inplace = True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_part_df.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_part_df = train_part_df[features + [target]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_part_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.metrics import roc_auc_score","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from lightgbm import LGBMClassifier","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lgbm = LGBMClassifier(\n    num_leaves=31, \n    max_depth= 2, \n    n_estimators = 25, \n    min_child_samples = 1000, \n    subsample=0.7, \n    subsample_freq=5,\n    n_jobs= -1,\n    is_higher_better = True,\n    first_metric_only = True\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lgbm.fit(train_part_df[features], train_part_df[target])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"roc_auc_score(train_part_df[target].values, lgbm.predict_proba(train_part_df[features])[:,1])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import riiideducation\n\nenv = riiideducation.make_env()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"iter_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_df, how = 'left', on = 'user_id')\n    test_df = test_df.merge(questions_df, how = 'left', left_on = 'content_id', right_on = 'question_id')\n    test_df = test_df.merge(bundle_answers_df, how = 'left', on = 'bundle_id')\n    test_df = test_df.merge(part_answers_df, 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'] = lgbm.predict_proba(test_df[features])[:,1]\n    env.predict(test_df.loc[test_df['content_type_id'] == 0, ['row_id', 'answered_correctly']])","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}