{"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":"**Google AI4Code – Understand Code in Python Notebooks\nPredict the relationship between code and comments**","metadata":{}},{"cell_type":"markdown","source":"**Setup**","metadata":{}},{"cell_type":"code","source":"import json\nfrom pathlib import Path\n\nimport numpy as np\nimport pandas as pd\nfrom scipy import sparse\nfrom tqdm import tqdm\n\npd.options.display.width = 180\npd.options.display.max_colwidth = 120\n\ndata_dir = Path('../input/AI4Code')","metadata":{"execution":{"iopub.status.busy":"2022-05-12T05:59:12.46946Z","iopub.execute_input":"2022-05-12T05:59:12.470109Z","iopub.status.idle":"2022-05-12T05:59:12.584962Z","shell.execute_reply.started":"2022-05-12T05:59:12.469984Z","shell.execute_reply":"2022-05-12T05:59:12.584Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Load Data**\n\nThe notebooks are stored as individiual JSON files. They've been cleaned of the usual metadata present in Jupyter notebooks, leaving only the cell_type and source. The Data page on the competition website has the full documentation of this dataset.\n\nWe'll load the notebooks here and join them into a dataframe for easier processing. The full set of training data takes quite a while to load, so we'll just use a subset for this demonstration.","metadata":{}},{"cell_type":"code","source":"NUM_TRAIN = 10000\n\n\ndef read_notebook(path):\n    return (\n        pd.read_json(\n            path,\n            dtype={'cell_type': 'category', 'source': 'str'})\n        .assign(id=path.stem)\n        .rename_axis('cell_id')\n    )\n\n\npaths_train = list((data_dir / 'train').glob('*.json'))[:NUM_TRAIN]\nnotebooks_train = [\n    read_notebook(path) for path in tqdm(paths_train, desc='Train NBs')\n]\ndf = (\n    pd.concat(notebooks_train)\n    .set_index('id', append=True)\n    .swaplevel()\n    .sort_index(level='id', sort_remaining=False)\n)\n\ndf","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:00:23.521521Z","iopub.execute_input":"2022-05-12T06:00:23.521853Z","iopub.status.idle":"2022-05-12T06:02:10.370884Z","shell.execute_reply.started":"2022-05-12T06:00:23.521819Z","shell.execute_reply":"2022-05-12T06:02:10.369989Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get an example notebook\nnb_id = df.index.unique('id')[6]\nprint('Notebook:', nb_id)\n\nprint(\"The disordered notebook:\")\nnb = df.loc[nb_id, :]\ndisplay(nb)\nprint()","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:02:13.264714Z","iopub.execute_input":"2022-05-12T06:02:13.265024Z","iopub.status.idle":"2022-05-12T06:02:13.291736Z","shell.execute_reply.started":"2022-05-12T06:02:13.264991Z","shell.execute_reply":"2022-05-12T06:02:13.290917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Ordering the Cells**","metadata":{}},{"cell_type":"code","source":"df_orders = pd.read_csv(\n    data_dir / 'train_orders.csv',\n    index_col='id',\n    squeeze=True,\n).str.split()  # Split the string representation of cell_ids into a list\n\ndf_orders","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:02:49.711813Z","iopub.execute_input":"2022-05-12T06:02:49.712267Z","iopub.status.idle":"2022-05-12T06:02:52.808144Z","shell.execute_reply.started":"2022-05-12T06:02:49.712235Z","shell.execute_reply":"2022-05-12T06:02:52.807181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Get the correct order\ncell_order = df_orders.loc[nb_id]\n\nprint(\"The ordered notebook:\")\nnb.loc[cell_order, :]","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:03:00.985672Z","iopub.execute_input":"2022-05-12T06:03:00.985971Z","iopub.status.idle":"2022-05-12T06:03:01.004133Z","shell.execute_reply.started":"2022-05-12T06:03:00.985938Z","shell.execute_reply":"2022-05-12T06:03:01.003262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#The correct numeric position of a cell we will call the rank of the cell. We can find the ranks of the cells within a notebook by referencing the true ordering of cell ids as given in train_orders.csv\ndef get_ranks(base, derived):\n    return [base.index(d) for d in derived]\n\ncell_ranks = get_ranks(cell_order, list(nb.index))\nnb.insert(0, 'rank', cell_ranks)\n\nnb","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:03:31.737489Z","iopub.execute_input":"2022-05-12T06:03:31.737889Z","iopub.status.idle":"2022-05-12T06:03:31.756253Z","shell.execute_reply.started":"2022-05-12T06:03:31.737844Z","shell.execute_reply":"2022-05-12T06:03:31.755263Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Sorting a notebook by the cell ranks is another way to order the notebook.\nfrom pandas.testing import assert_frame_equal\n\nassert_frame_equal(nb.loc[cell_order, :], nb.sort_values('rank'))","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:04:05.466773Z","iopub.execute_input":"2022-05-12T06:04:05.467083Z","iopub.status.idle":"2022-05-12T06:04:05.477123Z","shell.execute_reply.started":"2022-05-12T06:04:05.467054Z","shell.execute_reply":"2022-05-12T06:04:05.475873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#The algorithm we'll be using for our baseline model uses the cell ranks as the target, so let's create a dataframe of the ranks for each notebook.\ndf_orders_ = df_orders.to_frame().join(\n    df.reset_index('cell_id').groupby('id')['cell_id'].apply(list),\n    how='right',\n)\n\nranks = {}\nfor id_, cell_order, cell_id in df_orders_.itertuples():\n    ranks[id_] = {'cell_id': cell_id, 'rank': get_ranks(cell_order, cell_id)}\n\ndf_ranks = (\n    pd.DataFrame\n    .from_dict(ranks, orient='index')\n    .rename_axis('id')\n    .apply(pd.Series.explode)\n    .set_index('cell_id', append=True)\n)\n\ndf_ranks","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:04:29.85684Z","iopub.execute_input":"2022-05-12T06:04:29.857154Z","iopub.status.idle":"2022-05-12T06:04:33.084221Z","shell.execute_reply.started":"2022-05-12T06:04:29.857118Z","shell.execute_reply":"2022-05-12T06:04:33.083243Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Splits**","metadata":{}},{"cell_type":"code","source":"df_ancestors = pd.read_csv(data_dir / 'train_ancestors.csv', index_col='id')\ndf_ancestors","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:04:59.839801Z","iopub.execute_input":"2022-05-12T06:04:59.84015Z","iopub.status.idle":"2022-05-12T06:05:00.109508Z","shell.execute_reply.started":"2022-05-12T06:04:59.840117Z","shell.execute_reply":"2022-05-12T06:05:00.108575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.model_selection import GroupShuffleSplit\n\nNVALID = 0.1  # size of validation set\n\nsplitter = GroupShuffleSplit(n_splits=1, test_size=NVALID, random_state=0)\n\n# Split, keeping notebooks with a common origin (ancestor_id) together\nids = df.index.unique('id')\nancestors = df_ancestors.loc[ids, 'ancestor_id']\nids_train, ids_valid = next(splitter.split(ids, groups=ancestors))\nids_train, ids_valid = ids[ids_train], ids[ids_valid]\n\ndf_train = df.loc[ids_train, :]\ndf_valid = df.loc[ids_valid, :]","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:05:15.553013Z","iopub.execute_input":"2022-05-12T06:05:15.553652Z","iopub.status.idle":"2022-05-12T06:05:16.696274Z","shell.execute_reply.started":"2022-05-12T06:05:15.553611Z","shell.execute_reply":"2022-05-12T06:05:16.695124Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Feature Engineering**","metadata":{}},{"cell_type":"code","source":"from sklearn.feature_extraction.text import TfidfVectorizer\n\n# Training set\ntfidf = TfidfVectorizer(min_df=0.01)\nX_train = tfidf.fit_transform(df_train['source'].astype(str))\n# Rank of each cell within the notebook\ny_train = df_ranks.loc[ids_train].to_numpy()\n# Number of cells in each notebook\ngroups = df_ranks.loc[ids_train].groupby('id').size().to_numpy()","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:05:42.109862Z","iopub.execute_input":"2022-05-12T06:05:42.110166Z","iopub.status.idle":"2022-05-12T06:06:00.651175Z","shell.execute_reply.started":"2022-05-12T06:05:42.110136Z","shell.execute_reply":"2022-05-12T06:06:00.650109Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Add code cell ordering\nX_train = sparse.hstack((\n    X_train,\n    np.where(\n        df_train['cell_type'] == 'code',\n        df_train.groupby(['id', 'cell_type']).cumcount().to_numpy() + 1,\n        0,\n    ).reshape(-1, 1)\n))\nprint(X_train.shape)","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:06:04.437186Z","iopub.execute_input":"2022-05-12T06:06:04.437458Z","iopub.status.idle":"2022-05-12T06:06:04.72732Z","shell.execute_reply.started":"2022-05-12T06:06:04.437429Z","shell.execute_reply":"2022-05-12T06:06:04.726277Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Train**","metadata":{}},{"cell_type":"code","source":"from xgboost import XGBRanker\n\nmodel = XGBRanker(\n    min_child_weight=10,\n    subsample=0.5,\n    tree_method='hist',\n)\nmodel.fit(X_train, y_train, group=groups)","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:06:34.230585Z","iopub.execute_input":"2022-05-12T06:06:34.231333Z","iopub.status.idle":"2022-05-12T06:06:47.053949Z","shell.execute_reply.started":"2022-05-12T06:06:34.23129Z","shell.execute_reply":"2022-05-12T06:06:47.052955Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Validation set**","metadata":{}},{"cell_type":"code","source":"# Validation set\nX_valid = tfidf.transform(df_valid['source'].astype(str))\n# The metric uses cell ids\ny_valid = df_orders.loc[ids_valid]\n\nX_valid = sparse.hstack((\n    X_valid,\n    np.where(\n        df_valid['cell_type'] == 'code',\n        df_valid.groupby(['id', 'cell_type']).cumcount().to_numpy() + 1,\n        0,\n    ).reshape(-1, 1)\n))","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:07:08.129969Z","iopub.execute_input":"2022-05-12T06:07:08.130279Z","iopub.status.idle":"2022-05-12T06:07:09.966306Z","shell.execute_reply.started":"2022-05-12T06:07:08.130248Z","shell.execute_reply":"2022-05-12T06:07:09.965483Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = pd.DataFrame({'rank': model.predict(X_valid)}, index=df_valid.index)\ny_pred = (\n    y_pred\n    .sort_values(['id', 'rank'])  # Sort the cells in each notebook by their rank.\n                                  # The cell_ids are now in the order the model predicted.\n    .reset_index('cell_id')  # Convert the cell_id index into a column.\n    .groupby('id')['cell_id'].apply(list)  # Group the cell_ids for each notebook into a list.\n)\ny_pred.head(10)","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:07:19.730409Z","iopub.execute_input":"2022-05-12T06:07:19.730715Z","iopub.status.idle":"2022-05-12T06:07:19.920519Z","shell.execute_reply.started":"2022-05-12T06:07:19.730684Z","shell.execute_reply":"2022-05-12T06:07:19.919531Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nb_id = df_valid.index.get_level_values('id').unique()[8]\n\ndisplay(df.loc[nb_id])\ndisplay(df.loc[nb_id].loc[y_pred.loc[nb_id]])","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:07:32.113633Z","iopub.execute_input":"2022-05-12T06:07:32.113909Z","iopub.status.idle":"2022-05-12T06:07:32.148347Z","shell.execute_reply.started":"2022-05-12T06:07:32.113881Z","shell.execute_reply":"2022-05-12T06:07:32.147256Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Metric**","metadata":{}},{"cell_type":"code","source":"from bisect import bisect\n\n\ndef count_inversions(a):\n    inversions = 0\n    sorted_so_far = []\n    for i, u in enumerate(a):\n        j = bisect(sorted_so_far, u)\n        inversions += i - j\n        sorted_so_far.insert(j, u)\n    return inversions\n\n\ndef kendall_tau(ground_truth, predictions):\n    total_inversions = 0\n    total_2max = 0  # twice the maximum possible inversions across all instances\n    for gt, pred in zip(ground_truth, predictions):\n        ranks = [gt.index(x) for x in pred]  # rank predicted order in terms of ground truth\n        total_inversions += count_inversions(ranks)\n        n = len(gt)\n        total_2max += n * (n - 1)\n    return 1 - 4 * total_inversions / total_2max","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:08:15.578872Z","iopub.execute_input":"2022-05-12T06:08:15.579178Z","iopub.status.idle":"2022-05-12T06:08:15.587049Z","shell.execute_reply.started":"2022-05-12T06:08:15.57914Z","shell.execute_reply":"2022-05-12T06:08:15.58604Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_dummy = df_valid.reset_index('cell_id').groupby('id')['cell_id'].apply(list)\nkendall_tau(y_valid, y_dummy)","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:08:26.363754Z","iopub.execute_input":"2022-05-12T06:08:26.364099Z","iopub.status.idle":"2022-05-12T06:08:26.511737Z","shell.execute_reply.started":"2022-05-12T06:08:26.364061Z","shell.execute_reply":"2022-05-12T06:08:26.51081Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"kendall_tau(y_valid, y_pred)","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:08:35.140727Z","iopub.execute_input":"2022-05-12T06:08:35.141006Z","iopub.status.idle":"2022-05-12T06:08:35.239684Z","shell.execute_reply.started":"2022-05-12T06:08:35.140977Z","shell.execute_reply":"2022-05-12T06:08:35.238906Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Submission**","metadata":{}},{"cell_type":"code","source":"paths_test = list((data_dir / 'test').glob('*.json'))\nnotebooks_test = [\n    read_notebook(path) for path in tqdm(paths_test, desc='Test NBs')\n]\ndf_test = (\n    pd.concat(notebooks_test)\n    .set_index('id', append=True)\n    .swaplevel()\n    .sort_index(level='id', sort_remaining=False)\n)","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:09:06.302531Z","iopub.execute_input":"2022-05-12T06:09:06.302804Z","iopub.status.idle":"2022-05-12T06:09:06.365324Z","shell.execute_reply.started":"2022-05-12T06:09:06.302776Z","shell.execute_reply":"2022-05-12T06:09:06.364682Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X_test = tfidf.transform(df_test['source'].astype(str))\nX_test = sparse.hstack((\n    X_test,\n    np.where(\n        df_test['cell_type'] == 'code',\n        df_test.groupby(['id', 'cell_type']).cumcount().to_numpy() + 1,\n        0,\n    ).reshape(-1, 1)\n))","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:09:17.347502Z","iopub.execute_input":"2022-05-12T06:09:17.347776Z","iopub.status.idle":"2022-05-12T06:09:17.367595Z","shell.execute_reply.started":"2022-05-12T06:09:17.347747Z","shell.execute_reply":"2022-05-12T06:09:17.366662Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_infer = pd.DataFrame({'rank': model.predict(X_test)}, index=df_test.index)\ny_infer = y_infer.sort_values(['id', 'rank']).reset_index('cell_id').groupby('id')['cell_id'].apply(list)\ny_infer","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:09:25.406447Z","iopub.execute_input":"2022-05-12T06:09:25.406913Z","iopub.status.idle":"2022-05-12T06:09:25.438645Z","shell.execute_reply.started":"2022-05-12T06:09:25.406879Z","shell.execute_reply":"2022-05-12T06:09:25.437879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_sample = pd.read_csv(data_dir / 'sample_submission.csv', index_col='id', squeeze=True)\ny_sample","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:09:34.987358Z","iopub.execute_input":"2022-05-12T06:09:34.987838Z","iopub.status.idle":"2022-05-12T06:09:35.007704Z","shell.execute_reply.started":"2022-05-12T06:09:34.987794Z","shell.execute_reply":"2022-05-12T06:09:35.006706Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_submit = (\n    y_infer\n    .apply(' '.join)  # list of ids -> string of ids\n    .rename_axis('id')\n    .rename('cell_order')\n)\ny_submit","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:09:45.674008Z","iopub.execute_input":"2022-05-12T06:09:45.674295Z","iopub.status.idle":"2022-05-12T06:09:45.684173Z","shell.execute_reply.started":"2022-05-12T06:09:45.674261Z","shell.execute_reply":"2022-05-12T06:09:45.683062Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_submit.to_csv('submission.csv')","metadata":{"execution":{"iopub.status.busy":"2022-05-12T06:09:56.03496Z","iopub.execute_input":"2022-05-12T06:09:56.035415Z","iopub.status.idle":"2022-05-12T06:09:56.043542Z","shell.execute_reply.started":"2022-05-12T06:09:56.035365Z","shell.execute_reply":"2022-05-12T06:09:56.042728Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}