{"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 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":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-04-23T05:55:23.119948Z","iopub.execute_input":"2022-04-23T05:55:23.120243Z","iopub.status.idle":"2022-04-23T05:55:23.128516Z","shell.execute_reply.started":"2022-04-23T05:55:23.120214Z","shell.execute_reply":"2022-04-23T05:55:23.127467Z"},"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-23T05:55:23.164645Z","iopub.execute_input":"2022-04-23T05:55:23.165511Z","iopub.status.idle":"2022-04-23T05:55:23.177204Z","shell.execute_reply.started":"2022-04-23T05:55:23.165460Z","shell.execute_reply":"2022-04-23T05:55:23.176309Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:55:23.178689Z","iopub.execute_input":"2022-04-23T05:55:23.178904Z","iopub.status.idle":"2022-04-23T05:55:23.193993Z","shell.execute_reply.started":"2022-04-23T05:55:23.178879Z","shell.execute_reply":"2022-04-23T05:55:23.193183Z"},"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-23T05:55:23.202619Z","iopub.execute_input":"2022-04-23T05:55:23.203081Z","iopub.status.idle":"2022-04-23T05:55:36.082463Z","shell.execute_reply.started":"2022-04-23T05:55:23.203022Z","shell.execute_reply":"2022-04-23T05:55:36.079650Z"},"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-23T05:55:36.085509Z","iopub.execute_input":"2022-04-23T05:55:36.085765Z","iopub.status.idle":"2022-04-23T05:55:36.917765Z","shell.execute_reply.started":"2022-04-23T05:55:36.085733Z","shell.execute_reply":"2022-04-23T05:55:36.913695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"%%time\n\nc2weeks = transactions.groupby('customer_id')['week'].unique()","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:55:36.922992Z","iopub.execute_input":"2022-04-23T05:55:36.924454Z","iopub.status.idle":"2022-04-23T05:55:59.273157Z","shell.execute_reply.started":"2022-04-23T05:55:36.924156Z","shell.execute_reply":"2022-04-23T05:55:59.272021Z"},"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-23T05:55:59.276635Z","iopub.execute_input":"2022-04-23T05:55:59.277579Z","iopub.status.idle":"2022-04-23T05:55:59.360173Z","shell.execute_reply.started":"2022-04-23T05:55:59.277516Z","shell.execute_reply":"2022-04-23T05:55:59.359392Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"c2weeks","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:55:59.361324Z","iopub.execute_input":"2022-04-23T05:55:59.361641Z","iopub.status.idle":"2022-04-23T05:55:59.372242Z","shell.execute_reply.started":"2022-04-23T05:55:59.361611Z","shell.execute_reply":"2022-04-23T05:55:59.371288Z"},"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-23T05:55:59.373633Z","iopub.execute_input":"2022-04-23T05:55:59.373904Z","iopub.status.idle":"2022-04-23T05:56:00.403256Z","shell.execute_reply.started":"2022-04-23T05:55:59.373873Z","shell.execute_reply":"2022-04-23T05:56:00.402266Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"c2weeks2shifted_weeks[28847241659200]","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:00.404620Z","iopub.execute_input":"2022-04-23T05:56:00.404852Z","iopub.status.idle":"2022-04-23T05:56:00.409484Z","shell.execute_reply.started":"2022-04-23T05:56:00.404818Z","shell.execute_reply":"2022-04-23T05:56:00.408971Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"candidates_last_purchase = transactions.copy()","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:00.410367Z","iopub.execute_input":"2022-04-23T05:56:00.411042Z","iopub.status.idle":"2022-04-23T05:56:00.438361Z","shell.execute_reply.started":"2022-04-23T05:56:00.411004Z","shell.execute_reply":"2022-04-23T05:56:00.437603Z"},"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-23T05:56:00.439612Z","iopub.execute_input":"2022-04-23T05:56:00.440014Z","iopub.status.idle":"2022-04-23T05:56:08.113876Z","shell.execute_reply.started":"2022-04-23T05:56:00.439976Z","shell.execute_reply":"2022-04-23T05:56:08.112739Z"},"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-23T05:56:08.117240Z","iopub.execute_input":"2022-04-23T05:56:08.117479Z","iopub.status.idle":"2022-04-23T05:56:08.136744Z","shell.execute_reply.started":"2022-04-23T05:56:08.117451Z","shell.execute_reply":"2022-04-23T05:56:08.135753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transactions[transactions['customer_id']==272412481300040]","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:08.138341Z","iopub.execute_input":"2022-04-23T05:56:08.138639Z","iopub.status.idle":"2022-04-23T05:56:08.215340Z","shell.execute_reply.started":"2022-04-23T05:56:08.138599Z","shell.execute_reply":"2022-04-23T05:56:08.214385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mean_price = transactions \\\n    .groupby(['week', 'article_id'])['price'].mean()","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:08.216863Z","iopub.execute_input":"2022-04-23T05:56:08.217177Z","iopub.status.idle":"2022-04-23T05:56:08.500336Z","shell.execute_reply.started":"2022-04-23T05:56:08.217136Z","shell.execute_reply":"2022-04-23T05:56:08.499514Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"mean_price","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:08.501636Z","iopub.execute_input":"2022-04-23T05:56:08.502016Z","iopub.status.idle":"2022-04-23T05:56:08.513436Z","shell.execute_reply.started":"2022-04-23T05:56:08.501957Z","shell.execute_reply":"2022-04-23T05:56:08.512559Z"},"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-23T05:56:08.514673Z","iopub.execute_input":"2022-04-23T05:56:08.514971Z","iopub.status.idle":"2022-04-23T05:56:09.504038Z","shell.execute_reply.started":"2022-04-23T05:56:08.514942Z","shell.execute_reply":"2022-04-23T05:56:09.503169Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sales","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:09.505187Z","iopub.execute_input":"2022-04-23T05:56:09.505419Z","iopub.status.idle":"2022-04-23T05:56:09.514600Z","shell.execute_reply.started":"2022-04-23T05:56:09.505391Z","shell.execute_reply":"2022-04-23T05:56:09.513753Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sales.loc[95]","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:09.515933Z","iopub.execute_input":"2022-04-23T05:56:09.516183Z","iopub.status.idle":"2022-04-23T05:56:09.533947Z","shell.execute_reply.started":"2022-04-23T05:56:09.516151Z","shell.execute_reply":"2022-04-23T05:56:09.533034Z"},"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-23T05:56:09.535426Z","iopub.execute_input":"2022-04-23T05:56:09.536105Z","iopub.status.idle":"2022-04-23T05:56:09.582844Z","shell.execute_reply.started":"2022-04-23T05:56:09.536062Z","shell.execute_reply":"2022-04-23T05:56:09.582172Z"},"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-23T05:56:09.584301Z","iopub.execute_input":"2022-04-23T05:56:09.584744Z","iopub.status.idle":"2022-04-23T05:56:09.597610Z","shell.execute_reply.started":"2022-04-23T05:56:09.584700Z","shell.execute_reply":"2022-04-23T05:56:09.596833Z"},"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-23T05:56:09.598957Z","iopub.execute_input":"2022-04-23T05:56:09.599858Z","iopub.status.idle":"2022-04-23T05:56:10.282726Z","shell.execute_reply.started":"2022-04-23T05:56:09.599784Z","shell.execute_reply":"2022-04-23T05:56:10.281849Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"unique_transactions","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:10.284164Z","iopub.execute_input":"2022-04-23T05:56:10.284489Z","iopub.status.idle":"2022-04-23T05:56:10.297028Z","shell.execute_reply.started":"2022-04-23T05:56:10.284461Z","shell.execute_reply":"2022-04-23T05:56:10.296013Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transactions.drop_duplicates(['week', 'customer_id'])","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:10.298262Z","iopub.execute_input":"2022-04-23T05:56:10.298478Z","iopub.status.idle":"2022-04-23T05:56:10.583348Z","shell.execute_reply.started":"2022-04-23T05:56:10.298452Z","shell.execute_reply":"2022-04-23T05:56:10.582798Z"},"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-23T05:56:10.584149Z","iopub.execute_input":"2022-04-23T05:56:10.584791Z","iopub.status.idle":"2022-04-23T05:56:11.496168Z","shell.execute_reply.started":"2022-04-23T05:56:10.584758Z","shell.execute_reply":"2022-04-23T05:56:11.495170Z"},"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-23T05:56:11.497263Z","iopub.execute_input":"2022-04-23T05:56:11.497475Z","iopub.status.idle":"2022-04-23T05:56:11.603429Z","shell.execute_reply.started":"2022-04-23T05:56:11.497448Z","shell.execute_reply":"2022-04-23T05:56:11.602537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_set_transactions","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:11.604380Z","iopub.execute_input":"2022-04-23T05:56:11.604576Z","iopub.status.idle":"2022-04-23T05:56:11.619924Z","shell.execute_reply.started":"2022-04-23T05:56:11.604552Z","shell.execute_reply":"2022-04-23T05:56:11.619214Z"},"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-23T05:56:11.621151Z","iopub.execute_input":"2022-04-23T05:56:11.621678Z","iopub.status.idle":"2022-04-23T05:56:12.176713Z","shell.execute_reply.started":"2022-04-23T05:56:11.621637Z","shell.execute_reply":"2022-04-23T05:56:12.175991Z"},"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-23T05:56:12.177717Z","iopub.execute_input":"2022-04-23T05:56:12.178265Z","iopub.status.idle":"2022-04-23T05:56:13.698150Z","shell.execute_reply.started":"2022-04-23T05:56:12.178226Z","shell.execute_reply":"2022-04-23T05:56:13.697147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"candidates_bestsellers","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:13.699560Z","iopub.execute_input":"2022-04-23T05:56:13.699793Z","iopub.status.idle":"2022-04-23T05:56:13.714860Z","shell.execute_reply.started":"2022-04-23T05:56:13.699765Z","shell.execute_reply":"2022-04-23T05:56:13.713994Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"transactions['purchased'] = 1","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:13.718711Z","iopub.execute_input":"2022-04-23T05:56:13.719076Z","iopub.status.idle":"2022-04-23T05:56:13.736133Z","shell.execute_reply.started":"2022-04-23T05:56:13.719036Z","shell.execute_reply":"2022-04-23T05:56:13.735130Z"},"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-23T05:56:13.739103Z","iopub.execute_input":"2022-04-23T05:56:13.739405Z","iopub.status.idle":"2022-04-23T05:56:14.922723Z","shell.execute_reply.started":"2022-04-23T05:56:13.739368Z","shell.execute_reply":"2022-04-23T05:56:14.922152Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:14.923874Z","iopub.execute_input":"2022-04-23T05:56:14.924305Z","iopub.status.idle":"2022-04-23T05:56:14.942201Z","shell.execute_reply.started":"2022-04-23T05:56:14.924256Z","shell.execute_reply":"2022-04-23T05:56:14.941526Z"},"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-23T05:56:14.943606Z","iopub.execute_input":"2022-04-23T05:56:14.944206Z","iopub.status.idle":"2022-04-23T05:56:23.159523Z","shell.execute_reply.started":"2022-04-23T05:56:14.944160Z","shell.execute_reply":"2022-04-23T05:56:23.158476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"data.purchased.mean()","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:56:23.160879Z","iopub.execute_input":"2022-04-23T05:56:23.161430Z","iopub.status.idle":"2022-04-23T05:56:23.222663Z","shell.execute_reply.started":"2022-04-23T05:56:23.161383Z","shell.execute_reply":"2022-04-23T05:56:23.221790Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-23T05:56:23.223801Z","iopub.execute_input":"2022-04-23T05:56:23.224054Z","iopub.status.idle":"2022-04-23T05:56:27.512953Z","shell.execute_reply.started":"2022-04-23T05:56:23.224024Z","shell.execute_reply":"2022-04-23T05:56:27.512011Z"},"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-23T05:56:27.514235Z","iopub.execute_input":"2022-04-23T05:56:27.514535Z","iopub.status.idle":"2022-04-23T05:56:30.039353Z","shell.execute_reply.started":"2022-04-23T05:56:27.514496Z","shell.execute_reply":"2022-04-23T05:56:30.038363Z"},"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-23T05:56:30.041662Z","iopub.execute_input":"2022-04-23T05:56:30.042030Z","iopub.status.idle":"2022-04-23T05:56:54.691931Z","shell.execute_reply.started":"2022-04-23T05:56:30.041981Z","shell.execute_reply":"2022-04-23T05:56:54.691151Z"},"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-23T05:56:54.693026Z","iopub.execute_input":"2022-04-23T05:56:54.693368Z","iopub.status.idle":"2022-04-23T05:57:01.546546Z","shell.execute_reply.started":"2022-04-23T05:56:54.693328Z","shell.execute_reply":"2022-04-23T05:57:01.545716Z"},"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-23T05:57:01.547916Z","iopub.execute_input":"2022-04-23T05:57:01.548149Z","iopub.status.idle":"2022-04-23T05:57:09.557004Z","shell.execute_reply.started":"2022-04-23T05:57:01.548119Z","shell.execute_reply":"2022-04-23T05:57:09.556137Z"},"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-23T05:57:09.558435Z","iopub.execute_input":"2022-04-23T05:57:09.558720Z","iopub.status.idle":"2022-04-23T05:57:10.644383Z","shell.execute_reply.started":"2022-04-23T05:57:09.558683Z","shell.execute_reply":"2022-04-23T05:57:10.643559Z"},"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-23T05:57:10.645382Z","iopub.execute_input":"2022-04-23T05:57:10.645733Z","iopub.status.idle":"2022-04-23T05:57:10.649562Z","shell.execute_reply.started":"2022-04-23T05:57:10.645702Z","shell.execute_reply":"2022-04-23T05:57:10.649061Z"},"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-23T05:57:10.650615Z","iopub.execute_input":"2022-04-23T05:57:10.650843Z","iopub.status.idle":"2022-04-23T05:57:11.337538Z","shell.execute_reply.started":"2022-04-23T05:57:10.650799Z","shell.execute_reply":"2022-04-23T05:57:11.336675Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from lightgbm.sklearn import LGBMRanker","metadata":{"execution":{"iopub.status.busy":"2022-04-23T05:57:11.338975Z","iopub.execute_input":"2022-04-23T05:57:11.339319Z","iopub.status.idle":"2022-04-23T05:57:12.284636Z","shell.execute_reply.started":"2022-04-23T05:57:11.339288Z","shell.execute_reply":"2022-04-23T05:57:12.284023Z"},"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-23T05:57:12.285669Z","iopub.execute_input":"2022-04-23T05:57:12.285922Z","iopub.status.idle":"2022-04-23T05:57:12.290012Z","shell.execute_reply.started":"2022-04-23T05:57:12.285892Z","shell.execute_reply":"2022-04-23T05:57:12.289322Z"},"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-23T05:57:12.291185Z","iopub.execute_input":"2022-04-23T05:57:12.291699Z","iopub.status.idle":"2022-04-23T05:57:24.310713Z","shell.execute_reply.started":"2022-04-23T05:57:12.291658Z","shell.execute_reply":"2022-04-23T05:57:24.309864Z"},"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-04-23T05:57:24.311887Z","iopub.execute_input":"2022-04-23T05:57:24.312119Z","iopub.status.idle":"2022-04-23T05:57:24.326095Z","shell.execute_reply.started":"2022-04-23T05:57:24.312089Z","shell.execute_reply":"2022-04-23T05:57:24.325098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-04-23T05:57:24.327373Z","iopub.execute_input":"2022-04-23T05:57:24.327573Z","iopub.status.idle":"2022-04-23T05:57:36.853518Z","shell.execute_reply.started":"2022-04-23T05:57:24.327549Z","shell.execute_reply":"2022-04-23T05:57:36.852428Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-04-23T05:57:36.856753Z","iopub.execute_input":"2022-04-23T05:57:36.857018Z","iopub.status.idle":"2022-04-23T05:57:41.491263Z","shell.execute_reply.started":"2022-04-23T05:57:36.856990Z","shell.execute_reply":"2022-04-23T05:57:41.490292Z"},"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-04-23T05:57:41.492221Z","iopub.execute_input":"2022-04-23T05:57:41.492978Z","iopub.status.idle":"2022-04-23T05:57:48.105381Z","shell.execute_reply.started":"2022-04-23T05:57:41.492922Z","shell.execute_reply":"2022-04-23T05:57:48.104446Z"},"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-04-23T05:57:48.106718Z","iopub.execute_input":"2022-04-23T05:57:48.107493Z","iopub.status.idle":"2022-04-23T05:57:53.637951Z","shell.execute_reply.started":"2022-04-23T05:57:48.107438Z","shell.execute_reply":"2022-04-23T05:57:53.637051Z"},"trusted":true},"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":{"iopub.status.busy":"2022-04-23T05:57:53.639418Z","iopub.execute_input":"2022-04-23T05:57:53.639712Z","iopub.status.idle":"2022-04-23T05:58:14.907769Z","shell.execute_reply.started":"2022-04-23T05:57:53.639675Z","shell.execute_reply":"2022-04-23T05:58:14.907137Z"},"trusted":true},"execution_count":null,"outputs":[]}]}