{"cells":[{"metadata":{},"cell_type":"markdown","source":"<h1><center>Riiid! Answer Correctness Prediction. Data Analysis and visualization.</center></h1>\n\n<center><img src=\"https://www.riiid.co/assets/opengraph.png\"></center>\n\n\n"},{"metadata":{},"cell_type":"markdown","source":"#### In this competition, your challenge is to create algorithms for \"Knowledge Tracing,\" the modeling of student knowledge over time. The goal is to accurately predict how students will perform on future interactions. You will pair your machine learning skills using Riiid’s EdNet data.\n\n#### Let's check our data before we start this competition!"},{"metadata":{},"cell_type":"markdown","source":"<a id=\"top\"></a>\n\n<div class=\"list-group\" id=\"list-tab\" role=\"tablist\">\n<h3 class=\"list-group-item list-group-item-action active\" data-toggle=\"list\" style='background:black; border:0' role=\"tab\" aria-controls=\"home\"><center>Quick navigation</center></h3>\n\n* [1. train.csv](#1)\n* [2. questions.csv](#2)\n* [3. lectures.csv](#3)\n* [4. example_test.csv](#4)\n* [5. Modeling](#5)"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"_kg_hide-input":true,"_kg_hide-output":true},"cell_type":"code","source":"import numpy as np\nimport pandas as pd\n\nimport plotly.express as px\nfrom plotly.subplots import make_subplots\nimport plotly.graph_objs as go\n\nfrom sklearn.metrics import roc_auc_score\nfrom sklearn.model_selection import train_test_split\nfrom lightgbm import LGBMClassifier\n\nimport optuna\nfrom optuna.samplers import TPESampler\n\nimport riiideducation\nfrom sklearn.feature_selection import RFE\nfrom sklearn.tree import DecisionTreeClassifier","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"sampler = TPESampler(\n    seed=666\n)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"1\"></a>\n<h2 style='background:black; border:0; color:white'><center>1. train.csv<center><h2>"},{"metadata":{},"cell_type":"markdown","source":"**train.csv**\n\n* **row_id**: (int64) ID code for the row.\n\n* **timestamp**: (int64) the time between this user interaction and the first event from that user.\n\n* **user_id**: (int32) ID code for the user.\n\n* **content_id**: (int16) ID code for the user interaction\n\n* **content_type_id**: (int8) 0 if the event was a question being posed to the user, 1 if the event was the user watching a lecture.\n\n* **task_container_id**: (int16) Id code for the batch of questions or lectures. For example, a user might see three questions in a row before seeing the explanations for any of them. Those three would all share a task_container_id. Monotonically increasing for each user.\n\n* **user_answer**: (int8) the user's answer to the question, if any. Read -1 as null, for lectures.\n\n* **answered_correctly**: (int8) if the user responded correctly. Read -1 as null, for lectures.\n\n* **prior_question_elapsed_time**: (float32) How long it took a user to answer their previous question bundle, ignoring any lectures in between. The value is shared across a single question bundle, and is null for a user's first question bundle or lecture. Note that the time is the total time a user took to solve all the questions in the previous bundle.\n\n* **prior_question_had_explanation**: (bool) Whether or not the user saw an explanation and the correct response(s) after answering the previous question bundle, ignoring any lectures in between. The value is shared across a single question bundle, and is null for a user's first question bundle or lecture. Typically the first several questions a user sees were part of an onboarding diagnostic test where they did not get any feedback."},{"metadata":{"_kg_hide-input":true,"_kg_hide-output":true,"trusted":true},"cell_type":"code","source":"types = {\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}","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(\n    '/kaggle/input/riiid-test-answer-prediction/train.csv', \n    low_memory=False, \n    nrows=10**6, \n    dtype=types\n)\n\ntrain_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Part of missing values for every column')\nprint(train_df.isnull().sum() / len(train_df))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"WIDTH = 800","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = train_df['user_id'].value_counts().reset_index()\n\nds.columns = [\n    'user_id', \n    'count'\n]\n\nds['user_id'] = ds['user_id'].astype(str) + '-'\nds = ds.sort_values(['count']).tail(40)\n\nfig = px.bar(\n    ds, \n    x='count', \n    y='user_id', \n    orientation='h', \n    title='Top 40 users by number of actions', \n    width=WIDTH,\n    height=900 \n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = train_df['user_id'].value_counts().reset_index()\n\nds.columns = [\n    'user_id', \n    'count'\n]\n\nds = ds.sort_values('user_id')\n\nfig = px.line(\n    ds, \n    x='user_id', \n    y='count', \n    title='User action distribution', \n    width=WIDTH,\n    height=600 \n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = train_df['content_id'].value_counts().reset_index()\n\nds.columns = [\n    'content_id', \n    'count'\n]\n\nds['content_id'] = ds['content_id'].astype(str) + '-'\nds = ds.sort_values(['count']).tail(40)\n\nfig = px.bar(\n    ds, \n    x='count', \n    y='content_id', \n    orientation='h', \n    title='Top 40 most useful content_ids',  \n    width=WIDTH,\n    height=900\n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = train_df['content_id'].value_counts().reset_index()\n\nds.columns = [\n    'content_id', \n    'count'\n]\n\nds = ds.sort_values('content_id')\n\nfig = px.line(\n    ds, \n    x='content_id', \n    y='count', \n    title='content_id action distribution', \n    width=WIDTH,\n    height=600 \n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = train_df['content_type_id'].value_counts().reset_index()\n\nds.columns = [\n    'content_type_id', \n    'percent'\n]\n\nds['percent'] /= len(train_df)\n\nfig = px.pie(\n    ds, \n    names='content_type_id', \n    values='percent', \n    title='Lecures & questions', \n    width=WIDTH,\n    height=500 \n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = train_df['task_container_id'].value_counts().reset_index()\n\nds.columns = [\n    'task_container_id', \n    'count'\n]\n\nds['task_container_id'] = ds['task_container_id'].astype(str) + '-'\nds = ds.sort_values(['count']).tail(40)\n\nfig = px.bar(\n    ds, \n    x='count', \n    y='task_container_id', \n    orientation='h', \n    title='Top 40 most useful task_container_ids', \n    width=WIDTH,\n    height=900\n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = train_df['task_container_id'].value_counts().reset_index()\n\nds.columns = [\n    'task_container_id', \n    'count'\n]\n\nds = ds.sort_values('task_container_id')\n\nfig = px.line(\n    ds, \n    x='task_container_id', \n    y='count', \n    title='task_container_id action distribution', \n    width=WIDTH,\n    height=600  \n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = train_df['user_answer'].value_counts().reset_index()\n\nds.columns = [\n    'user_answer', \n    'percent_of_answers'\n]\n\nds['percent_of_answers'] /= len(train_df)\nds = ds.sort_values(['percent_of_answers'])\n\nfig = px.bar(\n    ds, \n    x='user_answer', \n    y='percent_of_answers', \n    orientation='v', \n    title='Percent of user answers for every option', \n    width=WIDTH,\n    height=400 \n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = train_df['answered_correctly'].value_counts().reset_index()\n\nds.columns = [\n    'answered_correctly', \n    'percent_of_answers'\n]\n\nds['percent_of_answers'] /= len(train_df)\nds = ds.sort_values(['percent_of_answers'])\n\nfig = px.pie(\n    ds, \n    names='answered_correctly', \n    values='percent_of_answers', \n    title='Percent of correct answers', \n    width=WIDTH,\n    height=500 \n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig = make_subplots(rows=3, cols=2)\n\ntraces = [\n    go.Bar(\n        x=[\n            -1, 0, 1\n        ], \n        y=[\n            len(train_df[(train_df['user_answer'] == item) & (train_df['answered_correctly'] == -1)]),\n            len(train_df[(train_df['user_answer'] == item) & (train_df['answered_correctly'] == 0)]),\n            len(train_df[(train_df['user_answer'] == item) & (train_df['answered_correctly'] == 1)])\n        ], \n        name='Option: ' + str(item),\n        text = [\n            str(round(100 * len(train_df[(train_df['user_answer'] == item) & (train_df['answered_correctly'] == -1)]) / len(train_df[(train_df['user_answer'] == item)]), 2)) + '%',\n            str(round(100 * len(train_df[(train_df['user_answer'] == item) & (train_df['answered_correctly'] == -0)]) / len(train_df[(train_df['user_answer'] == item)]), 2)) + '%',\n            str(round(100 * len(train_df[(train_df['user_answer'] == item) & (train_df['answered_correctly'] == 1)]) / len(train_df[(train_df['user_answer'] == item)]), 2)) + '%',\n        ],\n        textposition='auto'\n    ) for item in train_df['user_answer'].unique().tolist()\n]\n\nfor i in range(len(traces)):\n    fig.append_trace(\n        traces[i], \n        (i // 2) + 1, \n        (i % 2)  + 1\n    )\n\nfig.update_layout(\n    title_text='Percent of correct answers for every option',\n    height=900,\n    width=WIDTH\n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"fig = px.histogram(\n    train_df, \n    x=\"prior_question_elapsed_time\",\n    nbins=50,\n    title='prior_question_elapsed_time distribution',\n    width=WIDTH,\n    height=500\n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"2\"></a>\n<h2 style='background:black; border:0; color:white'><center>2. questions.csv<center><h2>"},{"metadata":{},"cell_type":"markdown","source":"**questions.csv**: metadata for the questions posed to users.\n\n* **question_id**: foreign key for the train/test content_id column, when the content type is question (0).\n\n* **bundle_id**: code for which questions are served together.\n\n* **correct_answer**: the answer to the question. Can be compared with the train user_answer column to check if the user was right.\n\n* **part**: top level category code for the question.\n\n* **tags**: one or more detailed tag codes for the question. The meaning of the tags will not be provided, but these codes are sufficient for clustering the questions together."},{"metadata":{"trusted":true},"cell_type":"code","source":"questions = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/questions.csv')\nquestions.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Part of missing values for every column')\nprint(questions.isnull().sum() / len(questions))","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"questions['tag'] = questions['tags'].str.split(' ')\nquestions = questions.explode('tag')\nquestions = pd.merge(\n    questions, \n    questions.groupby('question_id')['tag'].count().reset_index(), \n    on='question_id'\n)\n\nquestions = questions.drop(['tag_x'], axis=1)\n\nquestions.columns = [\n    'question_id', \n    'bundle_id', \n    'correct_answer', \n    'part', \n    'tags', \n    'tags_number'\n]\n\nquestions = questions.drop_duplicates()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = questions['correct_answer'].value_counts().reset_index()\n\nds.columns = [\n    'correct_answer', \n    'number_of_answers'\n]\n\nds['correct_answer'] = ds['correct_answer'].astype(str) + '-'\nds = ds.sort_values(['number_of_answers'])\n\nfig = px.bar(\n    ds, \n    x='number_of_answers', \n    y='correct_answer', \n    orientation='h', \n    title='Number of correct answers per group', \n    width=WIDTH,\n    height=300\n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = questions['part'].value_counts().reset_index()\n\nds.columns = [\n    'part', \n    'count'\n]\n\nds['part'] = ds['part'].astype(str) + '-'\nds = ds.sort_values(['count'])\n\nfig = px.bar(\n    ds, \n    x='count', \n    y='part', \n    orientation='h', \n    title='Parts distribution',\n    width=WIDTH,\n    height=400\n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = questions['tags_number'].value_counts().reset_index()\n\nds.columns = [\n    'tags_number', \n    'count'\n]\n\nds['tags_number'] = ds['tags_number'].astype(str) + '-'\nds = ds.sort_values(['tags_number'])\n\nfig = px.bar(\n    ds, \n    x='count', \n    y='tags_number', \n    orientation='h', \n    title='Number tags distribution', \n    width=WIDTH,\n    height=400 \n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"check = questions['tags'].str.split(' ').explode('tags').reset_index()\ncheck = check['tags'].value_counts().reset_index()\n\ncheck.columns = [\n    'tag', \n    'count'\n]\n\ncheck['tag'] = check['tag'].astype(str) + '-'\ncheck = check.sort_values(['count']).tail(40)\n\nfig = px.bar(\n    check, \n    x='count', \n    y='tag', \n    orientation='h', \n    title='Top 40 most useful tags', \n    width=WIDTH,\n    height=900 \n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"3\"></a>\n<h2 style='background:black; border:0; color:white'><center>3. lectures.csv<center><h2>"},{"metadata":{},"cell_type":"markdown","source":"**lectures.csv**: metadata for the lectures watched by users as they progress in their education.\n\n* **lecture_id**: foreign key for the train/test content_id column, when the content type is lecture (1).\n\n* **part**: top level category code for the lecture.\n\n* **tag**: one tag codes for the lecture. The meaning of the tags will not be provided, but these codes are sufficient for clustering the lectures together.\n\n* **type_of**: brief description of the core purpose of the lecture"},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"lectures = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/lectures.csv')\nlectures.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Part of missing values for every column')\nprint(lectures.isnull().sum() / len(lectures))","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = lectures['tag'].value_counts().reset_index()\n\nds.columns = [\n    'tag', \n    'count'\n]\n\nds['tag'] = ds['tag'].astype(str) + '-'\nds = ds.sort_values(['count']).tail(40)\n\nfig = px.bar(\n    ds, \n    x='count', \n    y='tag', \n    orientation='h', \n    title='Top 40 lectures by number of tags', \n    height=900, \n    width=WIDTH\n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = lectures['part'].value_counts().reset_index()\n\nds.columns = [\n    'part', \n    'count'\n]\n\nds['part'] = ds['part'].astype(str) + '-'\nds = ds.sort_values(['count'])\n\nfig = px.bar(\n    ds, \n    x='count', \n    y='part', \n    orientation='h', \n    title='Parts distribution', \n    height=400, \n    width=WIDTH\n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"ds = lectures['type_of'].value_counts().reset_index()\n\nds.columns = [\n    'type_of', \n    'count'\n]\n\nds = ds.sort_values(['count'])\n\nfig = px.bar(\n    ds, \n    x='count', \n    y='type_of', \n    orientation='h', \n    title='type_of column distribution', \n    height=300, \n    width=WIDTH\n)\n\nfig.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"4\"></a>\n<h2 style='background:black; border:0; color:white'><center>4. example_test.csv<center><h2>"},{"metadata":{},"cell_type":"markdown","source":"**example_test.csv** Three sample groups of the test set data as it will be delivered by the time-series API. The format is largely the same as train.csv. There are two different rows that mirror what information the AI tutor actually has available at any given time, but with the user interactions grouped together for the sake of API performance rather than strictly showing information for a single user at a time. Some questions will appear in the hidden test set that have NOT been presented in the train set, emulating the challenge of quickly adapting to modeling newly introduced questions. Their metadata is still in question.csv as usual.\n\nprior_group_responses (string) provides all of the user_answer entries for previous group in a string representation of a list in the first row of the group. All other rows in each group are null. If you are using Python, you will likely want to call eval on the non-null rows. Some rows may be null, or empty lists.\n\nprior_group_answers_correct (string) provides all the answered_correctly field for previous group, with the same format and caveats as prior_group_responses. Some rows may be null, or empty lists."},{"metadata":{"_kg_hide-input":true,"trusted":true},"cell_type":"code","source":"test_ex = pd.read_csv('/kaggle/input/riiid-test-answer-prediction/example_test.csv')\ntest_ex","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"<a id=\"5\"></a>\n<h2 style='background:black; border:0; color:white'><center>5. Modeling<center><h2>"},{"metadata":{"trusted":true},"cell_type":"code","source":"used_data_types_dict = {\n    'timestamp': 'int64',\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}","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(\n    '/kaggle/input/riiid-test-answer-prediction/train.csv',\n    usecols = used_data_types_dict.keys(),\n    dtype=used_data_types_dict, \n    index_col = 0\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"features_df = train_df.iloc[:int(9/10 * len(train_df))]\ntrain_df = train_df.iloc[int(9/10 * len(train_df)):]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_questions_only_df = features_df[features_df['answered_correctly']!=-1]\ngrouped_by_user_df = train_questions_only_df.groupby('user_id')\n\nuser_answers_df = grouped_by_user_df.agg(\n    {\n        'answered_correctly': [\n            'mean', \n            'count', \n            'std', \n            'median', \n            'skew'\n        ]\n    }\n).copy()\n\nuser_answers_df.columns = [\n    'mean_user_accuracy', \n    'questions_answered', \n    'std_user_accuracy', \n    'median_user_accuracy', \n    'skew_user_accuracy'\n]\n\nuser_answers_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"grouped_by_content_df = train_questions_only_df.groupby('content_id')\ncontent_answers_df = grouped_by_content_df.agg(\n    {\n        'answered_correctly': [\n            'mean', \n            'count', \n            'std', \n            'median', \n            'skew'\n        ]\n    }\n).copy()\n\ncontent_answers_df.columns = [\n    'mean_accuracy', \n    'question_asked', \n    'std_accuracy', \n    'median_accuracy', \n    'skew_accuracy'\n]\n\ncontent_answers_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"del features_df\ndel grouped_by_user_df\ndel grouped_by_content_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"features = [\n    'mean_user_accuracy', \n    'questions_answered',\n    'std_user_accuracy', \n    'median_user_accuracy',\n    'skew_user_accuracy',\n    'mean_accuracy', \n    'question_asked',\n    'std_accuracy', \n    'median_accuracy',\n    'prior_question_elapsed_time', \n    'prior_question_had_explanation',\n    'skew_accuracy'\n]\n\ntarget = 'answered_correctly'","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = train_df[train_df[target] != -1]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = train_df.merge(user_answers_df, how='left', on='user_id')\ntrain_df = train_df.merge(content_answers_df, how='left', on='content_id')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df['prior_question_had_explanation'] = train_df['prior_question_had_explanation'].fillna(value=False).astype(bool)\ntrain_df = train_df.fillna(value=0.5)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = train_df[features + [target]]\ntrain_df = train_df.replace([np.inf, -np.inf], np.nan)\ntrain_df = train_df.fillna(0.5)\n\ntrain_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df, test_df = train_test_split(train_df, random_state=666, test_size=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"rfe = RFE(\n    estimator=DecisionTreeClassifier(\n        random_state=666\n    ), \n    n_features_to_select=8\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"rfe.fit(train_df[features], train_df[target])\nX_transformed = rfe.transform(train_df[features])\nX_transformed = pd.DataFrame(X_transformed)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_transformed.columns = ['col_1', 'col_2', 'col_3', 'col_4', 'col_5', 'col_6', 'col_7', 'col_8']\nX_transformed","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_transformed_test = rfe.transform(test_df[features])\nX_transformed_test = pd.DataFrame(X_transformed_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_transformed_test.columns = ['col_1', 'col_2', 'col_3', 'col_4', 'col_5', 'col_6', 'col_7', 'col_8']\nX_transformed_test","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"X_transformed_test['col_1'] = X_transformed_test['col_1'].astype(np.float32)\nX_transformed_test['col_2'] = X_transformed_test['col_2'].astype(np.float32)\nX_transformed_test['col_3'] = X_transformed_test['col_3'].astype(np.int32)\nX_transformed_test['col_4'] = X_transformed_test['col_4'].astype(np.float32)\nX_transformed_test['col_5'] = X_transformed_test['col_5'].astype(np.int32)\nX_transformed_test['col_6'] = X_transformed_test['col_6'].astype(np.int32)\nX_transformed_test['col_7'] = X_transformed_test['col_7'].astype(np.int32)\nX_transformed_test['col_8'] = X_transformed_test['col_8'].astype(np.float32)\n\nX_transformed['col_1'] = X_transformed['col_1'].astype(np.float32)\nX_transformed['col_2'] = X_transformed['col_2'].astype(np.float32)\nX_transformed['col_3'] = X_transformed['col_3'].astype(np.int32)\nX_transformed['col_4'] = X_transformed['col_4'].astype(np.float32)\nX_transformed['col_5'] = X_transformed['col_5'].astype(np.int32)\nX_transformed['col_6'] = X_transformed['col_6'].astype(np.int32)\nX_transformed['col_7'] = X_transformed['col_7'].astype(np.int32)\nX_transformed['col_8'] = X_transformed['col_8'].astype(np.float32)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":" def create_model(trial):\n    num_leaves = trial.suggest_int(\"num_leaves\", 2, 31)\n    n_estimators = trial.suggest_int(\"n_estimators\", 50, 300)\n    max_depth = trial.suggest_int('max_depth', 3, 8)\n    min_child_samples = trial.suggest_int('min_child_samples', 100, 1200)\n    learning_rate = trial.suggest_uniform('learning_rate', 0.0001, 0.99)\n    min_data_in_leaf = trial.suggest_int('min_data_in_leaf', 5, 90)\n    bagging_fraction = trial.suggest_uniform('bagging_fraction', 0.0001, 1.0)\n    feature_fraction = trial.suggest_uniform('feature_fraction', 0.0001, 1.0)\n    \n    model = LGBMClassifier(\n        num_leaves=num_leaves,\n        n_estimators=n_estimators, \n        max_depth=max_depth, \n        min_child_samples=min_child_samples, \n        min_data_in_leaf=min_data_in_leaf,\n        learning_rate=learning_rate,\n        feature_fraction=feature_fraction,\n        random_state=666\n    )\n    return model\n\ndef objective(trial):\n    model = create_model(trial)\n    model.fit(X_transformed, train_df[target])\n    score = roc_auc_score(\n        test_df[target].values, \n        model.predict_proba(X_transformed_test)[:,1]\n    )\n    return score\n\n# uncomment to use optuna\n# final params is in study.best_params\n# study = optuna.create_study(direction=\"maximize\", sampler=sampler)\n# study.optimize(objective, n_trials=70)\n# params = study.best_params\n# params['random_state'] = 666\n\n\n\nparams = {\n    'bagging_fraction': 0.5817242323514327,\n    'feature_fraction': 0.6884588361650144,\n    'learning_rate': 0.42887924851375825, \n    'max_depth': 6,\n    'min_child_samples': 946, \n    'min_data_in_leaf': 47, \n    'n_estimators': 169,\n    'num_leaves': 29,\n    'random_state': 666\n}\n\nmodel = LGBMClassifier(\n    **params\n)\n\nmodel.fit(X_transformed, train_df[target])\nprint('LGB score: ', roc_auc_score(test_df[target].values, model.predict_proba(X_transformed_test)[:,1]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"env = riiideducation.make_env()\niter_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 = test_df.merge(user_answers_df, how='left', on='user_id')\n    test_df = test_df.merge(content_answers_df, how='left', on='content_id')\n    test_df['prior_question_had_explanation'] = test_df['prior_question_had_explanation'].fillna(value=False).astype(bool)\n    test_df.fillna(value = 0.5, inplace = True)\n    \n    test = rfe.transform(test_df)\n    test = pd.DataFrame(test)\n    test['col_1'] = test['col_1'].astype(np.float32)\n    test['col_2'] = test['col_2'].astype(np.float32)\n    test['col_3'] = test['col_3'].astype(np.int32)\n    test['col_4'] = test['col_4'].astype(np.float32)\n    test['col_5'] = test['col_5'].astype(np.int32)\n    test['col_6'] = test['col_6'].astype(np.int32)\n    test['col_7'] = test['col_7'].astype(np.int32)\n    test['col_8'] = test['col_8'].astype(np.float32)\n\n\n    test_df['answered_correctly'] = model.predict_proba(test)[:,1]\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}