{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"!pip install ../input/python-datatable/datatable-0.11.0-cp37-cp37m-manylinux2010_x86_64.whl > /dev/null 2>&1\n","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport datatable as dt\nimport lightgbm as lgb\nfrom collections import defaultdict\nfrom matplotlib import pyplot as plt\nfrom sklearn.preprocessing import LabelEncoder\nimport riiideducation\nimport xgboost\nfrom xgboost import XGBClassifier\nfrom xgboost import plot_importance\nfrom sklearn.metrics import roc_auc_score\n\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"data_types_dict = {\n    'user_id': 'int32', \n    'content_id': 'int16', \n    'answered_correctly': 'int8', \n    'prior_question_elapsed_time': 'float32', \n    'prior_question_had_explanation': 'bool'\n}\ntarget = 'answered_correctly'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = dt.fread('../input/riiid-test-answer-prediction/train.csv', columns=set(data_types_dict.keys())).to_pandas()\ntrain_df = train_df[train_df[target] != -1].reset_index(drop=True)\ntrain_df['prior_question_had_explanation'].fillna(False, inplace=True)\ntrain_df = train_df.astype(data_types_dict)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['lag'] = train_df.groupby('user_id')[target].shift()\ncum = train_df.groupby('user_id')['lag'].agg(['cumsum', 'cumcount'])\ntrain_df['user_correctness'] = cum['cumsum'] / cum['cumcount']\ntrain_df.drop(columns=['lag'], inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"user_agg = train_df.groupby('user_id')[target].agg(['sum', 'count'])\ncontent_agg = train_df.groupby('content_id')[target].agg(['sum', 'count'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = train_df.groupby('user_id').tail(24).reset_index(drop=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"questions_df = pd.read_csv(\n    '../input/riiid-test-answer-prediction/questions.csv', \n    usecols=[0, 3],\n    dtype={'question_id': 'int16', 'part': 'int8'}\n)\ntrain_df = pd.merge(train_df, questions_df, left_on='content_id', right_on='question_id', how='left')\ntrain_df.drop(columns=['question_id'], inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['content_count'] = train_df['content_id'].map(content_agg['count']).astype('int32')\ntrain_df['content_avg'] = train_df['content_id'].map(content_agg['sum'] / content_agg['count'])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lencoder = LabelEncoder()\ntrain_df['prior_question_had_explanation_enc'] = lencoder.fit_transform(train_df['prior_question_had_explanation'])\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"valid_df = train_df.groupby('user_id').tail(6)\ntrain_df.drop(valid_df.index, inplace=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"features = [\n    'prior_question_elapsed_time',\n    'prior_question_had_explanation_enc',\n    'user_correctness',\n    'part',\n    'content_count',\n    'content_avg'\n]\n\n#Parameters for XGBoost \nparams = {\n    'max_depth' : 7,\n   # 'max_leaves' : 2**4,\n    'alpha':0.1, \n   # 'lambda' : 0.2,\n    'min_child_weight ':2,\n    'subsample':0.7,\n    'tree_method' : 'gpu_hist',\n    'learning_rate': 0.1, #default = 0.3,\n    'colsample_bytree':0.7,\n    'eval_metric':'auc', \n    'objective' : 'binary:logistic',\n    'grow_policy' : 'lossguide',\n    'n_estimators': 800\n}\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_matrix = xgboost.DMatrix(data = train_df[features], label = train_df[target])\ntest_matrix = xgboost.DMatrix(data = valid_df[features])\nxgb = xgboost.train(params, dtrain = train_matrix)\n\npredicts = xgb.predict(test_matrix)\nroc = roc_auc_score(valid_df[target].astype('int32'), predicts)\nprint('ROC for XGBoost model')\nprint(roc)\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"xgb.get_score(importance_type='gain')\nplot_importance(xgb)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model=xgb","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"user_sum_dict = user_agg['sum'].astype('int16').to_dict(defaultdict(int))\nuser_count_dict = user_agg['count'].astype('int16').to_dict(defaultdict(int))\ncontent_sum_dict = content_agg['sum'].astype('int32').to_dict(defaultdict(int))\ncontent_count_dict = content_agg['count'].astype('int32').to_dict(defaultdict(int))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"try:\n    env = riiideducation.make_env()\nexcept:\n    pass\niter_test = env.iter_test()\nprior_test_df = None","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\nfor (test_df, sample_prediction_df) in iter_test:\n    if prior_test_df is not None:\n        prior_test_df[target] = eval(test_df['prior_group_answers_correct'].iloc[0])\n        prior_test_df = prior_test_df[prior_test_df[target] != -1].reset_index(drop = True)\n        \n        user_ids = prior_test_df['user_id'].values\n        content_ids = prior_test_df['content_id'].values\n        targets = prior_test_df[target].values\n        \n        for user_id, content_id, answered_correctly in zip(user_ids, content_ids, targets):\n            user_sum_dict[user_id] += answered_correctly\n            user_count_dict[user_id] += 1\n            content_sum_dict[content_id] += answered_correctly\n            content_count_dict[content_id] += 1\n\n    prior_test_df = test_df.copy()\n    \n    test_df = test_df[test_df['content_type_id'] == 0].reset_index(drop = True)\n    test_df = pd.merge(test_df, questions_df, left_on = 'content_id', right_on = 'question_id', how = 'left')\n    test_df['prior_question_had_explanation'] = test_df['prior_question_had_explanation'].fillna(False).astype('bool')    \n    test_df[\"prior_question_had_explanation_enc\"] = lencoder.transform(test_df[\"prior_question_had_explanation\"])\n    \n    user_sum = np.zeros(len(test_df), dtype = np.int16)\n    user_count = np.zeros(len(test_df), dtype = np.int16)\n    content_sum = np.zeros(len(test_df), dtype = np.int32)\n    content_count = np.zeros(len(test_df), dtype = np.int32)\n    \n    for i, (user_id, content_id) in enumerate(zip(test_df['user_id'].values, test_df['content_id'].values)):\n        user_sum[i] = user_sum_dict[user_id]\n        user_count[i] = user_count_dict[user_id]\n        content_sum[i] = content_sum_dict[content_id]\n        content_count[i] = content_count_dict[content_id]\n\n    test_df['user_correctness'] = user_sum / user_count\n    test_df['content_count'] = content_count\n    test_df['content_avg'] = content_sum / content_count\n    test_mat = xgboost.DMatrix(data = test_df[features])\n    test_df[target] = model.predict(test_mat)\n    env.predict(test_df[['row_id', target]])","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}