{"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-04-16T15:40:18.703245Z","iopub.execute_input":"2022-04-16T15:40:18.703622Z","iopub.status.idle":"2022-04-16T15:40:18.730374Z","shell.execute_reply.started":"2022-04-16T15:40:18.703524Z","shell.execute_reply":"2022-04-16T15:40:18.729632Z"},"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-04-16T15:43:57.626534Z","iopub.execute_input":"2022-04-16T15:43:57.627341Z","iopub.status.idle":"2022-04-16T15:43:57.638968Z","shell.execute_reply.started":"2022-04-16T15:43:57.627285Z","shell.execute_reply":"2022-04-16T15:43:57.638025Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd","metadata":{"execution":{"iopub.status.busy":"2022-04-16T15:43:58.795520Z","iopub.execute_input":"2022-04-16T15:43:58.795999Z","iopub.status.idle":"2022-04-16T15:43:58.799214Z","shell.execute_reply.started":"2022-04-16T15:43:58.795943Z","shell.execute_reply":"2022-04-16T15:43:58.798681Z"},"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-04-16T15:43:59.107716Z","iopub.execute_input":"2022-04-16T15:43:59.108344Z","iopub.status.idle":"2022-04-16T15:44:06.078986Z","shell.execute_reply.started":"2022-04-16T15:43:59.108264Z","shell.execute_reply":"2022-04-16T15:44:06.078171Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_week = transactions.week.max() + 1\ntransactions = transactions[transactions.week > transactions.week.max() - 10]","metadata":{"execution":{"iopub.status.busy":"2022-04-16T15:44:06.081004Z","iopub.execute_input":"2022-04-16T15:44:06.081314Z","iopub.status.idle":"2022-04-16T15:44:06.317468Z","shell.execute_reply.started":"2022-04-16T15:44:06.081272Z","shell.execute_reply":"2022-04-16T15:44:06.316598Z"},"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-04-16T15:44:14.483924Z","iopub.execute_input":"2022-04-16T15:44:14.484297Z","iopub.status.idle":"2022-04-16T15:44:32.713783Z","shell.execute_reply.started":"2022-04-16T15:44:14.484254Z","shell.execute_reply":"2022-04-16T15:44:32.712927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transactions.groupby('week')['t_dat'].agg(['min', 'max'])","metadata":{"execution":{"iopub.status.busy":"2022-04-16T15:52:20.359059Z","iopub.execute_input":"2022-04-16T15:52:20.359362Z","iopub.status.idle":"2022-04-16T15:52:20.430004Z","shell.execute_reply.started":"2022-04-16T15:52:20.359332Z","shell.execute_reply":"2022-04-16T15:52:20.428905Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"c2weeks","metadata":{"execution":{"iopub.status.busy":"2022-04-16T15:51:14.212650Z","iopub.execute_input":"2022-04-16T15:51:14.213638Z","iopub.status.idle":"2022-04-16T15:51:14.231518Z","shell.execute_reply.started":"2022-04-16T15:51:14.213593Z","shell.execute_reply":"2022-04-16T15:51:14.230546Z"},"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-04-16T15:52:37.190968Z","iopub.execute_input":"2022-04-16T15:52:37.191281Z","iopub.status.idle":"2022-04-16T15:52:38.270373Z","shell.execute_reply.started":"2022-04-16T15:52:37.191249Z","shell.execute_reply":"2022-04-16T15:52:38.269366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"c2weeks2shifted_weeks[28847241659200]","metadata":{"execution":{"iopub.status.busy":"2022-04-16T15:53:57.883004Z","iopub.execute_input":"2022-04-16T15:53:57.883327Z","iopub.status.idle":"2022-04-16T15:53:57.890002Z","shell.execute_reply.started":"2022-04-16T15:53:57.883291Z","shell.execute_reply":"2022-04-16T15:53:57.888855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"candidates_last_purchase = transactions.copy()","metadata":{"execution":{"iopub.status.busy":"2022-04-16T15:54:02.986364Z","iopub.execute_input":"2022-04-16T15:54:02.986659Z","iopub.status.idle":"2022-04-16T15:54:03.008647Z","shell.execute_reply.started":"2022-04-16T15:54:02.986626Z","shell.execute_reply":"2022-04-16T15:54:03.007375Z"},"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-04-16T15:54:09.502111Z","iopub.execute_input":"2022-04-16T15:54:09.502379Z","iopub.status.idle":"2022-04-16T15:54:17.173729Z","shell.execute_reply.started":"2022-04-16T15:54:09.502353Z","shell.execute_reply":"2022-04-16T15:54:17.172748Z"},"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-04-16T15:56:44.758863Z","iopub.execute_input":"2022-04-16T15:56:44.759734Z","iopub.status.idle":"2022-04-16T15:56:44.842348Z","shell.execute_reply.started":"2022-04-16T15:56:44.759688Z","shell.execute_reply":"2022-04-16T15:56:44.841432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transactions[transactions['customer_id']==272412481300040]","metadata":{"execution":{"iopub.status.busy":"2022-04-16T15:56:28.429248Z","iopub.execute_input":"2022-04-16T15:56:28.430209Z","iopub.status.idle":"2022-04-16T15:56:28.447782Z","shell.execute_reply.started":"2022-04-16T15:56:28.430158Z","shell.execute_reply":"2022-04-16T15:56:28.446947Z"},"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-04-16T15:57:17.650780Z","iopub.execute_input":"2022-04-16T15:57:17.651075Z","iopub.status.idle":"2022-04-16T15:57:17.917777Z","shell.execute_reply.started":"2022-04-16T15:57:17.651046Z","shell.execute_reply":"2022-04-16T15:57:17.916726Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mean_price","metadata":{"execution":{"iopub.status.busy":"2022-04-16T15:57:22.071051Z","iopub.execute_input":"2022-04-16T15:57:22.071336Z","iopub.status.idle":"2022-04-16T15:57:22.081278Z","shell.execute_reply.started":"2022-04-16T15:57:22.071307Z","shell.execute_reply":"2022-04-16T15:57:22.080255Z"},"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-04-16T16:02:22.824751Z","iopub.execute_input":"2022-04-16T16:02:22.825182Z","iopub.status.idle":"2022-04-16T16:02:23.799128Z","shell.execute_reply.started":"2022-04-16T16:02:22.825151Z","shell.execute_reply":"2022-04-16T16:02:23.798311Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sales","metadata":{"execution":{"iopub.status.busy":"2022-04-16T16:46:11.472531Z","iopub.execute_input":"2022-04-16T16:46:11.473050Z","iopub.status.idle":"2022-04-16T16:46:11.481960Z","shell.execute_reply.started":"2022-04-16T16:46:11.473006Z","shell.execute_reply":"2022-04-16T16:46:11.481241Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sales.loc[95]","metadata":{"execution":{"iopub.status.busy":"2022-04-16T16:46:02.076763Z","iopub.execute_input":"2022-04-16T16:46:02.077101Z","iopub.status.idle":"2022-04-16T16:46:02.086767Z","shell.execute_reply.started":"2022-04-16T16:46:02.077066Z","shell.execute_reply":"2022-04-16T16:46:02.086000Z"},"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-04-16T16:46:24.315491Z","iopub.execute_input":"2022-04-16T16:46:24.316099Z","iopub.status.idle":"2022-04-16T16:46:24.370425Z","shell.execute_reply.started":"2022-04-16T16:46:24.316060Z","shell.execute_reply":"2022-04-16T16:46:24.369607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"bestsellers_previous_week.pipe(lambda df: df[df['week']==96])","metadata":{"execution":{"iopub.status.busy":"2022-04-16T16:51:04.064135Z","iopub.execute_input":"2022-04-16T16:51:04.065012Z","iopub.status.idle":"2022-04-16T16:51:04.077812Z","shell.execute_reply.started":"2022-04-16T16:51:04.064965Z","shell.execute_reply":"2022-04-16T16:51:04.077199Z"},"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-04-16T16:51:34.885365Z","iopub.execute_input":"2022-04-16T16:51:34.886020Z","iopub.status.idle":"2022-04-16T16:51:35.522916Z","shell.execute_reply.started":"2022-04-16T16:51:34.885980Z","shell.execute_reply":"2022-04-16T16:51:35.521903Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"unique_transactions","metadata":{"execution":{"iopub.status.busy":"2022-04-16T16:51:41.276191Z","iopub.execute_input":"2022-04-16T16:51:41.276486Z","iopub.status.idle":"2022-04-16T16:51:41.290998Z","shell.execute_reply.started":"2022-04-16T16:51:41.276452Z","shell.execute_reply":"2022-04-16T16:51:41.290002Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transactions.drop_duplicates(['week', 'customer_id'])","metadata":{"execution":{"iopub.status.busy":"2022-04-16T16:53:57.806973Z","iopub.execute_input":"2022-04-16T16:53:57.807309Z","iopub.status.idle":"2022-04-16T16:53:58.097008Z","shell.execute_reply.started":"2022-04-16T16:53:57.807278Z","shell.execute_reply":"2022-04-16T16:53:58.095874Z"},"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-04-16T16:54:53.227772Z","iopub.execute_input":"2022-04-16T16:54:53.228505Z","iopub.status.idle":"2022-04-16T16:54:54.190001Z","shell.execute_reply.started":"2022-04-16T16:54:53.228453Z","shell.execute_reply":"2022-04-16T16:54:54.188749Z"},"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-04-16T16:55:38.063780Z","iopub.execute_input":"2022-04-16T16:55:38.064413Z","iopub.status.idle":"2022-04-16T16:55:38.168415Z","shell.execute_reply.started":"2022-04-16T16:55:38.064363Z","shell.execute_reply":"2022-04-16T16:55:38.167458Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_set_transactions","metadata":{"execution":{"iopub.status.busy":"2022-04-16T16:55:45.019630Z","iopub.execute_input":"2022-04-16T16:55:45.020084Z","iopub.status.idle":"2022-04-16T16:55:45.037194Z","shell.execute_reply.started":"2022-04-16T16:55:45.020041Z","shell.execute_reply":"2022-04-16T16:55:45.036123Z"},"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-04-16T16:55:58.921660Z","iopub.execute_input":"2022-04-16T16:55:58.921976Z","iopub.status.idle":"2022-04-16T16:55:59.465925Z","shell.execute_reply.started":"2022-04-16T16:55:58.921943Z","shell.execute_reply":"2022-04-16T16:55:59.465060Z"},"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-04-16T16:56:10.118260Z","iopub.execute_input":"2022-04-16T16:56:10.119061Z","iopub.status.idle":"2022-04-16T16:56:11.325461Z","shell.execute_reply.started":"2022-04-16T16:56:10.119017Z","shell.execute_reply":"2022-04-16T16:56:11.324762Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"candidates_bestsellers","metadata":{"execution":{"iopub.status.busy":"2022-04-16T16:56:19.254726Z","iopub.execute_input":"2022-04-16T16:56:19.255053Z","iopub.status.idle":"2022-04-16T16:56:19.271702Z","shell.execute_reply.started":"2022-04-16T16:56:19.255014Z","shell.execute_reply":"2022-04-16T16:56:19.270702Z"},"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-04-16T16:56:25.608950Z","iopub.execute_input":"2022-04-16T16:56:25.609882Z","iopub.status.idle":"2022-04-16T16:56:25.620461Z","shell.execute_reply.started":"2022-04-16T16:56:25.609833Z","shell.execute_reply":"2022-04-16T16:56:25.619506Z"},"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-04-16T16:56:31.824647Z","iopub.execute_input":"2022-04-16T16:56:31.824982Z","iopub.status.idle":"2022-04-16T16:56:32.437836Z","shell.execute_reply.started":"2022-04-16T16:56:31.824952Z","shell.execute_reply":"2022-04-16T16:56:32.436995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data","metadata":{"execution":{"iopub.status.busy":"2022-04-16T16:56:39.053412Z","iopub.execute_input":"2022-04-16T16:56:39.053729Z","iopub.status.idle":"2022-04-16T16:56:39.071738Z","shell.execute_reply.started":"2022-04-16T16:56:39.053698Z","shell.execute_reply":"2022-04-16T16:56:39.070857Z"},"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-04-16T16:56:54.897286Z","iopub.execute_input":"2022-04-16T16:56:54.897571Z","iopub.status.idle":"2022-04-16T16:57:02.803119Z","shell.execute_reply.started":"2022-04-16T16:56:54.897538Z","shell.execute_reply":"2022-04-16T16:57:02.802139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.purchased.mean()","metadata":{"execution":{"iopub.status.busy":"2022-04-16T16:57:02.805002Z","iopub.execute_input":"2022-04-16T16:57:02.805659Z","iopub.status.idle":"2022-04-16T16:57:02.868471Z","shell.execute_reply.started":"2022-04-16T16:57:02.805609Z","shell.execute_reply":"2022-04-16T16:57:02.867456Z"},"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-04-16T16:57:05.130621Z","iopub.execute_input":"2022-04-16T16:57:05.130915Z","iopub.status.idle":"2022-04-16T16:57:08.938612Z","shell.execute_reply.started":"2022-04-16T16:57:05.130885Z","shell.execute_reply":"2022-04-16T16:57:08.937710Z"},"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-04-16T16:57:08.940267Z","iopub.execute_input":"2022-04-16T16:57:08.940616Z","iopub.status.idle":"2022-04-16T16:57:11.304612Z","shell.execute_reply.started":"2022-04-16T16:57:08.940582Z","shell.execute_reply":"2022-04-16T16:57:11.303642Z"},"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-04-16T16:57:11.305896Z","iopub.execute_input":"2022-04-16T16:57:11.306171Z","iopub.status.idle":"2022-04-16T16:57:33.962326Z","shell.execute_reply.started":"2022-04-16T16:57:11.306138Z","shell.execute_reply":"2022-04-16T16:57:33.961223Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.sort_values(['week', 'customer_id'], inplace=True)\ndata.reset_index(drop=True, inplace=True)","metadata":{"execution":{"iopub.status.busy":"2022-04-16T16:57:33.964281Z","iopub.execute_input":"2022-04-16T16:57:33.964533Z","iopub.status.idle":"2022-04-16T16:57:40.058230Z","shell.execute_reply.started":"2022-04-16T16:57:33.964502Z","shell.execute_reply":"2022-04-16T16:57:40.057265Z"},"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-04-16T16:57:40.059395Z","iopub.execute_input":"2022-04-16T16:57:40.059659Z","iopub.status.idle":"2022-04-16T16:57:47.342576Z","shell.execute_reply.started":"2022-04-16T16:57:40.059627Z","shell.execute_reply":"2022-04-16T16:57:47.341790Z"},"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-04-16T16:57:47.343704Z","iopub.execute_input":"2022-04-16T16:57:47.344074Z","iopub.status.idle":"2022-04-16T16:57:48.278583Z","shell.execute_reply.started":"2022-04-16T16:57:47.344043Z","shell.execute_reply":"2022-04-16T16:57:48.277693Z"},"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-04-16T16:57:48.279843Z","iopub.execute_input":"2022-04-16T16:57:48.280088Z","iopub.status.idle":"2022-04-16T16:57:48.285125Z","shell.execute_reply.started":"2022-04-16T16:57:48.280057Z","shell.execute_reply":"2022-04-16T16:57:48.284292Z"},"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-04-16T16:57:48.286579Z","iopub.execute_input":"2022-04-16T16:57:48.287072Z","iopub.status.idle":"2022-04-16T16:57:49.009188Z","shell.execute_reply.started":"2022-04-16T16:57:48.287025Z","shell.execute_reply":"2022-04-16T16:57:49.008435Z"},"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-04-16T16:57:49.011890Z","iopub.execute_input":"2022-04-16T16:57:49.012576Z","iopub.status.idle":"2022-04-16T16:57:50.099966Z","shell.execute_reply.started":"2022-04-16T16:57:49.012515Z","shell.execute_reply":"2022-04-16T16:57:50.099090Z"},"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    verbose=10\n)","metadata":{"execution":{"iopub.status.busy":"2022-04-16T16:57:50.101082Z","iopub.execute_input":"2022-04-16T16:57:50.101312Z","iopub.status.idle":"2022-04-16T16:57:50.105859Z","shell.execute_reply.started":"2022-04-16T16:57:50.101285Z","shell.execute_reply":"2022-04-16T16:57:50.105251Z"},"trusted":true},"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-04-16T16:57:50.106963Z","iopub.execute_input":"2022-04-16T16:57:50.107518Z"},"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_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":{"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_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_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_count":null,"outputs":[]},{"cell_type":"code","source":"sub_name = 'basic_model_submission'\nsub.to_csv(f'{sub_name}.csv.gz', index=False)","metadata":{},"execution_count":null,"outputs":[]}]}