{"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_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"## Cài đặt các thư viện cần thiết","metadata":{}},{"cell_type":"code","source":"!pip install ../input/python-datatable/datatable-0.11.0-cp37-cp37m-manylinux2010_x86_64.whl","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:01.132458Z","iopub.execute_input":"2022-05-27T07:55:01.132928Z","iopub.status.idle":"2022-05-27T07:55:11.553847Z","shell.execute_reply.started":"2022-05-27T07:55:01.132837Z","shell.execute_reply":"2022-05-27T07:55:11.552588Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd\nimport datatable as dt\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport seaborn as sns\nimport os\n\nimport riiideducation\n\nfrom sklearn.metrics import roc_auc_score,mean_squared_error,roc_curve\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler\n\nimport tensorflow as tf\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import BatchNormalization,Dropout,Dense,Flatten,Conv1D, MaxPooling1D,LSTM,GRU\nfrom tensorflow.keras.optimizers import Adam\nfrom keras.metrics import BinaryAccuracy,MeanSquaredError\nfrom keras import backend as K","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:13.508462Z","iopub.execute_input":"2022-05-27T07:55:13.508887Z","iopub.status.idle":"2022-05-27T07:55:15.918963Z","shell.execute_reply.started":"2022-05-27T07:55:13.508847Z","shell.execute_reply":"2022-05-27T07:55:15.918267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import warnings\nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:18.391749Z","iopub.execute_input":"2022-05-27T07:55:18.392670Z","iopub.status.idle":"2022-05-27T07:55:18.396683Z","shell.execute_reply.started":"2022-05-27T07:55:18.392633Z","shell.execute_reply":"2022-05-27T07:55:18.395715Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Kiểm tra dữ liệu đang có","metadata":{}},{"cell_type":"code","source":"os.listdir('../input/riiid-test-answer-prediction')","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:22.187918Z","iopub.execute_input":"2022-05-27T07:55:22.188808Z","iopub.status.idle":"2022-05-27T07:55:22.196308Z","shell.execute_reply.started":"2022-05-27T07:55:22.188767Z","shell.execute_reply":"2022-05-27T07:55:22.195463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lectures_csv = dt.fread(\"../input/riiid-test-answer-prediction/lectures.csv\").to_pandas()\nexample_test_csv = dt.fread(\"../input/riiid-test-answer-prediction/example_test.csv\").to_pandas()\ntrain_csv = pd.read_csv(\"../input/riiid-test-answer-prediction/train.csv\", nrows=10**6, low_memory=False)\nquestions_csv = dt.fread(\"../input/riiid-test-answer-prediction/questions.csv\").to_pandas()","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:24.171941Z","iopub.execute_input":"2022-05-27T07:55:24.172329Z","iopub.status.idle":"2022-05-27T07:55:25.227480Z","shell.execute_reply.started":"2022-05-27T07:55:24.172298Z","shell.execute_reply":"2022-05-27T07:55:25.226687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 0 nếu sự kiện là câu hỏi cho người dùng, 1 nếu sự kiện là người dùng đang xem bài giảng. Chỉ cần lấy câu hỏi\ntrain_csv = train_csv[train_csv.content_type_id == 0]\n# giá trị -1 là bài giảng\ntrain_csv = train_csv[train_csv.answered_correctly != -1]","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:26.363014Z","iopub.execute_input":"2022-05-27T07:55:26.363470Z","iopub.status.idle":"2022-05-27T07:55:26.505836Z","shell.execute_reply.started":"2022-05-27T07:55:26.363431Z","shell.execute_reply":"2022-05-27T07:55:26.504776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_csv = train_csv.sort_values(['timestamp'], ascending=True).reset_index(drop = True)","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:27.866876Z","iopub.execute_input":"2022-05-27T07:55:27.867287Z","iopub.status.idle":"2022-05-27T07:55:28.077162Z","shell.execute_reply.started":"2022-05-27T07:55:27.867251Z","shell.execute_reply":"2022-05-27T07:55:28.076205Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_csv.head(5)","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:29.080412Z","iopub.execute_input":"2022-05-27T07:55:29.080808Z","iopub.status.idle":"2022-05-27T07:55:29.097410Z","shell.execute_reply.started":"2022-05-27T07:55:29.080772Z","shell.execute_reply":"2022-05-27T07:55:29.096386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"content_mean_final = train_csv[['content_id','answered_correctly']].groupby(['content_id']).agg(['mean'])\ncontent_mean_final.columns = [\"answered_correctly_content_mean\"]","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:31.035071Z","iopub.execute_input":"2022-05-27T07:55:31.035468Z","iopub.status.idle":"2022-05-27T07:55:31.085651Z","shell.execute_reply.started":"2022-05-27T07:55:31.035437Z","shell.execute_reply":"2022-05-27T07:55:31.084691Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"user_mean_final = train_csv[['user_id','answered_correctly']].groupby(['user_id']).agg(['mean', 'sum', 'count'])\nuser_mean_final.columns = [\"answered_correctly_user_mean\", 'sum_correct', 'count']","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:32.630023Z","iopub.execute_input":"2022-05-27T07:55:32.630421Z","iopub.status.idle":"2022-05-27T07:55:32.681294Z","shell.execute_reply.started":"2022-05-27T07:55:32.630379Z","shell.execute_reply":"2022-05-27T07:55:32.680545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#dữ liệu cho fillna\nelapsed_time_mean_final = train_csv.prior_question_elapsed_time.mean()","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:34.038013Z","iopub.execute_input":"2022-05-27T07:55:34.038449Z","iopub.status.idle":"2022-05-27T07:55:34.048115Z","shell.execute_reply.started":"2022-05-27T07:55:34.038410Z","shell.execute_reply":"2022-05-27T07:55:34.047276Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_csv.drop(['timestamp', 'content_type_id'], axis=1, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:35.637922Z","iopub.execute_input":"2022-05-27T07:55:35.638297Z","iopub.status.idle":"2022-05-27T07:55:35.665504Z","shell.execute_reply.started":"2022-05-27T07:55:35.638266Z","shell.execute_reply":"2022-05-27T07:55:35.664561Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Validation/Train datasets","metadata":{}},{"cell_type":"code","source":"validation = pd.DataFrame()\nfor i in range(4):\n    last_records = train_csv.drop_duplicates('user_id', keep = 'last')\n    train_csv = train_csv[~train_csv.index.isin(last_records.index)]\n    validation = validation.append(last_records)","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:36.918046Z","iopub.execute_input":"2022-05-27T07:55:36.918814Z","iopub.status.idle":"2022-05-27T07:55:37.274125Z","shell.execute_reply.started":"2022-05-27T07:55:36.918770Z","shell.execute_reply":"2022-05-27T07:55:37.273237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = pd.DataFrame()\nfor i in range(15):\n    last_records = train_csv.drop_duplicates('user_id', keep = 'last')\n    train_csv = train_csv[~train_csv.index.isin(last_records.index)]\n    X = X.append(last_records)","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:38.168246Z","iopub.execute_input":"2022-05-27T07:55:38.168654Z","iopub.status.idle":"2022-05-27T07:55:39.472346Z","shell.execute_reply.started":"2022-05-27T07:55:38.168621Z","shell.execute_reply":"2022-05-27T07:55:39.471215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"results_c = train_csv[['content_id','answered_correctly']].groupby(['content_id']).agg(['mean'])\nresults_c.columns = [\"answered_correctly_content_mean\"]\n\nresults_u = train_csv[['user_id','answered_correctly']].groupby(['user_id']).agg(['mean', 'sum', 'count'])\nresults_u.columns = [\"answered_correctly_user_mean\", 'sum_correct', 'count']","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:40.363978Z","iopub.execute_input":"2022-05-27T07:55:40.364658Z","iopub.status.idle":"2022-05-27T07:55:40.451501Z","shell.execute_reply.started":"2022-05-27T07:55:40.364621Z","shell.execute_reply":"2022-05-27T07:55:40.450458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"result_time_mean = train_csv.prior_question_elapsed_time.mean()","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:42.062783Z","iopub.execute_input":"2022-05-27T07:55:42.063184Z","iopub.status.idle":"2022-05-27T07:55:42.072294Z","shell.execute_reply.started":"2022-05-27T07:55:42.063149Z","shell.execute_reply":"2022-05-27T07:55:42.071450Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = pd.merge(X, results_u, on=['user_id'], how=\"left\")\nX = pd.merge(X, results_c, on=['content_id'], how=\"left\")","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:43.352145Z","iopub.execute_input":"2022-05-27T07:55:43.353012Z","iopub.status.idle":"2022-05-27T07:55:43.378444Z","shell.execute_reply.started":"2022-05-27T07:55:43.352972Z","shell.execute_reply":"2022-05-27T07:55:43.377712Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation = pd.merge(validation, results_u, on=['user_id'], how=\"left\")\nvalidation = pd.merge(validation, results_c, on=['content_id'], how=\"left\")","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:45.144317Z","iopub.execute_input":"2022-05-27T07:55:45.145060Z","iopub.status.idle":"2022-05-27T07:55:45.160495Z","shell.execute_reply.started":"2022-05-27T07:55:45.145018Z","shell.execute_reply":"2022-05-27T07:55:45.159694Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y = X['answered_correctly']\nX = X.drop(['answered_correctly'], axis=1)\n\ny_val = validation['answered_correctly']\nX_val = validation.drop(['answered_correctly'], axis=1)","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:46.581823Z","iopub.execute_input":"2022-05-27T07:55:46.582834Z","iopub.status.idle":"2022-05-27T07:55:46.593002Z","shell.execute_reply.started":"2022-05-27T07:55:46.582791Z","shell.execute_reply":"2022-05-27T07:55:46.592299Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X.columns","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:48.221499Z","iopub.execute_input":"2022-05-27T07:55:48.222279Z","iopub.status.idle":"2022-05-27T07:55:48.228085Z","shell.execute_reply.started":"2022-05-27T07:55:48.222244Z","shell.execute_reply":"2022-05-27T07:55:48.227330Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lencoder = LabelEncoder()\n\nX['prior_question_had_explanation'].fillna(False, inplace = True)\nX['prior_question_had_explanation_enc'] = lencoder.fit_transform(X['prior_question_had_explanation'])\nX['answered_correctly_user_mean'].fillna(0.5,  inplace=True)\nX['answered_correctly_content_mean'].fillna(0.5,  inplace=True)\nX['sum_correct'].fillna(0, inplace = True)\nX['count'].fillna(0, inplace = True)\nX['prior_question_elapsed_time'].fillna(result_time_mean, inplace = True)\n\nX_val['prior_question_had_explanation'].fillna(False, inplace = True)\nX_val['prior_question_had_explanation_enc'] = lencoder.fit_transform(X_val['prior_question_had_explanation'])\nX_val['answered_correctly_user_mean'].fillna(0.5,  inplace=True)\nX_val['answered_correctly_content_mean'].fillna(0.5,  inplace=True)\nX_val['sum_correct'].fillna(0, inplace = True)\nX_val['count'].fillna(0, inplace = True)\nX_val['prior_question_elapsed_time'].fillna(result_time_mean, inplace = True)","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:49.634558Z","iopub.execute_input":"2022-05-27T07:55:49.635227Z","iopub.status.idle":"2022-05-27T07:55:49.665199Z","shell.execute_reply.started":"2022-05-27T07:55:49.635187Z","shell.execute_reply":"2022-05-27T07:55:49.664410Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = X[['answered_correctly_user_mean', 'answered_correctly_content_mean', 'sum_correct', 'count',\n       'prior_question_elapsed_time','prior_question_had_explanation_enc']]\nX_val = X_val[['answered_correctly_user_mean', 'answered_correctly_content_mean', 'sum_correct', 'count',\n       'prior_question_elapsed_time','prior_question_had_explanation_enc']]","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:53.479047Z","iopub.execute_input":"2022-05-27T07:55:53.479482Z","iopub.status.idle":"2022-05-27T07:55:53.488796Z","shell.execute_reply.started":"2022-05-27T07:55:53.479444Z","shell.execute_reply":"2022-05-27T07:55:53.487842Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"scaler = StandardScaler()\nX = scaler.fit_transform(X)\nX_val = scaler.transform(X_val)","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:56.132431Z","iopub.execute_input":"2022-05-27T07:55:56.133063Z","iopub.status.idle":"2022-05-27T07:55:56.150532Z","shell.execute_reply.started":"2022-05-27T07:55:56.133012Z","shell.execute_reply":"2022-05-27T07:55:56.149736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow.keras.layers import Conv1D\nK.clear_session()\nX_train = X.reshape(X.shape[0], X.shape[1], 1)\nX_test = X_val.reshape(X_val.shape[0], X_val.shape[1], 1)\n    \nmodel=Sequential()\n\nmodel.add(Conv1D(32, 2, activation='sigmoid', input_shape=X_train[0].shape))\n\nmodel.add(Conv1D(24, 2, activation='relu', padding='causal'))\n\nmodel.add(Conv1D(128, 2, activation='relu', padding='causal'))\nmodel.add(Conv1D(256, 2, activation='relu', padding='causal'))\n\nmodel.add(Dense(64, activation='relu'))\nmodel.add(Dense(32, activation='relu'))\nmodel.add(Dense(28, activation='relu'))\nmodel.add(Flatten())\nmodel.add(Dense(1, activation='sigmoid'))\n\nmodel.compile(optimizer=Adam(learning_rate=0.01), loss='binary_crossentropy', metrics=[tf.keras.metrics.BinaryAccuracy()])","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:55:57.727250Z","iopub.execute_input":"2022-05-27T07:55:57.727873Z","iopub.status.idle":"2022-05-27T07:55:57.883038Z","shell.execute_reply.started":"2022-05-27T07:55:57.727830Z","shell.execute_reply":"2022-05-27T07:55:57.882173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(X_train, y, epochs=30, verbose=2, batch_size=50000)","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:56:00.390742Z","iopub.execute_input":"2022-05-27T07:56:00.391694Z","iopub.status.idle":"2022-05-27T07:57:28.117890Z","shell.execute_reply.started":"2022-05-27T07:56:00.391647Z","shell.execute_reply":"2022-05-27T07:57:28.117145Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = model.predict(X_test)\ny_true = np.array(y_val)","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:58:36.072602Z","iopub.execute_input":"2022-05-27T07:58:36.073065Z","iopub.status.idle":"2022-05-27T07:58:37.436231Z","shell.execute_reply.started":"2022-05-27T07:58:36.073025Z","shell.execute_reply":"2022-05-27T07:58:37.435454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"roc_auc_score(y_true, y_pred)","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:58:39.430936Z","iopub.execute_input":"2022-05-27T07:58:39.431822Z","iopub.status.idle":"2022-05-27T07:58:39.443980Z","shell.execute_reply.started":"2022-05-27T07:58:39.431778Z","shell.execute_reply":"2022-05-27T07:58:39.443000Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"fpr, tpr, _ = roc_curve(y_true, y_pred)\n\nplt.plot(fpr,tpr)\nplt.ylabel('True Positive Rate')\nplt.xlabel('False Positive Rate')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:58:42.025806Z","iopub.execute_input":"2022-05-27T07:58:42.026472Z","iopub.status.idle":"2022-05-27T07:58:42.219713Z","shell.execute_reply.started":"2022-05-27T07:58:42.026435Z","shell.execute_reply":"2022-05-27T07:58:42.219031Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mean_squared_error(y_true, y_pred)","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:58:44.836766Z","iopub.execute_input":"2022-05-27T07:58:44.837661Z","iopub.status.idle":"2022-05-27T07:58:44.846113Z","shell.execute_reply.started":"2022-05-27T07:58:44.837613Z","shell.execute_reply":"2022-05-27T07:58:44.845360Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Prediction","metadata":{}},{"cell_type":"code","source":"env = riiideducation.make_env()","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:58:46.978136Z","iopub.execute_input":"2022-05-27T07:58:46.978580Z","iopub.status.idle":"2022-05-27T07:58:46.983054Z","shell.execute_reply.started":"2022-05-27T07:58:46.978543Z","shell.execute_reply":"2022-05-27T07:58:46.982214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"iter_test = env.iter_test()","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:58:48.593053Z","iopub.execute_input":"2022-05-27T07:58:48.593458Z","iopub.status.idle":"2022-05-27T07:58:48.597879Z","shell.execute_reply.started":"2022-05-27T07:58:48.593427Z","shell.execute_reply":"2022-05-27T07:58:48.597243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for (test_df, sample_prediction_df) in iter_test:\n    test_df = pd.merge(test_df, user_mean_final, on=['user_id'],  how=\"left\")\n    test_df = pd.merge(test_df, content_mean_final, on=['content_id'],  how=\"left\")\n    \n    test_df['answered_correctly_user_mean'].fillna(0.5,  inplace=True)\n    test_df['answered_correctly_content_mean'].fillna(0.5,  inplace=True)\n    test_df['sum_correct'].fillna(0, inplace=True)\n    test_df['count'].fillna(0, inplace=True)\n    test_df['prior_question_elapsed_time'].fillna(elapsed_time_mean_final, inplace = True)\n    test_df['prior_question_had_explanation'].fillna(False, inplace=True)\n    test_df[\"prior_question_had_explanation_enc\"] = lencoder.transform(test_df[\"prior_question_had_explanation\"])\n\n    # fit transform cnn\n    X = scaler.transform(test_df[['answered_correctly_user_mean', 'answered_correctly_content_mean', 'sum_correct', 'count',\n                                  'prior_question_elapsed_time', 'prior_question_had_explanation_enc']])\n    test_df['answered_correctly'] = model.predict(X.reshape(X.shape[0], X.shape[1], 1))\n    \n    env.predict(test_df.loc[test_df['content_type_id'] == 0, ['row_id', 'answered_correctly']])","metadata":{"execution":{"iopub.status.busy":"2022-05-27T07:58:50.060110Z","iopub.execute_input":"2022-05-27T07:58:50.060777Z","iopub.status.idle":"2022-05-27T07:58:50.362674Z","shell.execute_reply.started":"2022-05-27T07:58:50.060733Z","shell.execute_reply":"2022-05-27T07:58:50.361870Z"},"trusted":true},"execution_count":null,"outputs":[]}]}