{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport gc\n\nimport lightgbm as lgb\n\nimport riiideducation\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Notebook by Braysen Goodwin\n\n## Heavily based off of: https://www.kaggle.com/erikbruin/riiid-comprehensive-eda-baseline by Erik Bruin"},{"metadata":{},"cell_type":"markdown","source":"# Read In Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\n\ntrain = pd.read_pickle(\"../input/riiid-train-data-multiple-formats/riiid_train.pkl.gzip\")\n\nprint(\"Train size:\", train.shape)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train.head()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Preprocess Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"features = ['content_id', 'timestamp', 'content_type_id', 'task_container_id', 'prior_question_elapsed_time', 'prior_question_had_explanation']\n\ndef setupDataframes(dataframe, garbageCollect=False, includeLabels = False):\n    \"\"\"\n    normalizes the dataframe by filling the missing values with special values, \n      conveting to the correct type, and only keeping the necessary data.\n    \n    params:\n      dataframe - the pandas dataframe to normalize\n      garbageCollect = False - whether to garbage collect after memory intensive operations\n      includeLabels - should include also return the labels\n    \n    returns:\n          data\n            data - a pandas dataframe with the correct data to run the model on\n        or \n          data, labels\n            data - a pandas dataframe with the correct data to run the model on\n            lables - the target labels for each row\n    \"\"\"\n    data = dataframe[features]\n    \n    data['content_type_id'] = data['content_type_id'].replace(np.nan, -1)\n    data['prior_question_elapsed_time'] = data['prior_question_elapsed_time'].replace(np.nan, -1)\n    data['prior_question_had_explanation'] = data['prior_question_had_explanation'].replace(np.nan, -1)\n    data['prior_question_had_explanation'] = data['prior_question_had_explanation'].apply(lambda x: -1 if x is None else int(x))\n    \n    if garbageCollect:\n        gc.collect()\n\n    data['content_type_id'] = data['content_type_id'].astype('int32')\n    data['prior_question_had_explanation'] = data['prior_question_had_explanation'].astype('int32')\n\n    if garbageCollect:\n        gc.collect()\n    \n    if includeLabels:\n        return data, dataframe['answered_correctly']\n    \n    return data\n    \n    \n    \n    \n    \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train, labels = setupDataframes(train, garbageCollect=True, includeLabels=True)\n\ngc.collect()\n\ntrain.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"trainingCount = 90000000\n\n# convert the dataset into an object the model can understand\ntrain_dataset = lgb.Dataset(train[:trainingCount], labels[:trainingCount])\nvalid_dataset = lgb.Dataset(train[trainingCount:], labels[trainingCount:])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Make and train the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"%%time\nmodel = lgb.train(\n    {'objective': 'binary', 'metric': 'auc'}, \n    train_dataset,\n    valid_sets=[train_dataset, valid_dataset],\n    verbose_eval=50,\n    num_boost_round=10000,\n    early_stopping_rounds=8\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"gc.collect()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Create Submission"},{"metadata":{"trusted":true},"cell_type":"code","source":"env = riiideducation.make_env()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"for (test_df, sample_prediction_df) in env.iter_test():\n    tesdata = setupDataframes(test_df)\n    test_df['answered_correctly'] =  model.predict(tesdata[features])\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}