{"cells":[{"metadata":{},"cell_type":"markdown","source":"#Marcin Staśko Submission for Capstone Project - Eductation profiling"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","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\ntry:\n    env = riiideducation.make_env()\nexcept:\n    pass\nimport seaborn as sns\nsns.set_style(\"dark\")","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","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":{"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":"train['timestamp'].hist(bins = 100)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Answers by by user\n\ntrain_questions_only_df = train[train['answered_correctly']!=-1]\ntrain_questions_only_df['answered_correctly'].mean()\ngrouped_by_user_df = train_questions_only_df.groupby('user_id')\nuser_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":{"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()\ntrain.drop(['timestamp', 'content_type_id'], axis=1, inplace=True)","execution_count":null,"outputs":[]},{"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":"X = pd.DataFrame()\nfor 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":"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)","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\")\nvalidation = 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","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":"# 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)","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":{"trusted":true},"cell_type":"code","source":"import lightgbm as lgb\n\nparams = {\n    'objective': 'binary',\n    'max_bin': 255,\n    'learning_rate': 0.09,\n    'num_leaves': 6,\n    'boosting_type':'gbdt', \n    'colsample_bytree' : 0.64,\n    'subsample' : 0.7,\n    'reg_alpha' : 1,\n    'reg_lambda' : 1,\n    'min_child_weight': 1, \n    'min_child_samples': 5,\n    'min_split_gain': 0.5,\n    'metric' : 'binary_error',\n    'lambda_l1': 5, # L1 regularization\n    'lambda_l2': 10, # L2 regularization\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":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport seaborn as sns\n#displaying the most important features\nlgb.plot_importance(model)\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"iter_test = env.iter_test()\nfor (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":{"trusted":true},"cell_type":"code","source":"","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}