{"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\nimport pandas as pd\n\n\ndf = pd.read_csv(\"../input/h-and-m-personalized-fashion-recommendations/transactions_train.csv\", dtype={\"article_id\": str})\nprint(df.shape)\ndf.head()","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-08-09T17:33:10.466691Z","iopub.execute_input":"2022-08-09T17:33:10.467546Z","iopub.status.idle":"2022-08-09T17:34:08.162941Z","shell.execute_reply.started":"2022-08-09T17:33:10.467363Z","shell.execute_reply":"2022-08-09T17:34:08.162245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df[\"t_dat\"] = pd.to_datetime(df[\"t_dat\"])\ndf[\"t_dat\"].max()","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:34:08.164499Z","iopub.execute_input":"2022-08-09T17:34:08.164861Z","iopub.status.idle":"2022-08-09T17:34:12.846223Z","shell.execute_reply.started":"2022-08-09T17:34:08.164823Z","shell.execute_reply":"2022-08-09T17:34:12.845470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"active_articles = df.groupby(\"article_id\")[\"t_dat\"].max().reset_index()\nactive_articles = active_articles[active_articles[\"t_dat\"] >= \"2019-09-01\"].reset_index()\nactive_articles.shape","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:34:12.847364Z","iopub.execute_input":"2022-08-09T17:34:12.847653Z","iopub.status.idle":"2022-08-09T17:34:17.664769Z","shell.execute_reply.started":"2022-08-09T17:34:12.847612Z","shell.execute_reply":"2022-08-09T17:34:17.664056Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = df[df[\"article_id\"].isin(active_articles[\"article_id\"])].reset_index(drop=True)\ndf.shape","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:34:17.667113Z","iopub.execute_input":"2022-08-09T17:34:17.667417Z","iopub.status.idle":"2022-08-09T17:34:24.353144Z","shell.execute_reply.started":"2022-08-09T17:34:17.667376Z","shell.execute_reply":"2022-08-09T17:34:24.352437Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df[\"week\"] = (df[\"t_dat\"].max() - df[\"t_dat\"]).dt.days // 7\ndf[\"week\"].value_counts()","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:34:24.354515Z","iopub.execute_input":"2022-08-09T17:34:24.354791Z","iopub.status.idle":"2022-08-09T17:34:25.766137Z","shell.execute_reply.started":"2022-08-09T17:34:24.354755Z","shell.execute_reply":"2022-08-09T17:34:25.765194Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.preprocessing import LabelEncoder\n\n\narticle_ids = np.concatenate([[\"placeholder\"], np.unique(df[\"article_id\"].values)])\n\nle_article = LabelEncoder()\nle_article.fit(article_ids)\ndf[\"article_id\"] = le_article.transform(df[\"article_id\"])","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:34:25.767905Z","iopub.execute_input":"2022-08-09T17:34:25.768207Z","iopub.status.idle":"2022-08-09T17:35:12.041335Z","shell.execute_reply.started":"2022-08-09T17:34:25.768166Z","shell.execute_reply":"2022-08-09T17:35:12.040495Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"WEEK_HIST_MAX = 5\n\ndef create_dataset(df, week):\n    hist_df = df[(df[\"week\"] > week) & (df[\"week\"] <= week + WEEK_HIST_MAX)]\n    hist_df = hist_df.groupby(\"customer_id\").agg({\"article_id\": list, \"week\": list}).reset_index()\n    hist_df.rename(columns={\"week\": 'week_history'}, inplace=True)\n    \n    target_df = df[df[\"week\"] == week]\n    target_df = target_df.groupby(\"customer_id\").agg({\"article_id\": list}).reset_index()\n    target_df.rename(columns={\"article_id\": \"target\"}, inplace=True)\n    target_df[\"week\"] = week\n    \n    return target_df.merge(hist_df, on=\"customer_id\", how=\"left\")\n\nval_weeks = [0]\ntrain_weeks = [1, 2, 3, 4]\n\n\nval_df = pd.concat([create_dataset(df, w) for w in val_weeks]).reset_index(drop=True)\ntrain_df = pd.concat([create_dataset(df, w) for w in train_weeks]).reset_index(drop=True)\ntrain_df.shape, val_df.shape","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:35:12.042702Z","iopub.execute_input":"2022-08-09T17:35:12.042945Z","iopub.status.idle":"2022-08-09T17:35:44.132256Z","shell.execute_reply.started":"2022-08-09T17:35:12.042909Z","shell.execute_reply":"2022-08-09T17:35:44.131470Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from torch.utils.data import Dataset, DataLoader\nimport torch\nfrom tqdm import tqdm\n\nclass HMDataset(Dataset):\n    def __init__(self, df, seq_len, is_test=False):\n        self.df = df.reset_index(drop=True)\n        self.seq_len = seq_len\n        self.is_test = is_test\n    \n    def __len__(self):\n        return self.df.shape[0]\n    \n    def __getitem__(self, index):\n        row = self.df.iloc[index]\n        \n        if self.is_test:#for inference\n            target = torch.zeros(2).float()\n            \n        article_hist = torch.zeros(self.seq_len).long()\n        week_hist = torch.ones(self.seq_len).float()\n        sample_index = torch.ones(2)\n        \n        if isinstance(row.article_id, list):\n            if len(row.article_id) >= self.seq_len:\n                article_hist = torch.LongTensor(row.article_id[-self.seq_len:])\n                week_hist = (torch.LongTensor(row.week_history[-self.seq_len:]) - row.week)/WEEK_HIST_MAX/2\n            else:\n                article_hist[-len(row.article_id):] = torch.LongTensor(row.article_id)\n                week_hist[-len(row.article_id):] = (torch.LongTensor(row.week_history) - row.week)/WEEK_HIST_MAX/2\n        \n        if not self.is_test:#target and index relevant to sampled softmax\n            \n            negative_sample_shape = 300 - len(row.target)\n            corpus = np.delete(np.arange(len(article_ids)),row.target)#remove the target items\n            \n            negative_sample = np.random.choice(corpus,negative_sample_shape,replace=False)#choose negative items\n            sample_target = torch.zeros(300).float()\n\n            sample_target[:len(row.target)] = torch.ones(len(row.target))\n            sample_index = torch.IntTensor(row.target)\n#             for i in range(len(row.target)):\n#                 sample_target[i] = 1.0\n#                 sample_index[i] = row.target[i]\n            sample_index = torch.cat((sample_index,torch.from_numpy(negative_sample)),0)\n            \n            target = sample_target\n\n\n        return article_hist, week_hist, sample_index, target\n    \nHMDataset(val_df, 64)[100]","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:50:43.436474Z","iopub.execute_input":"2022-08-09T17:50:43.437216Z","iopub.status.idle":"2022-08-09T17:50:43.467146Z","shell.execute_reply.started":"2022-08-09T17:50:43.437179Z","shell.execute_reply":"2022-08-09T17:50:43.466236Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def adjust_lr(optimizer, epoch):\n    if epoch < 1:\n        lr = 5e-5\n    elif epoch < 6:\n        lr = 1e-3\n    elif epoch < 9:\n        lr = 1e-4\n    else:\n        lr = 1e-5\n\n    for p in optimizer.param_groups:\n        p['lr'] = lr\n    return lr\n    \ndef get_optimizer(net):\n    optimizer = torch.optim.Adam(filter(lambda p: p.requires_grad, net.parameters()), lr=3e-4, betas=(0.9, 0.999),\n                                 eps=1e-08)\n    return optimizer","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:46:26.600002Z","iopub.execute_input":"2022-08-09T17:46:26.600285Z","iopub.status.idle":"2022-08-09T17:46:26.606510Z","shell.execute_reply.started":"2022-08-09T17:46:26.600255Z","shell.execute_reply":"2022-08-09T17:46:26.605750Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import copy","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:16:49.576715Z","iopub.execute_input":"2022-08-09T17:16:49.577269Z","iopub.status.idle":"2022-08-09T17:16:49.581173Z","shell.execute_reply.started":"2022-08-09T17:16:49.577232Z","shell.execute_reply":"2022-08-09T17:16:49.580365Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch.nn as nn\nimport torch.nn.functional as F\n\nclass HMModel(nn.Module):\n    def __init__(self, article_shape):\n        super(HMModel, self).__init__()\n        \n        self.article_emb = nn.Embedding(article_shape[0], embedding_dim=article_shape[1])\n        \n        self.article_likelihood = nn.Parameter(torch.zeros(article_shape[0]), requires_grad=True)\n        self.top = nn.Sequential(nn.Conv1d(2, 32, kernel_size=1), nn.LeakyReLU(),\n                                 nn.Conv1d(32, 8, kernel_size=1), nn.LeakyReLU(),\n                                 nn.Conv1d(8, 1, kernel_size=1))\n        \n    def forward(self, inputs,is_test=False):\n        article_hist, week_hist, sample_index = inputs[0], inputs[1], inputs[2]\n        x = self.article_emb(article_hist)\n        x = F.normalize(x, dim=2)#[256,16,512]\n        \n        if is_test:\n            x = x@F.normalize(self.article_emb.weight).T\n        else:\n#             sample_article_emb = self.article_emb(sample_index)#[256,100,512]\n#             sample_article_emb = torch.transpose(sample_article_emb, 1, 2)#[256,512,100]\n#             x= torch.matmul(x, sample_article_emb)#[256,16,100]\n            x = x@F.normalize(torch.transpose(self.article_emb(sample_index), 1, 2))\n            \n            \n        x, indices = x.max(axis=1)\n        x = x.clamp(1e-3, 0.999)\n        x = -torch.log(1/x - 1)\n\n        max_week = week_hist.unsqueeze(2).repeat(1, 1, x.shape[-1]).gather(1, indices.unsqueeze(1).repeat(1, week_hist.shape[1], 1))\n        max_week = max_week.mean(axis=1).unsqueeze(1)\n        #self.article_likelihood[None, None, :].repeat(x.shape[0], 1, 1)]\n        x = torch.cat([x.unsqueeze(1), max_week], axis=1)\n        x = self.top(x).squeeze(1)\n        return x\n\n    \nmodel = HMModel((len(le_article.classes_), 512))\nmodel = model.cuda()","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:46:28.732466Z","iopub.execute_input":"2022-08-09T17:46:28.733005Z","iopub.status.idle":"2022-08-09T17:46:29.127292Z","shell.execute_reply.started":"2022-08-09T17:46:28.732968Z","shell.execute_reply":"2022-08-09T17:46:29.126552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test1 = copy.deepcopy(model.article_emb.weight)","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:17:03.264943Z","iopub.execute_input":"2022-08-09T17:17:03.265663Z","iopub.status.idle":"2022-08-09T17:17:03.269496Z","shell.execute_reply.started":"2022-08-09T17:17:03.265628Z","shell.execute_reply":"2022-08-09T17:17:03.2688Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import sys\n\ndef calc_map(topk_preds, target_array, k=12):\n    metric = []\n    tp, fp = 0, 0\n    \n    for pred in topk_preds:\n        if target_array[pred]:\n            tp += 1\n            metric.append(tp/(tp + fp))\n        else:\n            fp += 1\n            \n    return np.sum(metric) / min(k, target_array.sum())\n\ndef read_data(data):\n    return tuple(d.cuda() for d in data[:-1]), data[-1].cuda()\n    #return tuple(d for d in data[:-1]), data[-1]\n\n\ndef validate(model, val_loader, k=12):\n    model.eval()\n    \n    tbar = tqdm(val_loader, file=sys.stdout)\n    \n    maps = []\n    \n    with torch.no_grad():\n        for idx, data in enumerate(tbar):\n            inputs, target = read_data(data)\n\n            logits = model(inputs)\n\n            _, indices = torch.topk(logits, k, dim=1)\n\n            indices = indices.detach().cpu().numpy()\n            target = target.detach().cpu().numpy()\n\n            for i in range(indices.shape[0]):\n                maps.append(calc_map(indices[i], target[i]))\n        \n    \n    return np.mean(maps)\n\nSEQ_LEN = 16\n\nBS = 256\nNW = 8\n\nval_dataset = HMDataset(val_df, SEQ_LEN)\nval_loader = DataLoader(val_dataset, batch_size=BS, shuffle=False, num_workers=NW,\n                          pin_memory=False, drop_last=False)","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:46:32.085500Z","iopub.execute_input":"2022-08-09T17:46:32.086066Z","iopub.status.idle":"2022-08-09T17:46:32.139106Z","shell.execute_reply.started":"2022-08-09T17:46:32.086018Z","shell.execute_reply":"2022-08-09T17:46:32.138428Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train and validate","metadata":{}},{"cell_type":"code","source":"def dice_loss(y_pred, y_true):\n    y_pred = y_pred.sigmoid()\n    intersect = (y_true*y_pred).sum(axis=1)\n    \n    return 1 - (intersect/(intersect + y_true.sum(axis=1) + y_pred.sum(axis=1))).mean()\n\n\ndef train(model, train_loader, val_loader, epochs):\n    np.random.seed(SEED)\n    \n    optimizer = get_optimizer(model)\n    scaler = torch.cuda.amp.GradScaler()\n\n    criterion = torch.nn.BCEWithLogitsLoss()\n    \n    for e in range(epochs):\n        model.train()\n        tbar = tqdm(train_loader, file=sys.stdout)\n        \n        lr = adjust_lr(optimizer, e)\n        \n        loss_list = []\n\n        for idx, data in enumerate(tbar):\n            inputs, target = read_data(data)\n            optimizer.zero_grad()\n            \n            with torch.cuda.amp.autocast():\n                logits = model(inputs)\n                loss = criterion(logits, target) + dice_loss(logits, target)\n            \n            \n            #loss.backward()\n            scaler.scale(loss).backward()\n            #optimizer.step()\n            scaler.step(optimizer)\n            scaler.update()\n            \n            loss_list.append(loss.detach().cpu().item())\n            \n            avg_loss = np.round(100*np.mean(loss_list), 4)\n\n            tbar.set_description(f\"Epoch {e+1} Loss: {avg_loss} lr: {lr}\")\n            \n            \n        val_map = validate(model, val_loader)\n\n        log_text = f\"Epoch {e+1}\\nTrain Loss: {avg_loss}\\nValidation MAP: {val_map}\\n\"\n            \n        print(log_text)\n        \n        #logfile = open(f\"models/{MODEL_NAME}_{SEED}.txt\", 'a')\n        #logfile.write(log_text)\n        #logfile.close()\n    return model\n\n\nMODEL_NAME = \"exp001\"\nSEED = 0\n\ntrain_dataset = HMDataset(train_df, SEQ_LEN)\ntrain_loader = DataLoader(train_dataset, batch_size=BS, shuffle=True, num_workers=NW,\n                          pin_memory=False, drop_last=True)\n\nmodel = train(model, train_loader, val_loader, epochs=10)","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:46:35.257068Z","iopub.execute_input":"2022-08-09T17:46:35.257329Z","iopub.status.idle":"2022-08-09T17:46:52.888694Z","shell.execute_reply.started":"2022-08-09T17:46:35.257298Z","shell.execute_reply":"2022-08-09T17:46:52.874895Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Finetune with more recent data for submission (include validation set)","metadata":{}},{"cell_type":"code","source":"train_dataset = HMDataset(train_df[train_df[\"week\"] < 4].append(val_df), SEQ_LEN)\ntrain_loader = DataLoader(train_dataset, batch_size=BS, shuffle=True, num_workers=NW,\n                          pin_memory=False, drop_last=True)\n\nmodel = train(model, train_loader, val_loader, epochs=10)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df = pd.read_csv('../input/h-and-m-personalized-fashion-recommendations/sample_submission.csv').drop(\"prediction\", axis=1)\nprint(test_df.shape)\ntest_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:39:35.403434Z","iopub.execute_input":"2022-08-09T17:39:35.404051Z","iopub.status.idle":"2022-08-09T17:39:39.948738Z","shell.execute_reply.started":"2022-08-09T17:39:35.404004Z","shell.execute_reply":"2022-08-09T17:39:39.947956Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_test_dataset(test_df):\n    week = -1\n    test_df[\"week\"] = week\n    \n    hist_df = df[(df[\"week\"] > week) & (df[\"week\"] <= week + WEEK_HIST_MAX)]\n    hist_df = hist_df.groupby(\"customer_id\").agg({\"article_id\": list, \"week\": list}).reset_index()\n    hist_df.rename(columns={\"week\": 'week_history'}, inplace=True)\n    \n    \n    return test_df.merge(hist_df, on=\"customer_id\", how=\"left\")\n\ntest_df = create_test_dataset(test_df)\ntest_df.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:40:46.262703Z","iopub.execute_input":"2022-08-09T17:40:46.263500Z","iopub.status.idle":"2022-08-09T17:40:52.584222Z","shell.execute_reply.started":"2022-08-09T17:40:46.263448Z","shell.execute_reply":"2022-08-09T17:40:52.583466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df[\"article_id\"].isnull().mean()","metadata":{"execution":{"iopub.status.busy":"2022-03-18T13:19:46.235925Z","iopub.execute_input":"2022-03-18T13:19:46.236179Z","iopub.status.idle":"2022-03-18T13:19:46.313921Z","shell.execute_reply.started":"2022-03-18T13:19:46.236144Z","shell.execute_reply":"2022-03-18T13:19:46.313072Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = HMDataset(test_df, SEQ_LEN, is_test=True)\ntest_loader = DataLoader(test_ds, batch_size=BS, shuffle=False, num_workers=NW,\n                          pin_memory=False, drop_last=False)\n\n\ndef inference(model, loader, k=12):\n    model.eval()\n    \n    tbar = tqdm(loader, file=sys.stdout)\n    \n    preds = []\n    \n    with torch.no_grad():\n        for idx, data in enumerate(tbar):\n            inputs, target = read_data(data)\n\n            logits = model(inputs,is_test=True)\n\n            _, indices = torch.topk(logits, k, dim=1)\n\n            indices = indices.detach().cpu().numpy()\n            target = target.detach().cpu().numpy()\n\n            for i in range(indices.shape[0]):\n                preds.append(\" \".join(list(le_article.inverse_transform(indices[i]))))\n        \n    \n    return preds\n\n\ntest_df[\"prediction\"] = inference(model, test_loader)","metadata":{"execution":{"iopub.status.busy":"2022-08-09T17:45:55.850547Z","iopub.execute_input":"2022-08-09T17:45:55.851492Z","iopub.status.idle":"2022-08-09T17:46:06.764460Z","shell.execute_reply.started":"2022-08-09T17:45:55.851440Z","shell.execute_reply":"2022-08-09T17:46:06.763327Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_df.to_csv(\"submission.csv\", index=False, columns=[\"customer_id\", \"prediction\"])","metadata":{"execution":{"iopub.status.busy":"2022-03-18T13:20:11.209147Z","iopub.status.idle":"2022-03-18T13:20:11.209811Z","shell.execute_reply.started":"2022-03-18T13:20:11.209573Z","shell.execute_reply":"2022-03-18T13:20:11.209598Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}