{"cells":[{"metadata":{},"cell_type":"markdown","source":"This is attempting to improve on my first simple LGBM model with only 3 features.\n"},{"metadata":{},"cell_type":"markdown","source":"## Reading Data and Importing Libraries ##"},{"metadata":{"trusted":true},"cell_type":"code","source":"import riiideducation\n# import dask.dataframe as dd\nimport pandas as pd\nimport numpy as np\nfrom sklearn.metrics import roc_auc_score\nenv = riiideducation.make_env()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/train.csv',\n                   usecols=[1, 2, 3, 4, 7, 8, 9],\n                   dtype={'timestamp': 'int64',\n                          'user_id': 'int32',\n                          'content_id': 'int16',\n                          'content_type_id': 'int8',\n                          'answered_correctly':'int8',\n                          'prior_question_elapsed_time': 'float32',\n                          'prior_question_had_explanation': 'boolean'}\n                   )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Affirmatives (True) for content_type_id are only for those with a different type of content (lectures). These are not real questions."},{"metadata":{"trusted":true},"cell_type":"code","source":"#removing True or 1 for content_type_id\n\ntrain = train[train.content_type_id == False]\n\n#arrange by timestamp\n\ntrain = train.sort_values(['timestamp'], ascending=True).reset_index(drop = True)\n\ntrain.head(10)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#getting final results ready for later, so we can clear memory\nresults_c_final = train[['content_id','answered_correctly']].groupby(['content_id']).agg(['mean'])\nresults_c_final.columns = [\"answered_correctly_content\"]\n\nresults_u_final = train[['user_id','answered_correctly']].groupby(['user_id']).agg(['mean', 'sum', 'count'])\nresults_u_final.columns = ['answered_correctly_user', 'sum', 'count']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#saving value to fillna\nelapsed_mean = train.prior_question_elapsed_time.mean()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data Exploration ##"},{"metadata":{"trusted":true},"cell_type":"code","source":"train.loc[(train.timestamp == 0)].answered_correctly.mean()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.loc[(train.timestamp != 0)].answered_correctly.mean()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.loc[(train.timestamp < 1000000) & (train.timestamp > 0)].answered_correctly.mean()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Are early questions fundamentally different? The best answer I could get was: not really"},{"metadata":{"trusted":true},"cell_type":"code","source":"train.prior_question_had_explanation.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.answered_correctly.mean()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.drop(['timestamp', 'content_type_id'], axis=1, inplace=True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Creating Validation Set (Most Recent Answers by User) ##"},{"metadata":{"trusted":true},"cell_type":"code","source":"validation = pd.DataFrame()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(4):\n    last_records = train.drop_duplicates('user_id', keep = 'last')\n    train = train[~train.index.isin(last_records.index)]\n    validation = validation.append(last_records)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(validation)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validation.answered_correctly.mean()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.answered_correctly.mean()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Does it make sense to use last questions as validation? Why is the rate of correct answers so low?"},{"metadata":{},"cell_type":"markdown","source":"## Extracting Training Data ##"},{"metadata":{"trusted":true},"cell_type":"code","source":"X = pd.DataFrame()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for i in range(15):\n    last_records = train.drop_duplicates('user_id', keep = 'last')\n    train = train[~train.index.isin(last_records.index)]\n    X = X.append(last_records)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(X)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X.answered_correctly.mean()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.answered_correctly.mean()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Aggregating and Shaping Data ##"},{"metadata":{"trusted":true},"cell_type":"code","source":"results_c = train[['content_id','answered_correctly']].groupby(['content_id']).agg(['mean'])\nresults_c.columns = [\"answered_correctly_content\"]\n\nresults_u = train[['user_id','answered_correctly']].groupby(['user_id']).agg(['mean', 'sum', 'count'])\nresults_u.columns = [\"answered_correctly_user\", 'sum', 'count']","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#clearing memory\ndel(train)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = pd.merge(X, results_u, on=['user_id'], how=\"left\")\nX = pd.merge(X, results_c_final, on=['content_id'], how=\"left\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"validation = pd.merge(validation, results_u, on=['user_id'], how=\"left\")\nvalidation = pd.merge(validation, results_c_final, on=['content_id'], how=\"left\")","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\n\nlb_make = LabelEncoder()\n\nX.prior_question_had_explanation.fillna(False, inplace = True)\nvalidation.prior_question_had_explanation.fillna(False, inplace = True)\n\nvalidation[\"prior_question_had_explanation_enc\"] = lb_make.fit_transform(validation[\"prior_question_had_explanation\"])\nX[\"prior_question_had_explanation_enc\"] = lb_make.fit_transform(X[\"prior_question_had_explanation\"])\nX.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#reading in question df\nquestions_df = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/questions.csv',\n                            usecols=[0, 3],\n                            dtype={'question_id': 'int16',\n                              'part': 'int8'}\n                          )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = pd.merge(X, questions_df, left_on = 'content_id', right_on = 'question_id', how = 'left')\nvalidation = pd.merge(validation, questions_df, left_on = 'content_id', right_on = 'question_id', how = 'left')\nX.part = X.part - 1\nvalidation.part = validation.part - 1\n\nX.part.value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y = X['answered_correctly']\nX = X.drop(['answered_correctly'], axis=1)\nX.head()\n\ny_val = validation['answered_correctly']\nX_val = validation.drop(['answered_correctly'], axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X = X[['answered_correctly_user', 'answered_correctly_content', 'sum', 'count',\n       'prior_question_elapsed_time','prior_question_had_explanation_enc', 'part']]\nX_val = X_val[['answered_correctly_user', 'answered_correctly_content', 'sum', 'count',\n       'prior_question_elapsed_time','prior_question_had_explanation_enc', 'part']]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\n# Filling with 0.5 for simplicity; there could likely be a better value\nX['answered_correctly_user'].fillna(0.5,  inplace=True)\nX['answered_correctly_content'].fillna(0.5,  inplace=True)\n\nX['part'].fillna(4, inplace = True)\nX['sum'].fillna(0, inplace = True)\nX['count'].fillna(0, inplace = True)\nX['prior_question_elapsed_time'].fillna(elapsed_mean, inplace = True)\nX['prior_question_had_explanation_enc'].fillna(0, inplace = True)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Filling with 0.5 for simplicity; there could likely be a better value\nX_val['answered_correctly_user'].fillna(0.5,  inplace=True)\nX_val['answered_correctly_content'].fillna(0.5,  inplace=True)\n\nX_val['part'].fillna(4, inplace = True)\nX_val['count'].fillna(0, inplace = True)\nX_val['sum'].fillna(0, inplace = True)\nX_val['prior_question_elapsed_time'].fillna(elapsed_mean, inplace = True)\nX_val['prior_question_had_explanation_enc'].fillna(0, inplace = True)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Modeling ##"},{"metadata":{"trusted":true},"cell_type":"code","source":"import lightgbm as lgb\n\nparams = {\n    'objective': 'binary',\n    'max_bin': 700,\n    'learning_rate': 0.0175,\n    'num_leaves': 80\n}\n\nlgb_train = lgb.Dataset(X, y, categorical_feature = ['part', 'prior_question_had_explanation_enc'])\nlgb_eval = lgb.Dataset(X_val, y_val, categorical_feature = ['part', 'prior_question_had_explanation_enc'], reference=lgb_train)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = lgb.train(\n    params, lgb_train,\n    valid_sets=[lgb_train, lgb_eval],\n    verbose_eval=50,\n    num_boost_round=10000,\n    early_stopping_rounds=12\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"y_pred = model.predict(X_val)\ny_true = np.array(y_val)\nroc_auc_score(y_true, y_pred)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Examining Feature Importance ##"},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#displaying the most important features\nlgb.plot_importance(model)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Making Predictions for New Data ##"},{"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 = pd.merge(test_df, questions_df, left_on = 'content_id', right_on = 'question_id', how = 'left')\n    test_df = pd.merge(test_df, results_u_final, on=['user_id'],  how=\"left\")\n    test_df = pd.merge(test_df, results_c_final, on=['content_id'],  how=\"left\")\n    test_df['answered_correctly_user'].fillna(0.5,  inplace=True)\n    test_df['answered_correctly_content'].fillna(0.5,  inplace=True)\n    test_df['part'] = test_df.part - 1\n\n    test_df['part'].fillna(4, inplace = True)\n    test_df['sum'].fillna(0, inplace=True)\n    test_df['count'].fillna(0, inplace=True)\n    test_df['prior_question_elapsed_time'].fillna(elapsed_mean, inplace = True)\n    test_df['prior_question_had_explanation'].fillna(False, inplace=True)\n    test_df[\"prior_question_had_explanation_enc\"] = lb_make.fit_transform(test_df[\"prior_question_had_explanation\"])\n    test_df['answered_correctly'] =  model.predict(test_df[['answered_correctly_user', 'answered_correctly_content', 'sum', 'count',\n                                                                  'prior_question_elapsed_time','prior_question_had_explanation_enc', 'part']])\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}