{"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":"Radek posted about this [here](https://www.kaggle.com/competitions/h-and-m-personalized-fashion-recommendations/discussion/309220), and linked to a GitHub repo with the code.\n\nI just transferred that code here to Kaggle notebooks, that's all.","metadata":{}},{"cell_type":"code","source":"import numpy as np\n\ndef apk(actual, predicted, k=10):\n    \"\"\"\n    Computes the average precision at k.\n\n    This function computes the average prescision at k between two lists of\n    items.\n\n    Parameters\n    ----------\n    actual : list\n             A list of elements that are to be predicted (order doesn't matter)\n    predicted : list\n                A list of predicted elements (order does matter)\n    k : int, optional\n        The maximum number of predicted elements\n\n    Returns\n    -------\n    score : double\n            The average precision at k over the input lists\n\n    \"\"\"\n    if len(predicted)>k:\n        predicted = predicted[:k]\n\n    score = 0.0\n    num_hits = 0.0\n\n    for i,p in enumerate(predicted):\n        if p in actual and p not in predicted[:i]:\n            num_hits += 1.0\n            score += num_hits / (i+1.0)\n\n    if not actual:\n        return 0.0\n\n    return score / min(len(actual), k)\n\ndef mapk(actual, predicted, k=10):\n    \"\"\"\n    Computes the mean average precision at k.\n\n    This function computes the mean average prescision at k between two lists\n    of lists of items.\n\n    Parameters\n    ----------\n    actual : list\n             A list of lists of elements that are to be predicted \n             (order doesn't matter in the lists)\n    predicted : list\n                A list of lists of predicted elements\n                (order matters in the lists)\n    k : int, optional\n        The maximum number of predicted elements\n\n    Returns\n    -------\n    score : double\n            The mean average precision at k over the input lists\n\n    \"\"\"\n    return np.mean([apk(a,p,k) for a,p in zip(actual, predicted)])","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:55:03.065071Z","iopub.execute_input":"2022-05-03T21:55:03.065471Z","iopub.status.idle":"2022-05-03T21:55:03.076144Z","shell.execute_reply.started":"2022-05-03T21:55:03.065436Z","shell.execute_reply":"2022-05-03T21:55:03.075432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.base import BaseEstimator, TransformerMixin\nimport numpy as np\n\n# https://www.kaggle.com/c/h-and-m-personalized-fashion-recommendations/discussion/308635\ndef customer_hex_id_to_int(series):\n    return series.str[-16:].apply(hex_id_to_int)\n\ndef hex_id_to_int(str):\n    return int(str[-16:], 16)\n\ndef article_id_str_to_int(series):\n    return series.astype('int32')\n\ndef article_id_int_to_str(series):\n    return '0' + series.astype('str')\n\nclass Categorize(BaseEstimator, TransformerMixin):\n    def __init__(self, min_examples=0):\n        self.min_examples = min_examples\n        self.categories = []\n        \n    def fit(self, X):\n        for i in range(X.shape[1]):\n            vc = X.iloc[:, i].value_counts()\n            self.categories.append(vc[vc > self.min_examples].index.tolist())\n        return self\n\n    def transform(self, X):\n        data = {X.columns[i]: pd.Categorical(X.iloc[:, i], categories=self.categories[i]).codes for i in range(X.shape[1])}\n        return pd.DataFrame(data=data)\n\n\ndef calculate_apk(list_of_preds, list_of_gts):\n    # for fast validation this can be changed to operate on dicts of {'cust_id_int': [art_id_int, ...]}\n    # using 'data/val_week_purchases_by_cust.pkl'\n    apks = []\n    for preds, gt in zip(list_of_preds, list_of_gts):\n        apks.append(apk(gt, preds, k=12))\n    return np.mean(apks)\n\ndef eval_sub(sub_csv, skip_cust_with_no_purchases=True):\n    sub=pd.read_csv(sub_csv)\n    validation_set=pd.read_parquet('data/validation_ground_truth.parquet')\n\n    apks = []\n\n    no_purchases_pattern = []\n    for pred, gt in zip(sub.prediction.str.split(), validation_set.prediction.str.split()):\n        if skip_cust_with_no_purchases and (gt == no_purchases_pattern): continue\n        apks.append(apk(gt, pred, k=12))\n    return np.mean(apks)","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:55:03.090761Z","iopub.execute_input":"2022-05-03T21:55:03.092301Z","iopub.status.idle":"2022-05-03T21:55:03.160891Z","shell.execute_reply.started":"2022-05-03T21:55:03.092185Z","shell.execute_reply":"2022-05-03T21:55:03.160168Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:55:03.16255Z","iopub.execute_input":"2022-05-03T21:55:03.163713Z","iopub.status.idle":"2022-05-03T21:55:03.181481Z","shell.execute_reply.started":"2022-05-03T21:55:03.163636Z","shell.execute_reply":"2022-05-03T21:55:03.180445Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\ntransactions = pd.read_parquet('../input/warmup/transactions_train.parquet')\ncustomers = pd.read_parquet('../input/warmup/customers.parquet')\narticles = pd.read_parquet('../input/warmup/articles.parquet')\n\n# sample = 0.05\n# transactions = pd.read_parquet(f'data/transactions_train_sample_{sample}.parquet')\n# customers = pd.read_parquet(f'data/customers_sample_{sample}.parquet')\n# articles = pd.read_parquet(f'data/articles_train_sample_{sample}.parquet')","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:55:03.183735Z","iopub.execute_input":"2022-05-03T21:55:03.184171Z","iopub.status.idle":"2022-05-03T21:55:07.380346Z","shell.execute_reply.started":"2022-05-03T21:55:03.184135Z","shell.execute_reply":"2022-05-03T21:55:07.378928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transactions['week'].max()","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:57:28.92322Z","iopub.execute_input":"2022-05-03T21:57:28.923569Z","iopub.status.idle":"2022-05-03T21:57:28.955502Z","shell.execute_reply.started":"2022-05-03T21:57:28.923533Z","shell.execute_reply":"2022-05-03T21:57:28.954879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_week = transactions.week.max() + 1\ntransactions = transactions[transactions.week > transactions.week.max() - 6]","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:18.640636Z","iopub.execute_input":"2022-05-03T21:49:18.640915Z","iopub.status.idle":"2022-05-03T21:49:18.742186Z","shell.execute_reply.started":"2022-05-03T21:49:18.640883Z","shell.execute_reply":"2022-05-03T21:49:18.741393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Generating candidates","metadata":{}},{"cell_type":"markdown","source":"### Last purchase candidates","metadata":{}},{"cell_type":"code","source":"%%time\n\nc2weeks = transactions.groupby('customer_id')['week'].unique()","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:18.743279Z","iopub.execute_input":"2022-05-03T21:49:18.743805Z","iopub.status.idle":"2022-05-03T21:49:25.399604Z","shell.execute_reply.started":"2022-05-03T21:49:18.743766Z","shell.execute_reply":"2022-05-03T21:49:25.39869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transactions.groupby('week')['t_dat'].agg(['min', 'max'])","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:25.402055Z","iopub.execute_input":"2022-05-03T21:49:25.40286Z","iopub.status.idle":"2022-05-03T21:49:25.428507Z","shell.execute_reply.started":"2022-05-03T21:49:25.402819Z","shell.execute_reply":"2022-05-03T21:49:25.427401Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nc2weeks2shifted_weeks = {}\n\nfor c_id, weeks in c2weeks.items():\n    c2weeks2shifted_weeks[c_id] = {}\n    for i in range(weeks.shape[0]-1):\n        c2weeks2shifted_weeks[c_id][weeks[i]] = weeks[i+1]\n    c2weeks2shifted_weeks[c_id][weeks[-1]] = test_week","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:25.429888Z","iopub.execute_input":"2022-05-03T21:49:25.430479Z","iopub.status.idle":"2022-05-03T21:49:25.715546Z","shell.execute_reply.started":"2022-05-03T21:49:25.430435Z","shell.execute_reply":"2022-05-03T21:49:25.714633Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# c2weeks2shifted_weeks[28847241659200]","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:25.716927Z","iopub.execute_input":"2022-05-03T21:49:25.71715Z","iopub.status.idle":"2022-05-03T21:49:25.72176Z","shell.execute_reply.started":"2022-05-03T21:49:25.717123Z","shell.execute_reply":"2022-05-03T21:49:25.720874Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"candidates_last_purchase = transactions.copy()","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:25.723163Z","iopub.execute_input":"2022-05-03T21:49:25.723406Z","iopub.status.idle":"2022-05-03T21:49:25.739264Z","shell.execute_reply.started":"2022-05-03T21:49:25.723379Z","shell.execute_reply":"2022-05-03T21:49:25.738302Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nweeks = []\nfor i, (c_id, week) in enumerate(zip(transactions['customer_id'], transactions['week'])):\n    weeks.append(c2weeks2shifted_weeks[c_id][week])\n    \ncandidates_last_purchase.week=weeks","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:25.740663Z","iopub.execute_input":"2022-05-03T21:49:25.74163Z","iopub.status.idle":"2022-05-03T21:49:27.937715Z","shell.execute_reply.started":"2022-05-03T21:49:25.741582Z","shell.execute_reply":"2022-05-03T21:49:27.936614Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# candidates_last_purchase[candidates_last_purchase['customer_id']==272412481300040]","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:27.941051Z","iopub.execute_input":"2022-05-03T21:49:27.941834Z","iopub.status.idle":"2022-05-03T21:49:27.947065Z","shell.execute_reply.started":"2022-05-03T21:49:27.941797Z","shell.execute_reply":"2022-05-03T21:49:27.945946Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# transactions[transactions['customer_id']==272412481300040]","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:27.950699Z","iopub.execute_input":"2022-05-03T21:49:27.95095Z","iopub.status.idle":"2022-05-03T21:49:27.962282Z","shell.execute_reply.started":"2022-05-03T21:49:27.950922Z","shell.execute_reply":"2022-05-03T21:49:27.961115Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Bestsellers candidates","metadata":{}},{"cell_type":"code","source":"mean_price = transactions \\\n    .groupby(['week', 'article_id'])['price'].mean()","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:27.964557Z","iopub.execute_input":"2022-05-03T21:49:27.964975Z","iopub.status.idle":"2022-05-03T21:49:28.025621Z","shell.execute_reply.started":"2022-05-03T21:49:27.964943Z","shell.execute_reply":"2022-05-03T21:49:28.024598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sales = transactions \\\n    .groupby('week')['article_id'].value_counts() \\\n    .groupby('week').rank(method='dense', ascending=False) \\\n    .groupby('week').head(12).rename('bestseller_rank').astype('int8')","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.027596Z","iopub.execute_input":"2022-05-03T21:49:28.027916Z","iopub.status.idle":"2022-05-03T21:49:28.152955Z","shell.execute_reply.started":"2022-05-03T21:49:28.027872Z","shell.execute_reply":"2022-05-03T21:49:28.152247Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# sales","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.154526Z","iopub.execute_input":"2022-05-03T21:49:28.155028Z","iopub.status.idle":"2022-05-03T21:49:28.159855Z","shell.execute_reply.started":"2022-05-03T21:49:28.154981Z","shell.execute_reply":"2022-05-03T21:49:28.15834Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# sales.loc[95]","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.161322Z","iopub.execute_input":"2022-05-03T21:49:28.161635Z","iopub.status.idle":"2022-05-03T21:49:28.173005Z","shell.execute_reply.started":"2022-05-03T21:49:28.161601Z","shell.execute_reply":"2022-05-03T21:49:28.172282Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"bestsellers_previous_week = pd.merge(sales, mean_price, on=['week', 'article_id']).reset_index()\nbestsellers_previous_week.week += 1","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.174228Z","iopub.execute_input":"2022-05-03T21:49:28.174604Z","iopub.status.idle":"2022-05-03T21:49:28.200659Z","shell.execute_reply.started":"2022-05-03T21:49:28.174572Z","shell.execute_reply":"2022-05-03T21:49:28.199598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"unique_transactions = transactions \\\n    .groupby(['week', 'customer_id']) \\\n    .head(1) \\\n    .drop(columns=['article_id', 'price']) \\\n    .copy()","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.202539Z","iopub.execute_input":"2022-05-03T21:49:28.202868Z","iopub.status.idle":"2022-05-03T21:49:28.322278Z","shell.execute_reply.started":"2022-05-03T21:49:28.202825Z","shell.execute_reply":"2022-05-03T21:49:28.32131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transactions.drop_duplicates(['week', 'customer_id'])","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.323798Z","iopub.execute_input":"2022-05-03T21:49:28.324145Z","iopub.status.idle":"2022-05-03T21:49:28.38792Z","shell.execute_reply.started":"2022-05-03T21:49:28.324099Z","shell.execute_reply":"2022-05-03T21:49:28.386796Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"candidates_bestsellers = pd.merge(\n    unique_transactions,\n    bestsellers_previous_week,\n    on='week',\n)","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.389672Z","iopub.execute_input":"2022-05-03T21:49:28.390423Z","iopub.status.idle":"2022-05-03T21:49:28.454754Z","shell.execute_reply.started":"2022-05-03T21:49:28.390368Z","shell.execute_reply":"2022-05-03T21:49:28.45367Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_set_transactions = unique_transactions.drop_duplicates('customer_id').reset_index(drop=True)\ntest_set_transactions.week = test_week","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.456655Z","iopub.execute_input":"2022-05-03T21:49:28.457117Z","iopub.status.idle":"2022-05-03T21:49:28.482083Z","shell.execute_reply.started":"2022-05-03T21:49:28.457068Z","shell.execute_reply":"2022-05-03T21:49:28.481291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"candidates_bestsellers_test_week = pd.merge(\n    test_set_transactions,\n    bestsellers_previous_week,\n    on='week'\n)","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.483608Z","iopub.execute_input":"2022-05-03T21:49:28.483914Z","iopub.status.idle":"2022-05-03T21:49:28.594094Z","shell.execute_reply.started":"2022-05-03T21:49:28.483873Z","shell.execute_reply":"2022-05-03T21:49:28.592987Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"candidates_bestsellers = pd.concat([candidates_bestsellers, candidates_bestsellers_test_week])\ncandidates_bestsellers.drop(columns='bestseller_rank', inplace=True)","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.595427Z","iopub.execute_input":"2022-05-03T21:49:28.595662Z","iopub.status.idle":"2022-05-03T21:49:28.738397Z","shell.execute_reply.started":"2022-05-03T21:49:28.595634Z","shell.execute_reply":"2022-05-03T21:49:28.737063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Combining transactions and candidates / negative examples","metadata":{}},{"cell_type":"code","source":"transactions['purchased'] = 1","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.73983Z","iopub.execute_input":"2022-05-03T21:49:28.74008Z","iopub.status.idle":"2022-05-03T21:49:28.746052Z","shell.execute_reply.started":"2022-05-03T21:49:28.740051Z","shell.execute_reply":"2022-05-03T21:49:28.744875Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.concat([transactions, candidates_last_purchase, candidates_bestsellers])\ndata.purchased.fillna(0, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.747706Z","iopub.execute_input":"2022-05-03T21:49:28.747943Z","iopub.status.idle":"2022-05-03T21:49:28.852033Z","shell.execute_reply.started":"2022-05-03T21:49:28.747916Z","shell.execute_reply":"2022-05-03T21:49:28.85086Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.drop_duplicates(['customer_id', 'article_id', 'week'], inplace=True)","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:28.853932Z","iopub.execute_input":"2022-05-03T21:49:28.854173Z","iopub.status.idle":"2022-05-03T21:49:29.895503Z","shell.execute_reply.started":"2022-05-03T21:49:28.854145Z","shell.execute_reply":"2022-05-03T21:49:29.894546Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Add bestseller information","metadata":{}},{"cell_type":"code","source":"data = pd.merge(\n    data,\n    bestsellers_previous_week[['week', 'article_id', 'bestseller_rank']],\n    on=['week', 'article_id'],\n    how='left'\n)","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:29.896952Z","iopub.execute_input":"2022-05-03T21:49:29.897833Z","iopub.status.idle":"2022-05-03T21:49:30.477056Z","shell.execute_reply.started":"2022-05-03T21:49:29.897786Z","shell.execute_reply":"2022-05-03T21:49:30.476298Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = data[data.week != data.week.min()]\ndata.bestseller_rank.fillna(999, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:30.480827Z","iopub.execute_input":"2022-05-03T21:49:30.481106Z","iopub.status.idle":"2022-05-03T21:49:30.72922Z","shell.execute_reply.started":"2022-05-03T21:49:30.481072Z","shell.execute_reply":"2022-05-03T21:49:30.728267Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data = pd.merge(data, articles, on='article_id', how='left')\ndata = pd.merge(data, customers, on='customer_id', how='left')","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:30.730644Z","iopub.execute_input":"2022-05-03T21:49:30.730981Z","iopub.status.idle":"2022-05-03T21:49:34.685182Z","shell.execute_reply.started":"2022-05-03T21:49:30.730926Z","shell.execute_reply":"2022-05-03T21:49:34.68393Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.sort_values(['week', 'customer_id'], ignore_index=True, inplace=True)\n# data.reset_index(drop=True, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:34.690627Z","iopub.execute_input":"2022-05-03T21:49:34.690936Z","iopub.status.idle":"2022-05-03T21:49:35.522693Z","shell.execute_reply.started":"2022-05-03T21:49:34.690901Z","shell.execute_reply":"2022-05-03T21:49:35.521575Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = data[data.week != test_week]\ntest = data[data.week==test_week].drop_duplicates(['customer_id', 'article_id', 'sales_channel_id']).copy()","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:35.524356Z","iopub.execute_input":"2022-05-03T21:49:35.524742Z","iopub.status.idle":"2022-05-03T21:49:36.797873Z","shell.execute_reply.started":"2022-05-03T21:49:35.524702Z","shell.execute_reply":"2022-05-03T21:49:36.796732Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_baskets = train.groupby(['week', 'customer_id'])['article_id'].count().values","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:36.799691Z","iopub.execute_input":"2022-05-03T21:49:36.800909Z","iopub.status.idle":"2022-05-03T21:49:36.880841Z","shell.execute_reply.started":"2022-05-03T21:49:36.800857Z","shell.execute_reply":"2022-05-03T21:49:36.879689Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_baskets","metadata":{"execution":{"iopub.status.busy":"2022-05-03T22:01:38.72584Z","iopub.execute_input":"2022-05-03T22:01:38.726638Z","iopub.status.idle":"2022-05-03T22:01:38.733229Z","shell.execute_reply.started":"2022-05-03T22:01:38.726595Z","shell.execute_reply":"2022-05-03T22:01:38.732049Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"columns_to_use = ['article_id', 'product_type_no', 'graphical_appearance_no', 'colour_group_code', 'perceived_colour_value_id',\n'perceived_colour_master_id', 'department_no', 'index_code',\n'index_group_no', 'section_no', 'garment_group_no', 'FN', 'Active',\n'club_member_status', 'fashion_news_frequency', 'age', 'postal_code', 'bestseller_rank']","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:36.969282Z","iopub.execute_input":"2022-05-03T21:49:36.969515Z","iopub.status.idle":"2022-05-03T21:49:36.975486Z","shell.execute_reply.started":"2022-05-03T21:49:36.969486Z","shell.execute_reply":"2022-05-03T21:49:36.974648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\ntrain_X = train[columns_to_use]\ntrain_y = train['purchased']\n\ntest_X = test[columns_to_use]","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:36.976831Z","iopub.execute_input":"2022-05-03T21:49:36.97751Z","iopub.status.idle":"2022-05-03T21:49:37.0779Z","shell.execute_reply.started":"2022-05-03T21:49:36.977472Z","shell.execute_reply":"2022-05-03T21:49:37.077016Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model training","metadata":{}},{"cell_type":"code","source":"from lightgbm.sklearn import LGBMRanker","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:37.079172Z","iopub.execute_input":"2022-05-03T21:49:37.079436Z","iopub.status.idle":"2022-05-03T21:49:37.083695Z","shell.execute_reply.started":"2022-05-03T21:49:37.079405Z","shell.execute_reply":"2022-05-03T21:49:37.082861Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ranker = LGBMRanker(\n    objective=\"lambdarank\",\n    metric=\"ndcg\",\n    boosting_type=\"dart\",\n    n_estimators=1,\n    importance_type='gain',\n    learning_rate=0.03,\n    verbose=10\n)","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:37.084822Z","iopub.execute_input":"2022-05-03T21:49:37.085031Z","iopub.status.idle":"2022-05-03T21:49:37.097671Z","shell.execute_reply.started":"2022-05-03T21:49:37.085004Z","shell.execute_reply":"2022-05-03T21:49:37.096415Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nranker = ranker.fit(\n    train_X,\n    train_y,\n    group=train_baskets,\n)","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:37.099464Z","iopub.execute_input":"2022-05-03T21:49:37.100441Z","iopub.status.idle":"2022-05-03T21:49:38.273183Z","shell.execute_reply.started":"2022-05-03T21:49:37.100404Z","shell.execute_reply":"2022-05-03T21:49:38.272369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for i in ranker.feature_importances_.argsort()[::-1]:\n    print(columns_to_use[i], ranker.feature_importances_[i]/ranker.feature_importances_.sum())","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:38.277829Z","iopub.execute_input":"2022-05-03T21:49:38.279804Z","iopub.status.idle":"2022-05-03T21:49:38.295503Z","shell.execute_reply.started":"2022-05-03T21:49:38.279742Z","shell.execute_reply":"2022-05-03T21:49:38.294733Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Calculate predictions","metadata":{}},{"cell_type":"code","source":"%time\n\ntest['preds'] = ranker.predict(test_X)\n\nc_id2predicted_article_ids = test \\\n    .sort_values(['customer_id', 'preds'], ascending=False) \\\n    .groupby('customer_id')['article_id'].apply(list).to_dict()\n\nbestsellers_last_week = \\\n    bestsellers_previous_week[bestsellers_previous_week.week == bestsellers_previous_week.week.max()]['article_id'].tolist()","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:38.297079Z","iopub.execute_input":"2022-05-03T21:49:38.297361Z","iopub.status.idle":"2022-05-03T21:49:42.891804Z","shell.execute_reply.started":"2022-05-03T21:49:38.297327Z","shell.execute_reply":"2022-05-03T21:49:42.890652Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Create submission","metadata":{}},{"cell_type":"code","source":"sub = pd.read_csv('/kaggle/input/h-and-m-personalized-fashion-recommendations/sample_submission.csv')","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:42.893391Z","iopub.execute_input":"2022-05-03T21:49:42.893945Z","iopub.status.idle":"2022-05-03T21:49:48.609426Z","shell.execute_reply.started":"2022-05-03T21:49:42.893896Z","shell.execute_reply":"2022-05-03T21:49:48.608176Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\npreds = []\nfor c_id in customer_hex_id_to_int(sub.customer_id):\n    pred = c_id2predicted_article_ids.get(c_id, [])\n    pred = pred + bestsellers_last_week\n    preds.append(pred[:12])","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:48.610971Z","iopub.execute_input":"2022-05-03T21:49:48.611265Z","iopub.status.idle":"2022-05-03T21:49:54.821014Z","shell.execute_reply.started":"2022-05-03T21:49:48.611227Z","shell.execute_reply":"2022-05-03T21:49:54.819961Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds = [' '.join(['0' + str(p) for p in ps]) for ps in preds]\nsub.prediction = preds","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:49:54.822437Z","iopub.execute_input":"2022-05-03T21:49:54.822689Z","iopub.status.idle":"2022-05-03T21:50:01.137949Z","shell.execute_reply.started":"2022-05-03T21:49:54.822658Z","shell.execute_reply":"2022-05-03T21:50:01.136748Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_name = 'submission'\nsub.to_csv(f'{sub_name}.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2022-05-03T21:50:01.139803Z","iopub.execute_input":"2022-05-03T21:50:01.140126Z","iopub.status.idle":"2022-05-03T21:50:13.951264Z","shell.execute_reply.started":"2022-05-03T21:50:01.140084Z","shell.execute_reply":"2022-05-03T21:50:13.950098Z"},"trusted":true},"execution_count":null,"outputs":[]}]}