{"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-23T07:09:42.05724Z","iopub.execute_input":"2022-07-23T07:09:42.058086Z","iopub.status.idle":"2022-07-23T07:09:42.064581Z","shell.execute_reply.started":"2022-07-23T07:09:42.058048Z","shell.execute_reply":"2022-07-23T07:09:42.062798Z"},"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-07-23T07:09:42.08927Z","iopub.execute_input":"2022-07-23T07:09:42.089675Z","iopub.status.idle":"2022-07-23T07:10:50.11496Z","shell.execute_reply.started":"2022-07-23T07:09:42.089642Z","shell.execute_reply":"2022-07-23T07:10:50.113781Z"},"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-07-23T07:10:50.117338Z","iopub.execute_input":"2022-07-23T07:10:50.117731Z","iopub.status.idle":"2022-07-23T07:10:50.143208Z","shell.execute_reply.started":"2022-07-23T07:10:50.1177Z","shell.execute_reply":"2022-07-23T07:10:50.142089Z"},"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-23T07:10:50.144722Z","iopub.execute_input":"2022-07-23T07:10:50.145151Z","iopub.status.idle":"2022-07-23T07:10:52.006436Z","shell.execute_reply.started":"2022-07-23T07:10:50.145114Z","shell.execute_reply":"2022-07-23T07:10:52.005328Z"},"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-23T07:10:52.009146Z","iopub.execute_input":"2022-07-23T07:10:52.00948Z","iopub.status.idle":"2022-07-23T07:10:52.033699Z","shell.execute_reply.started":"2022-07-23T07:10:52.00945Z","shell.execute_reply":"2022-07-23T07:10:52.032621Z"},"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-23T07:10:52.035478Z","iopub.execute_input":"2022-07-23T07:10:52.03579Z","iopub.status.idle":"2022-07-23T07:10:52.050678Z","shell.execute_reply.started":"2022-07-23T07:10:52.035762Z","shell.execute_reply":"2022-07-23T07:10:52.049537Z"},"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-23T07:10:52.052453Z","iopub.execute_input":"2022-07-23T07:10:52.052806Z","iopub.status.idle":"2022-07-23T07:10:52.066883Z","shell.execute_reply.started":"2022-07-23T07:10:52.052774Z","shell.execute_reply":"2022-07-23T07:10:52.065585Z"},"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-23T07:10:52.068543Z","iopub.execute_input":"2022-07-23T07:10:52.069124Z","iopub.status.idle":"2022-07-23T07:10:56.029423Z","shell.execute_reply.started":"2022-07-23T07:10:52.069083Z","shell.execute_reply":"2022-07-23T07:10:56.028298Z"},"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-23T07:10:56.030933Z","iopub.execute_input":"2022-07-23T07:10:56.031401Z","iopub.status.idle":"2022-07-23T07:10:56.25175Z","shell.execute_reply.started":"2022-07-23T07:10:56.031335Z","shell.execute_reply":"2022-07-23T07:10:56.250716Z"},"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-23T07:10:56.253353Z","iopub.execute_input":"2022-07-23T07:10:56.253712Z","iopub.status.idle":"2022-07-23T07:10:56.83242Z","shell.execute_reply.started":"2022-07-23T07:10:56.25368Z","shell.execute_reply":"2022-07-23T07:10:56.830467Z"},"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-23T07:10:56.83859Z","iopub.execute_input":"2022-07-23T07:10:56.83896Z","iopub.status.idle":"2022-07-23T07:11:15.559214Z","shell.execute_reply.started":"2022-07-23T07:10:56.838921Z","shell.execute_reply":"2022-07-23T07:11:15.558066Z"},"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-23T07:11:15.560513Z","iopub.execute_input":"2022-07-23T07:11:15.560843Z","iopub.status.idle":"2022-07-23T07:11:15.883011Z","shell.execute_reply.started":"2022-07-23T07:11:15.560813Z","shell.execute_reply":"2022-07-23T07:11:15.88176Z"},"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-23T07:11:15.884972Z","iopub.execute_input":"2022-07-23T07:11:15.885847Z","iopub.status.idle":"2022-07-23T07:11:30.336803Z","shell.execute_reply.started":"2022-07-23T07:11:15.885801Z","shell.execute_reply":"2022-07-23T07:11:30.335861Z"},"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-23T07:11:30.338107Z","iopub.execute_input":"2022-07-23T07:11:30.338706Z","iopub.status.idle":"2022-07-23T07:11:32.205939Z","shell.execute_reply.started":"2022-07-23T07:11:30.338673Z","shell.execute_reply":"2022-07-23T07:11:32.20482Z"},"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-23T07:11:32.207435Z","iopub.execute_input":"2022-07-23T07:11:32.208056Z","iopub.status.idle":"2022-07-23T07:11:32.402547Z","shell.execute_reply.started":"2022-07-23T07:11:32.208017Z","shell.execute_reply":"2022-07-23T07:11:32.401268Z"},"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-23T07:11:32.404238Z","iopub.execute_input":"2022-07-23T07:11:32.405107Z","iopub.status.idle":"2022-07-23T07:11:32.443223Z","shell.execute_reply.started":"2022-07-23T07:11:32.405055Z","shell.execute_reply":"2022-07-23T07:11:32.442445Z"},"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-23T07:11:32.444843Z","iopub.execute_input":"2022-07-23T07:11:32.445157Z","iopub.status.idle":"2022-07-23T07:11:32.455617Z","shell.execute_reply.started":"2022-07-23T07:11:32.445129Z","shell.execute_reply":"2022-07-23T07:11:32.454247Z"},"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-23T07:11:32.45758Z","iopub.execute_input":"2022-07-23T07:11:32.458349Z","iopub.status.idle":"2022-07-23T07:11:32.612538Z","shell.execute_reply.started":"2022-07-23T07:11:32.458298Z","shell.execute_reply":"2022-07-23T07:11:32.611425Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"kendall_tau(y_valid, y_pred)","metadata":{"execution":{"iopub.status.busy":"2022-07-23T07:11:32.614035Z","iopub.execute_input":"2022-07-23T07:11:32.614824Z","iopub.status.idle":"2022-07-23T07:11:32.7155Z","shell.execute_reply.started":"2022-07-23T07:11:32.614776Z","shell.execute_reply":"2022-07-23T07:11:32.714335Z"},"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-23T07:11:32.717147Z","iopub.execute_input":"2022-07-23T07:11:32.717495Z","iopub.status.idle":"2022-07-23T07:11:32.776275Z","shell.execute_reply.started":"2022-07-23T07:11:32.717466Z","shell.execute_reply":"2022-07-23T07:11:32.775498Z"},"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-23T07:11:32.777531Z","iopub.execute_input":"2022-07-23T07:11:32.777822Z","iopub.status.idle":"2022-07-23T07:11:32.797828Z","shell.execute_reply.started":"2022-07-23T07:11:32.777795Z","shell.execute_reply":"2022-07-23T07:11:32.796794Z"},"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-23T07:11:32.799109Z","iopub.execute_input":"2022-07-23T07:11:32.799957Z","iopub.status.idle":"2022-07-23T07:11:32.825281Z","shell.execute_reply.started":"2022-07-23T07:11:32.799902Z","shell.execute_reply":"2022-07-23T07:11:32.824154Z"},"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-23T07:11:32.826979Z","iopub.execute_input":"2022-07-23T07:11:32.829273Z","iopub.status.idle":"2022-07-23T07:11:32.846545Z","shell.execute_reply.started":"2022-07-23T07:11:32.829216Z","shell.execute_reply":"2022-07-23T07:11:32.845672Z"},"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-23T07:11:32.847633Z","iopub.execute_input":"2022-07-23T07:11:32.848348Z","iopub.status.idle":"2022-07-23T07:11:32.85708Z","shell.execute_reply.started":"2022-07-23T07:11:32.848314Z","shell.execute_reply":"2022-07-23T07:11:32.85608Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_submit.to_csv('submission.csv')","metadata":{"execution":{"iopub.status.busy":"2022-07-23T07:11:32.858422Z","iopub.execute_input":"2022-07-23T07:11:32.859085Z","iopub.status.idle":"2022-07-23T07:11:32.86949Z","shell.execute_reply.started":"2022-07-23T07:11:32.859047Z","shell.execute_reply":"2022-07-23T07:11:32.868432Z"},"trusted":true},"execution_count":null,"outputs":[]}]}