{"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":"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":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-07-13T07:23:02.590373Z","iopub.execute_input":"2022-07-13T07:23:02.590901Z","iopub.status.idle":"2022-07-13T07:23:02.705416Z","shell.execute_reply.started":"2022-07-13T07:23:02.590784Z","shell.execute_reply":"2022-07-13T07:23:02.704141Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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]","metadata":{"execution":{"iopub.status.busy":"2022-07-13T07:23:04.926766Z","iopub.execute_input":"2022-07-13T07:23:04.927666Z","iopub.status.idle":"2022-07-13T07:24:46.402114Z","shell.execute_reply.started":"2022-07-13T07:23:04.927588Z","shell.execute_reply":"2022-07-13T07:24:46.400832Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = (\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-07-13T07:27:21.589364Z","iopub.execute_input":"2022-07-13T07:27:21.590470Z","iopub.status.idle":"2022-07-13T07:27:24.325323Z","shell.execute_reply.started":"2022-07-13T07:27:21.590419Z","shell.execute_reply":"2022-07-13T07:27:24.324001Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"nb_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-07-13T07:27:35.802247Z","iopub.execute_input":"2022-07-13T07:27:35.802645Z","iopub.status.idle":"2022-07-13T07:27:35.832046Z","shell.execute_reply.started":"2022-07-13T07:27:35.802594Z","shell.execute_reply":"2022-07-13T07:27:35.830596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07-13T07:27:50.563327Z","iopub.execute_input":"2022-07-13T07:27:50.563780Z","iopub.status.idle":"2022-07-13T07:27:53.811297Z","shell.execute_reply.started":"2022-07-13T07:27:50.563728Z","shell.execute_reply":"2022-07-13T07:27:53.809877Z"},"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-07-13T07:28:07.566126Z","iopub.execute_input":"2022-07-13T07:28:07.566556Z","iopub.status.idle":"2022-07-13T07:28:07.584562Z","shell.execute_reply.started":"2022-07-13T07:28:07.566518Z","shell.execute_reply":"2022-07-13T07:28:07.583052Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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-07-13T07:28:26.429411Z","iopub.execute_input":"2022-07-13T07:28:26.429824Z","iopub.status.idle":"2022-07-13T07:28:26.444473Z","shell.execute_reply.started":"2022-07-13T07:28:26.429787Z","shell.execute_reply":"2022-07-13T07:28:26.443346Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from pandas.testing import assert_frame_equal\n\nassert_frame_equal(nb.loc[cell_order, :], nb.sort_values('rank'))","metadata":{"execution":{"iopub.status.busy":"2022-07-13T07:28:40.563969Z","iopub.execute_input":"2022-07-13T07:28:40.564374Z","iopub.status.idle":"2022-07-13T07:28:40.572802Z","shell.execute_reply.started":"2022-07-13T07:28:40.564341Z","shell.execute_reply":"2022-07-13T07:28:40.571615Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df_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-07-13T07:28:58.560497Z","iopub.execute_input":"2022-07-13T07:28:58.560881Z","iopub.status.idle":"2022-07-13T07:29:01.148422Z","shell.execute_reply.started":"2022-07-13T07:28:58.560848Z","shell.execute_reply":"2022-07-13T07:29:01.147191Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07-13T07:29:17.633423Z","iopub.execute_input":"2022-07-13T07:29:17.633914Z","iopub.status.idle":"2022-07-13T07:29:17.903811Z","shell.execute_reply.started":"2022-07-13T07:29:17.633859Z","shell.execute_reply":"2022-07-13T07:29:17.902633Z"},"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-07-13T07:29:30.042599Z","iopub.execute_input":"2022-07-13T07:29:30.043023Z","iopub.status.idle":"2022-07-13T07:29:30.660719Z","shell.execute_reply.started":"2022-07-13T07:29:30.042987Z","shell.execute_reply":"2022-07-13T07:29:30.659373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07-13T07:29:48.837925Z","iopub.execute_input":"2022-07-13T07:29:48.838393Z","iopub.status.idle":"2022-07-13T07:30:02.020441Z","shell.execute_reply.started":"2022-07-13T07:29:48.838344Z","shell.execute_reply":"2022-07-13T07:30:02.019320Z"},"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-07-13T07:30:04.037899Z","iopub.execute_input":"2022-07-13T07:30:04.038303Z","iopub.status.idle":"2022-07-13T07:30:04.305321Z","shell.execute_reply.started":"2022-07-13T07:30:04.038270Z","shell.execute_reply":"2022-07-13T07:30:04.303958Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07-13T07:30:20.728778Z","iopub.execute_input":"2022-07-13T07:30:20.729179Z","iopub.status.idle":"2022-07-13T07:30:33.500693Z","shell.execute_reply.started":"2022-07-13T07:30:20.729143Z","shell.execute_reply":"2022-07-13T07:30:33.499885Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07-13T07:31:19.833622Z","iopub.execute_input":"2022-07-13T07:31:19.834050Z","iopub.status.idle":"2022-07-13T07:31:21.096814Z","shell.execute_reply.started":"2022-07-13T07:31:19.834014Z","shell.execute_reply":"2022-07-13T07:31:21.095474Z"},"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-07-13T07:31:35.330511Z","iopub.execute_input":"2022-07-13T07:31:35.331442Z","iopub.status.idle":"2022-07-13T07:31:35.511293Z","shell.execute_reply.started":"2022-07-13T07:31:35.331369Z","shell.execute_reply":"2022-07-13T07:31:35.509999Z"},"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-07-13T07:31:48.458680Z","iopub.execute_input":"2022-07-13T07:31:48.459974Z","iopub.status.idle":"2022-07-13T07:31:48.490453Z","shell.execute_reply.started":"2022-07-13T07:31:48.459912Z","shell.execute_reply":"2022-07-13T07:31:48.489544Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07-13T07:32:04.574033Z","iopub.execute_input":"2022-07-13T07:32:04.574419Z","iopub.status.idle":"2022-07-13T07:32:04.583148Z","shell.execute_reply.started":"2022-07-13T07:32:04.574387Z","shell.execute_reply":"2022-07-13T07:32:04.581712Z"},"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-07-13T07:32:15.046975Z","iopub.execute_input":"2022-07-13T07:32:15.047383Z","iopub.status.idle":"2022-07-13T07:32:15.162924Z","shell.execute_reply.started":"2022-07-13T07:32:15.047346Z","shell.execute_reply":"2022-07-13T07:32:15.161731Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"kendall_tau(y_valid, y_pred)","metadata":{"execution":{"iopub.status.busy":"2022-07-13T07:32:27.151089Z","iopub.execute_input":"2022-07-13T07:32:27.151506Z","iopub.status.idle":"2022-07-13T07:32:27.222895Z","shell.execute_reply.started":"2022-07-13T07:32:27.151473Z","shell.execute_reply":"2022-07-13T07:32:27.221408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-07-13T07:32:38.265984Z","iopub.execute_input":"2022-07-13T07:32:38.266581Z","iopub.status.idle":"2022-07-13T07:32:38.325921Z","shell.execute_reply.started":"2022-07-13T07:32:38.266529Z","shell.execute_reply":"2022-07-13T07:32:38.324931Z"},"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-07-13T07:32:50.387471Z","iopub.execute_input":"2022-07-13T07:32:50.388675Z","iopub.status.idle":"2022-07-13T07:32:50.405195Z","shell.execute_reply.started":"2022-07-13T07:32:50.388614Z","shell.execute_reply":"2022-07-13T07:32:50.404020Z"},"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-07-13T07:33:01.981560Z","iopub.execute_input":"2022-07-13T07:33:01.981982Z","iopub.status.idle":"2022-07-13T07:33:02.017154Z","shell.execute_reply.started":"2022-07-13T07:33:01.981946Z","shell.execute_reply":"2022-07-13T07:33:02.015726Z"},"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-07-13T07:33:13.174651Z","iopub.execute_input":"2022-07-13T07:33:13.175066Z","iopub.status.idle":"2022-07-13T07:33:13.191154Z","shell.execute_reply.started":"2022-07-13T07:33:13.175031Z","shell.execute_reply":"2022-07-13T07:33:13.189695Z"},"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-07-13T07:33:24.863809Z","iopub.execute_input":"2022-07-13T07:33:24.864233Z","iopub.status.idle":"2022-07-13T07:33:24.874125Z","shell.execute_reply.started":"2022-07-13T07:33:24.864183Z","shell.execute_reply":"2022-07-13T07:33:24.872979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_submit.to_csv('submission.csv')","metadata":{"execution":{"iopub.status.busy":"2022-07-13T07:33:33.496361Z","iopub.execute_input":"2022-07-13T07:33:33.496789Z","iopub.status.idle":"2022-07-13T07:33:33.505719Z","shell.execute_reply.started":"2022-07-13T07:33:33.496756Z","shell.execute_reply":"2022-07-13T07:33:33.504552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}