{"cells":[{"metadata":{},"cell_type":"markdown","source":"# About RiiiD!\n![](https://www.riiid.co/assets/about_image_3@2x.png)\nRiiiD! is a Korea based AI research company. Their goal is, in their own words, \"Inviting AI Researchers to Solve the World's Biggest Challenges in AI Education\".Their website can be found at https://www.riiid.co/en/about."},{"metadata":{},"cell_type":"markdown","source":"# All avaiable files"},{"metadata":{"trusted":true},"cell_type":"code","source":"import plotly.express as px\nimport gc\nimport pickle","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":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))\nroot = '/kaggle/input/riiid-test-answer-prediction/'","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# train.csv\ntrain.csv is a very large file. \nIt is a very \"long\" file with only 10 columns, but 101,230,332 rows."},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"%%time\n\ndf_train = pd.read_csv(root + 'train.csv', \n    nrows = 10**7,\n    dtype={\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': 'float32', \n        'prior_question_had_explanation': 'boolean'\n    },\n)\ndf_train.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nDescribe does not yield any especially useful info about train.csv.\n\"\"\"\ndf_train.describe()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\ncontent_type_id denotes if the contents are questions or lectures.\nThe pie shows that 98.1% of the data in train.csv are questions (0), only 1.94% are lectures.\n\"\"\"\ndf = df_train['content_type_id'].value_counts().reset_index()\n\nfig = px.pie(df, values='content_type_id', names='index')\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nuser_answer denotes if a user answered the question or not.\n0,1,2,3: I assume this means which option a user choose.\n-1: if content_type is lecture.\n\"\"\"\ndf = df_train['user_answer'].value_counts().reset_index()\n\nfig = px.pie(df, values='user_answer', names='index')\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nanswered_correctly denotes if a user answered the question correctly.\n-1: it's a lecture not a question.\n0: wrong answer.\n1: correct answer.\n\"\"\"\ndf = df_train['answered_correctly'].value_counts().reset_index()\n\nfig = px.pie(df, values='answered_correctly', names='index')\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nDrop useless columns in train.csv for sake of saving memory.\n\"\"\"\ndf_train = df_train.drop([\n    'row_id', \n    'timestamp', \n    'content_type_id',\n    'task_container_id',\n], axis=1)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# lectures.csv\nshape=(418, 4)"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_lectures = pd.read_csv(root+'lectures.csv')\ndf_lectures.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\ntype_of indicates what a lecture is about.\n\"\"\"\ndf = df_lectures['type_of'].value_counts().reset_index()\n\nfig = px.pie(df, values='type_of', names='index')\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# questions.csv\nshape=(13523, 5)"},{"metadata":{"trusted":true},"cell_type":"code","source":"df_questions = pd.read_csv(root+'questions.csv')\ndf_questions.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nlecture ids and question ids have overlap. This is a little strange.\nI'm expecting no overlap and each id correcpond to the 'content_id' column in train.csv...\n\"\"\"\nlecture_ids = df_lectures['lecture_id'].unique()\nquestion_ids = df_questions['question_id'].unique()\nset(lecture_ids).intersection(set(question_ids))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# XGBoost model [WIP]"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\n\"\"\"\nRead necessary cols from train.csv.\n\"\"\"\nnecessary_cols = {\n    'user_id': 'int32',\n    'content_id': 'int16',\n    'answered_correctly': 'int8',\n    'prior_question_elapsed_time': 'float16',\n    'prior_question_had_explanation': 'boolean'\n}\n\ndf_train = pd.read_csv(\n    root+'train.csv',\n    usecols=necessary_cols.keys(),\n    dtype=necessary_cols, \n    index_col=0\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nFeature engineering: calc a user's historical performance.\n\"\"\"\ndf_train_groupByUser = df_train.groupby('user_id')\ndf_train_groupByUserStats = df_train_groupByUser.agg({\n    'answered_correctly':['mean', 'count', 'std', 'skew'],\n    'prior_question_elapsed_time': ['mean', 'std']\n})\n\n# Flatten index.\ndf_train_groupByUserStats.columns = [\n    'user_answered_correctly_mean',\n    'user_answered_correctly_count',\n    'user_answered_correctly_std',\n    'user_answered_correctly_skew',\n    'user_prior_question_elapsed_time_mean',\n    'user_prior_question_elapsed_time_std',\n]\ndf_user_stats = df_train_groupByUserStats.reset_index()\ndf_user_stats","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nFeature engineering: calc a specific content's states.\n\"\"\"\ndf_train_groupByContent = df_train.groupby('content_id')\ndf_train_groupByContentStats = df_train_groupByContent.agg({\n    'answered_correctly': ['mean', 'count', 'std', 'skew']})\ndf_train_groupByContentStats","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nFeature engineering: combine lectures.csv and questions.csv\n\"\"\"\ndf_lectures['is_lecture'] = 1\ndf_lectures_droped = df_lectures.drop(['tag', 'type_of', 'part'], axis=1)\ndf_lectures_droped.columns = ['content_id', 'is_lecture']\ndf_questions['is_question'] = 1\ndf_questions_droped = df_questions.drop(['bundle_id', 'correct_answer', 'tags', 'part'], axis=1)\ndf_questions_droped.columns = ['content_id', 'is_question']\n\ndf_contents = pd.merge(df_lectures_droped, df_questions_droped, on='content_id', how='outer')\ndf_contents[['is_lecture', 'is_question']] = df_contents[['is_lecture', 'is_question']].fillna(0)\ndf_contents_stats = pd.merge(df_train_groupByContentStats, df_contents, on='content_id', how='left')\ndf_contents_stats.columns = [\n    'content_id',\n    'content_answered_correctly_mean',\n    'content_answered_correctly_count',\n    'content_answered_correctly_std',\n    'content_answered_correctly_skew',\n    'is_lecture',\n    'is_question'\n]\ndf_contents_stats","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del df_questions\ndel df_lectures\ndel df_lectures_droped\ndel df_questions_droped\ndel df_contents\ndel df_train_groupByUserStats\ndel df_train_groupByContent\ndel df_train_groupByContentStats\ndel df_train_groupByUser\ngc.collect()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nUtil fn: reduce memory usage of a dataframe.\n\"\"\"\ndef reduce_mem_usage(df, verbose=True):\n    \"\"\"Make everything faster by reducing the memory used by dataframes.\n    Iterate all columns and modify data type to reduce memory.\n\n    Args:\n        df: pandas dataframe\n    Returns:\n        df: pandas dataframe, with reduced memory\n    \"\"\"\n    numerics = ['int16', 'int32', 'int64', 'float16', 'float32', 'float64']\n    start_mem = df.memory_usage().sum() / 1024**2    \n    for col in df.columns:\n        col_type = df[col].dtypes\n        if col_type in numerics:\n            c_min = df[col].min()\n            c_max = df[col].max()\n            if str(col_type)[:3] == 'int':\n                if c_min > np.iinfo(np.int8).min and c_max < np.iinfo(np.int8).max:\n                    df[col] = df[col].astype(np.int8)\n                elif c_min > np.iinfo(np.int16).min and c_max < np.iinfo(np.int16).max:\n                    df[col] = df[col].astype(np.int16)\n                elif c_min > np.iinfo(np.int32).min and c_max < np.iinfo(np.int32).max:\n                    df[col] = df[col].astype(np.int32)\n                elif c_min > np.iinfo(np.int64).min and c_max < np.iinfo(np.int64).max:\n                    df[col] = df[col].astype(np.int64)  \n            else:\n                if c_min > np.finfo(np.float16).min and c_max < np.finfo(np.float16).max:\n                    df[col] = df[col].astype(np.float16)\n                elif c_min > np.finfo(np.float32).min and c_max < np.finfo(np.float32).max:\n                    df[col] = df[col].astype(np.float32)\n                else:\n                    df[col] = df[col].astype(np.float64)    \n    end_mem = df.memory_usage().sum() / 1024**2\n    if verbose: \n        print('Mem. usage decreased to {:5.2f} Mb ({:.1f}% reduction)'.format(end_mem, 100 * (start_mem - end_mem) / start_mem))\n    return df\n\ndf_train = reduce_mem_usage(df_train)\ndf_user_stats = reduce_mem_usage(df_user_stats)\ndf_contents_stats = reduce_mem_usage(df_contents_stats)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nSave df_train, df_user_stats, df_contents_stats before merge. \nMemory error is likely to occur. Painful...\n\"\"\"\n# Save dataframe\n# df_train.to_pickle('df_train.pkl')\n# df_user_stats.to_pickle('df_user_stats.pkl')\n# df_contents_stats.to_pickle('df_contents_stats.pkl')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Load saved dataframe\n# df_train = pd.read_pickle('df_train.pkl')\n# df_user_stats = pd.read_pickle('df_user_stats.pkl')\n# df_contents_stats = pd.read_pickle('df_contents_stats.pkl')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nConstructing training dataframe.\n\"\"\"\n# Only choose rows questions, not lectures.\ndf_train = df_train[df_train['answered_correctly'] != -1]\n\ndf_train = df_train.merge(df_user_stats, on='user_id', how='left')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train = df_train.merge(df_contents_stats, on='content_id', how='left')\n\ndf_train['prior_question_had_explanation'] = df_train['prior_question_had_explanation'].fillna(value=False).astype(bool)\ndf_train = df_train.fillna(0.5)\ndf_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.columns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nFinal step before split.\nOnly choose necessary features.\n\"\"\"\nfeatures = [\n       'prior_question_elapsed_time', 'prior_question_had_explanation',\n       'user_answered_correctly_mean', 'user_answered_correctly_count',\n       'user_answered_correctly_std', 'user_answered_correctly_skew',\n       'user_prior_question_elapsed_time_mean',\n       'user_prior_question_elapsed_time_std',\n       'content_answered_correctly_mean', 'content_answered_correctly_count',\n       'content_answered_correctly_std', 'content_answered_correctly_skew',\n       'is_lecture', 'is_question'\n]\ntarget = 'answered_correctly'\n\ndf_train = df_train[features + [target]]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_train.fillna(0.5)\ndf_train","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.model_selection import train_test_split\n\ndf_train, df_test = train_test_split(df_train, random_state=1, test_size=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nBuild XGBoost model.\n\"\"\"\nimport xgboost as xgb\nfrom sklearn.model_selection import GridSearchCV\n\nxgb_matrix = xgb.DMatrix(\n    df_train[features],\n    df_train[target]\n)\n\nour_params = {\n  'eta'             : 0.05,    \n  'seed'            : 0, \n  'subsample'       : 0.8, \n  'colsample_bytree': 0.8, \n  'objective'       : 'binary:logistic', # output probability [0, 1]\n  'max_depth'       : 10,  \n  'min_child_weight': 1 # default=1, prevent overfitting, high value may cause under fitting\n}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nfinal_gb = xgb.train(\n  params = our_params, \n  dtrain = xgb_matrix, \n  num_boost_round = 10,\n#   early_stopping_rounds = 150,\n  verbose_eval = 5\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nPredict using df_test.\n\"\"\"\nfrom sklearn.metrics import roc_auc_score\n\nxgb_matrix_test = xgb.DMatrix(\n    df_test[features],\n#     df_test[target]\n)\n\ntest_predict = final_gb.predict(xgb_matrix_test)\n\nroc_auc_score(df_test[target].values, test_predict)\ntest_predict","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nRiiiD API. Only run this cell once!\n\"\"\"\nimport riiideducation\n\nenv = riiideducation.make_env()\niter_test = env.iter_test()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nCreate submission.\n\"\"\"\n\nfor (df_test, sample_prediction_df) in iter_test:\n    df_test = df_test.merge(df_user_stats, how = 'left', on = 'user_id')\n    df_test = df_test.merge(df_contents_stats, how = 'left', on = 'content_id')\n    df_test['prior_question_had_explanation'] = df_test['prior_question_had_explanation'].fillna(value=False).astype(bool)\n    df_test.fillna(value = 0.5, inplace = True)\n\n    dMatrix = xgb.DMatrix(df_test[features])\n    \n    df_test['answered_correctly'] = final_gb.predict(dMatrix)\n    env.predict(df_test.loc[df_test['content_type_id'] == 0, ['row_id', 'answered_correctly']])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Some notes\nMemory management is crucial for this competition.\nToDo: hyperparameter optimization."}],"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}