{"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-06-24T18:24:35.954104Z","iopub.execute_input":"2022-06-24T18:24:35.954601Z","iopub.status.idle":"2022-06-24T18:24:36.03894Z","shell.execute_reply.started":"2022-06-24T18:24:35.954532Z","shell.execute_reply":"2022-06-24T18:24:36.038149Z"},"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]\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-06-24T18:24:44.525415Z","iopub.execute_input":"2022-06-24T18:24:44.525722Z","iopub.status.idle":"2022-06-24T18:26:42.392845Z","shell.execute_reply.started":"2022-06-24T18:24:44.525698Z","shell.execute_reply":"2022-06-24T18:26:42.391715Z"},"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-06-24T18:26:42.394768Z","iopub.execute_input":"2022-06-24T18:26:42.395082Z","iopub.status.idle":"2022-06-24T18:26:42.416774Z","shell.execute_reply.started":"2022-06-24T18:26:42.395054Z","shell.execute_reply":"2022-06-24T18:26:42.415945Z"},"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-06-24T18:26:42.4178Z","iopub.execute_input":"2022-06-24T18:26:42.418431Z","iopub.status.idle":"2022-06-24T18:26:45.544646Z","shell.execute_reply.started":"2022-06-24T18:26:42.4184Z","shell.execute_reply":"2022-06-24T18:26:45.543647Z"},"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-06-24T18:26:51.696021Z","iopub.execute_input":"2022-06-24T18:26:51.696373Z","iopub.status.idle":"2022-06-24T18:26:51.718469Z","shell.execute_reply.started":"2022-06-24T18:26:51.696345Z","shell.execute_reply":"2022-06-24T18:26:51.717493Z"},"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-06-24T18:27:18.557261Z","iopub.execute_input":"2022-06-24T18:27:18.557897Z","iopub.status.idle":"2022-06-24T18:27:18.570353Z","shell.execute_reply.started":"2022-06-24T18:27:18.557873Z","shell.execute_reply":"2022-06-24T18:27:18.569549Z"},"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-06-24T18:27:38.326284Z","iopub.execute_input":"2022-06-24T18:27:38.326554Z","iopub.status.idle":"2022-06-24T18:27:38.335536Z","shell.execute_reply.started":"2022-06-24T18:27:38.326531Z","shell.execute_reply":"2022-06-24T18:27:38.334506Z"},"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-06-24T18:27:50.053819Z","iopub.execute_input":"2022-06-24T18:27:50.054128Z","iopub.status.idle":"2022-06-24T18:27:52.332098Z","shell.execute_reply.started":"2022-06-24T18:27:50.054106Z","shell.execute_reply":"2022-06-24T18:27:52.331036Z"},"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-06-24T18:28:08.773592Z","iopub.execute_input":"2022-06-24T18:28:08.773951Z","iopub.status.idle":"2022-06-24T18:28:08.997305Z","shell.execute_reply.started":"2022-06-24T18:28:08.773923Z","shell.execute_reply":"2022-06-24T18:28:08.996033Z"},"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-06-24T18:28:30.577442Z","iopub.execute_input":"2022-06-24T18:28:30.577727Z","iopub.status.idle":"2022-06-24T18:28:31.021232Z","shell.execute_reply.started":"2022-06-24T18:28:30.577705Z","shell.execute_reply":"2022-06-24T18:28:31.0202Z"},"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-06-24T18:28:47.579083Z","iopub.execute_input":"2022-06-24T18:28:47.57942Z","iopub.status.idle":"2022-06-24T18:28:58.921149Z","shell.execute_reply.started":"2022-06-24T18:28:47.579391Z","shell.execute_reply":"2022-06-24T18:28:58.919988Z"},"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-06-24T18:28:58.922712Z","iopub.execute_input":"2022-06-24T18:28:58.923053Z","iopub.status.idle":"2022-06-24T18:28:59.149072Z","shell.execute_reply.started":"2022-06-24T18:28:58.92302Z","shell.execute_reply":"2022-06-24T18:28:59.14778Z"},"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-06-24T18:29:05.69951Z","iopub.execute_input":"2022-06-24T18:29:05.6998Z","iopub.status.idle":"2022-06-24T18:29:15.47144Z","shell.execute_reply.started":"2022-06-24T18:29:05.699778Z","shell.execute_reply":"2022-06-24T18:29:15.470125Z"},"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-06-24T18:29:20.531571Z","iopub.execute_input":"2022-06-24T18:29:20.532519Z","iopub.status.idle":"2022-06-24T18:29:22.356383Z","shell.execute_reply.started":"2022-06-24T18:29:20.532488Z","shell.execute_reply":"2022-06-24T18:29:22.355458Z"},"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-06-24T18:29:32.674971Z","iopub.execute_input":"2022-06-24T18:29:32.675692Z","iopub.status.idle":"2022-06-24T18:29:32.848641Z","shell.execute_reply.started":"2022-06-24T18:29:32.675666Z","shell.execute_reply":"2022-06-24T18:29:32.847558Z"},"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-06-24T18:29:46.580621Z","iopub.execute_input":"2022-06-24T18:29:46.580957Z","iopub.status.idle":"2022-06-24T18:29:46.614216Z","shell.execute_reply.started":"2022-06-24T18:29:46.580928Z","shell.execute_reply":"2022-06-24T18:29:46.613298Z"},"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-06-24T18:30:13.790724Z","iopub.execute_input":"2022-06-24T18:30:13.791048Z","iopub.status.idle":"2022-06-24T18:30:13.798132Z","shell.execute_reply.started":"2022-06-24T18:30:13.79102Z","shell.execute_reply":"2022-06-24T18:30:13.79729Z"},"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-06-24T18:30:25.383972Z","iopub.execute_input":"2022-06-24T18:30:25.384715Z","iopub.status.idle":"2022-06-24T18:30:25.561042Z","shell.execute_reply.started":"2022-06-24T18:30:25.384687Z","shell.execute_reply":"2022-06-24T18:30:25.560351Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"kendall_tau(y_valid, y_pred)","metadata":{"execution":{"iopub.status.busy":"2022-06-24T18:30:33.116094Z","iopub.execute_input":"2022-06-24T18:30:33.116441Z","iopub.status.idle":"2022-06-24T18:30:33.231689Z","shell.execute_reply.started":"2022-06-24T18:30:33.116412Z","shell.execute_reply":"2022-06-24T18:30:33.230727Z"},"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-06-24T18:30:50.377398Z","iopub.execute_input":"2022-06-24T18:30:50.377705Z","iopub.status.idle":"2022-06-24T18:30:50.440037Z","shell.execute_reply.started":"2022-06-24T18:30:50.37768Z","shell.execute_reply":"2022-06-24T18:30:50.439023Z"},"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-06-24T18:31:05.382115Z","iopub.execute_input":"2022-06-24T18:31:05.382465Z","iopub.status.idle":"2022-06-24T18:31:05.399624Z","shell.execute_reply.started":"2022-06-24T18:31:05.382437Z","shell.execute_reply":"2022-06-24T18:31:05.398698Z"},"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-06-24T18:31:13.433619Z","iopub.execute_input":"2022-06-24T18:31:13.433978Z","iopub.status.idle":"2022-06-24T18:31:13.454401Z","shell.execute_reply.started":"2022-06-24T18:31:13.433948Z","shell.execute_reply":"2022-06-24T18:31:13.453635Z"},"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-06-24T18:31:29.122318Z","iopub.execute_input":"2022-06-24T18:31:29.122622Z","iopub.status.idle":"2022-06-24T18:31:29.13314Z","shell.execute_reply.started":"2022-06-24T18:31:29.122597Z","shell.execute_reply":"2022-06-24T18:31:29.132305Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ny_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-06-24T18:31:48.020208Z","iopub.execute_input":"2022-06-24T18:31:48.020506Z","iopub.status.idle":"2022-06-24T18:31:48.028821Z","shell.execute_reply.started":"2022-06-24T18:31:48.020483Z","shell.execute_reply":"2022-06-24T18:31:48.02766Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_submit.to_csv('submission.csv')","metadata":{"execution":{"iopub.status.busy":"2022-06-24T18:31:55.018597Z","iopub.execute_input":"2022-06-24T18:31:55.018945Z","iopub.status.idle":"2022-06-24T18:31:55.02625Z","shell.execute_reply.started":"2022-06-24T18:31:55.018916Z","shell.execute_reply":"2022-06-24T18:31:55.025434Z"},"trusted":true},"execution_count":null,"outputs":[]}]}