{"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 os\nimport gc\nimport pickle\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport torch\n\nimport torch.nn as nn\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import StratifiedKFold","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-06-29T17:30:14.229571Z","iopub.execute_input":"2022-06-29T17:30:14.230818Z","iopub.status.idle":"2022-06-29T17:30:16.619801Z","shell.execute_reply.started":"2022-06-29T17:30:14.230708Z","shell.execute_reply":"2022-06-29T17:30:16.618386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Gru Baseline Reference:\nhttps://www.kaggle.com/code/cdeotte/tensorflow-gru-starter-0-790/notebook","metadata":{}},{"cell_type":"markdown","source":"# Config","metadata":{}},{"cell_type":"code","source":"class CFG:\n    BATCH_SIZE=512\n    N_EPOCHS=7","metadata":{"execution":{"iopub.status.busy":"2022-06-29T17:30:16.621877Z","iopub.execute_input":"2022-06-29T17:30:16.62248Z","iopub.status.idle":"2022-06-29T17:30:16.629023Z","shell.execute_reply.started":"2022-06-29T17:30:16.622443Z","shell.execute_reply":"2022-06-29T17:30:16.627858Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"device=torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nprint(device)","metadata":{"execution":{"iopub.status.busy":"2022-06-29T17:30:18.110282Z","iopub.execute_input":"2022-06-29T17:30:18.111288Z","iopub.status.idle":"2022-06-29T17:30:18.118381Z","shell.execute_reply.started":"2022-06-29T17:30:18.111246Z","shell.execute_reply":"2022-06-29T17:30:18.116816Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# loading the dataset","metadata":{}},{"cell_type":"code","source":"%%time\nallX=[]\nally=[]\n\nfor i in range(100):\n    xpath = \"../input/amex-train-series/Xchunk_{}.npy\".format(i)\n    ypath = \"../input/amex-train-series/ychunk_{}.npy\".format(i)\n    \n    if not os.path.exists(xpath):\n        break\n    allX.append(np.load(xpath))\n    ally.append(np.load(ypath))\n    gc.collect()\n    \nallX=np.concatenate(allX)\nally=np.concatenate(ally)\nprint(allX.shape, ally.shape)","metadata":{"execution":{"iopub.status.busy":"2022-06-29T17:31:31.765214Z","iopub.execute_input":"2022-06-29T17:31:31.765616Z","iopub.status.idle":"2022-06-29T17:31:40.321735Z","shell.execute_reply.started":"2022-06-29T17:31:31.765582Z","shell.execute_reply":"2022-06-29T17:31:40.320434Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# dataset","metadata":{}},{"cell_type":"code","source":"class AmexDataset(torch.utils.data.Dataset):\n    def __init__(self, X, y, idxs, phase='train'):\n        self.idxs=idxs\n        self.X = X\n        self.y = y\n        self.phase=phase\n    \n    def __getitem__(self, idx):\n        idx=self.idxs[idx]\n        Xnumeric = torch.tensor(self.X[idx][:, :-11], dtype=torch.float32)\n        Xcat  = torch.tensor(self.X[idx][:, -11:], dtype=torch.long)\n        if self.phase !='train':\n            return Xnumeric, Xcat\n        y = torch.tensor(self.y[idx], dtype=torch.float32)\n        return (Xnumeric, Xcat , y)\n    \n    def __len__(self):\n        return len(self.idxs)","metadata":{"execution":{"iopub.status.busy":"2022-06-29T17:38:11.183755Z","iopub.execute_input":"2022-06-29T17:38:11.184204Z","iopub.status.idle":"2022-06-29T17:38:11.194606Z","shell.execute_reply.started":"2022-06-29T17:38:11.184171Z","shell.execute_reply":"2022-06-29T17:38:11.193386Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model","metadata":{}},{"cell_type":"code","source":"class AmexGruModel(nn.Module):\n    def __init__(self):\n        super().__init__()\n        self.embeddings = nn.ModuleList([nn.Embedding(10, 4, padding_idx=0) for _ in range(11)])\n        self.conv1d = nn.Conv1d(213, 256, 3)\n        self.silu = nn.SiLU()\n        self.bn = nn.BatchNorm1d(256)\n        self.dropout = nn.Dropout(0.1)\n        \n        \n        self.gru = nn.GRU(256, 128, batch_first = True)\n        self.out = nn.Sequential(\n            nn.Dropout(0.1),\n            \n            nn.Linear(128, 64),\n            nn.SiLU(),\n            nn.BatchNorm1d(64),\n            \n            nn.Linear(64, 32),\n            nn.SiLU(),\n            \n            nn.Linear(32, 1)\n        )\n    def forward(self, x, xcat):\n        xcat_embedds = []\n        for i in range(11):\n            xcat_embedds.append( self.embeddings[i](xcat[:, :, i]) )\n        xcat_embedds = torch.cat(xcat_embedds, dim=-1)\n        \n        x = torch.cat([x, xcat_embedds], dim=-1)\n        x = x.permute(0, 2, 1)\n        x = self.dropout(self.bn(self.silu(self.conv1d(x))))\n        x = x.permute(0, 2, 1)\n        (_, h) = self.gru(x)\n        h = h.squeeze(0)\n        y = self.out(h).view(-1)\n        return y","metadata":{"execution":{"iopub.status.busy":"2022-06-29T17:41:03.476458Z","iopub.execute_input":"2022-06-29T17:41:03.47695Z","iopub.status.idle":"2022-06-29T17:41:03.492776Z","shell.execute_reply.started":"2022-06-29T17:41:03.476911Z","shell.execute_reply":"2022-06-29T17:41:03.491481Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Metrics","metadata":{}},{"cell_type":"code","source":"def top_4percent(pred_df):\n    df = pred_df.copy()\n    df = df.sort_values('pred', ascending=False)\n    df['weight'] = df['target'].apply(lambda v: 20 if v==0 else 1)\n    four_percent_cutoff = 0.04 * sum(df['weight'])\n    df['weight_cumsum'] = df['weight'].cumsum()\n    df_cutoff = df[df.weight_cumsum <= four_percent_cutoff]\n    \n    return df_cutoff['target'].sum()/df['target'].sum()\n\ndef weighted_gini(pred_df):\n    df = pred_df.copy()\n    df = df.sort_values('pred', ascending=False)\n    df['weight'] = df['target'].apply(lambda v: 20 if v==0 else 1)\n    df['random'] = (df['weight'] / df['weight'].sum()).cumsum()\n    total_pos = (df['target'] * df['weight']).sum()\n    df['cum_pos_found'] = (df['target'] * df['weight']).cumsum()\n    df['lorentz'] = df['cum_pos_found'] / total_pos\n    df['gini'] = (df['lorentz'] - df['random']) * df['weight']\n    return df['gini'].sum()\n\n\ndef normalized_gini(df):\n    df_true=df[['target']].copy()\n    df_true['pred'] = df_true['target'].copy()\n    \n    G = weighted_gini(df)/weighted_gini(df_true)\n    return G","metadata":{"execution":{"iopub.status.busy":"2022-06-29T17:41:03.569023Z","iopub.execute_input":"2022-06-29T17:41:03.570484Z","iopub.status.idle":"2022-06-29T17:41:03.584614Z","shell.execute_reply.started":"2022-06-29T17:41:03.570427Z","shell.execute_reply":"2022-06-29T17:41:03.583542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# losses","metadata":{}},{"cell_type":"code","source":"def get_rank_loss(y, yhat):\n    loss = torch.tensor(0.0, device=device)\n    ypos = yhat[y==1]\n    yneg = yhat[y==0]\n    \n    if len(ypos) == 0 or len(yneg) == 0:\n        return loss\n    \n    yneg = yneg.repeat((len(ypos), 1))\n    ypos = ypos.unsqueeze(dim=-1)\n    loss = -torch.log( torch.sigmoid( ypos-yneg ) ).mean()\n    return loss","metadata":{"execution":{"iopub.status.busy":"2022-06-29T17:41:03.646789Z","iopub.execute_input":"2022-06-29T17:41:03.64834Z","iopub.status.idle":"2022-06-29T17:41:03.658183Z","shell.execute_reply.started":"2022-06-29T17:41:03.648298Z","shell.execute_reply":"2022-06-29T17:41:03.656627Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# train model","metadata":{}},{"cell_type":"code","source":"def get_lr(epoch_num):\n    lrs = [1e-3, 1e-3, 1e-3, 1e-4, 1e-4, 1e-4, 1e-5]\n    if epoch_num < len(lrs):\n        return lrs[foldnum]\n    return 1e-5","metadata":{"execution":{"iopub.status.busy":"2022-06-29T17:41:03.753219Z","iopub.execute_input":"2022-06-29T17:41:03.754064Z","iopub.status.idle":"2022-06-29T17:41:03.759919Z","shell.execute_reply.started":"2022-06-29T17:41:03.753994Z","shell.execute_reply":"2022-06-29T17:41:03.759018Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def evaluate(model, val_dataloader):\n    model.eval()\n    ytrue=[]\n    ypred=[]\n    \n    for (Xnumeric, Xcat , y) in val_dataloader:\n        Xnumeric = Xnumeric.to(device)\n        Xcat = Xcat.to(device)\n        y = y.to(device)\n        \n        with torch.no_grad():\n            yhat=model(Xnumeric, Xcat)\n            yhat = yhat.sigmoid()\n            ytrue += y.cpu().tolist()\n            ypred += yhat.cpu().tolist()\n    \n    df = pd.DataFrame.from_dict({\n        'target': ytrue,\n        'pred': ypred\n    })\n    \n    G = normalized_gini(df[['target', 'pred']])\n    D = top_4percent(df[['target', 'pred']])\n    \n    M = (G+D)/2\n    return (G, D, M)","metadata":{"execution":{"iopub.status.busy":"2022-06-29T17:41:03.842268Z","iopub.execute_input":"2022-06-29T17:41:03.84337Z","iopub.status.idle":"2022-06-29T17:41:03.853123Z","shell.execute_reply.started":"2022-06-29T17:41:03.843324Z","shell.execute_reply":"2022-06-29T17:41:03.851787Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def train_model(foldnum, train_dataloader, val_dataloader):\n    best_eval=None\n    \n    model = AmexGruModel().to(device)\n    criterion = nn.BCEWithLogitsLoss()\n    optimizer = torch.optim.AdamW(model.parameters(),lr=1e-3, weight_decay=1e-6)\n    scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, \n                                                           T_max = CFG.N_EPOCHS * len(train_dataloader), \n                                                           eta_min=1e-5)\n    \n    for e in range(CFG.N_EPOCHS):\n        epoch_loss=[]\n        model.train()\n        for it, (Xnumeric, Xcat , y) in enumerate(train_dataloader):\n            Xnumeric = Xnumeric.to(device)\n            Xcat = Xcat.to(device)\n            y = y.to(device)\n            \n            yhat = model(Xnumeric, Xcat)\n            loss = criterion(yhat, y) + 0.4 * get_rank_loss(y, yhat)\n            \n            optimizer.zero_grad(set_to_none=True)\n            loss.backward()\n            optimizer.step()\n            scheduler.step()\n            \n            epoch_loss.append(loss.item())\n        \n        #Evaluating\n        (G, D, M) = evaluate(model, val_dataloader)\n        if best_eval is None or best_eval<M:\n            best_eval = M\n            torch.save(model, \"model{}.pt\".format(foldnum))\n        \n        print(\"epoch:{:.4f} | loss:{:.4f}\".format(e, np.mean(epoch_loss)))\n        print(\"current Eval:{:.4f} | best Eval:{:.4f}\".format(M, best_eval))\n        print(\"Gini:{:.4f} | Default Rate:{:4f}\".format(G, D))\n        print()\n        print()\n        \n        plt.title(\"train epoch loss.\")\n        plt.plot(epoch_loss)\n        plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-06-29T17:41:03.988554Z","iopub.execute_input":"2022-06-29T17:41:03.98924Z","iopub.status.idle":"2022-06-29T17:41:04.002634Z","shell.execute_reply.started":"2022-06-29T17:41:03.989202Z","shell.execute_reply":"2022-06-29T17:41:04.001567Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"skf = StratifiedKFold(n_splits=7, random_state=232, shuffle=True)\nfor foldnum, (train_index, val_index) in enumerate(skf.split(ally, ally)):\n    train_dataset = AmexDataset(allX,ally, train_index)\n    val_dataset = AmexDataset(allX, ally, val_index)\n    \n    train_dataloader = torch.utils.data.DataLoader(train_dataset, \n                                                   batch_size=CFG.BATCH_SIZE, \n                                                   shuffle=True,\n                                                   drop_last=True)\n    \n    val_dataloader = torch.utils.data.DataLoader(val_dataset, batch_size=CFG.BATCH_SIZE, \n                                                   shuffle=False,\n                                                   drop_last=False)\n    \n    \n    print(\"Foldnumber:\", foldnum)\n    print(\"number of train iterations:\", len(train_dataloader))\n    print(\"number of val iterations:\", len(val_dataloader))\n    \n    train_model(foldnum, train_dataloader, val_dataloader)","metadata":{"execution":{"iopub.status.busy":"2022-06-29T17:41:04.144613Z","iopub.execute_input":"2022-06-29T17:41:04.145336Z","iopub.status.idle":"2022-06-29T17:41:20.813616Z","shell.execute_reply.started":"2022-06-29T17:41:04.145295Z","shell.execute_reply":"2022-06-29T17:41:20.812455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Inference","metadata":{}},{"cell_type":"code","source":"def load_pickle_obj(filename):\n    with open(filename, 'rb') as file:\n        obj = pickle.load(file)\n    return obj\n\ntest_id2customer = load_pickle_obj(\"../input/amex-datasetcategorical-encoders/test_id2customer.pkl\")\nprint(len(test_id2customer))","metadata":{"execution":{"iopub.status.busy":"2022-06-24T13:51:16.229008Z","iopub.execute_input":"2022-06-24T13:51:16.229819Z","iopub.status.idle":"2022-06-24T13:51:17.34821Z","shell.execute_reply.started":"2022-06-24T13:51:16.229765Z","shell.execute_reply":"2022-06-24T13:51:17.346866Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"models=[]\nfor i in range(7):\n    model = torch.load(\"model{}.pt\".format(i))\n    models.append(model)","metadata":{"execution":{"iopub.status.busy":"2022-06-24T13:51:17.349413Z","iopub.execute_input":"2022-06-24T13:51:17.349727Z","iopub.status.idle":"2022-06-24T13:51:17.371544Z","shell.execute_reply.started":"2022-06-24T13:51:17.349697Z","shell.execute_reply":"2022-06-24T13:51:17.370444Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_df = []\nfor fileid in range(200):\n    xpath = \"../input/amex-test-time-series-dataset/Xchunk_{}.npy\".format(fileid)\n    customer_path = \"../input/amex-test-time-series-dataset/customerIds_chunk_{}.npy\".format(fileid)\n    \n    if os.path.exists(xpath):\n        Xtest = np.load(xpath)\n        customerids = np.load(customer_path)\n        test_ids = np.arange(len(Xtest))\n        test_dataset = AmexDataset(Xtest, None, test_ids, phase=\"infer\")\n        test_loader  = torch.utils.data.DataLoader(test_dataset, shuffle=False, drop_last=False, batch_size=512)\n        \n        all_preds=[]\n        for (Xnumeric, Xcat) in test_loader:\n            Xnumeric = Xnumeric.to(device)\n            Xcat = Xcat.to(device)\n            \n            preds=np.zeros(len(Xnumeric))\n            \n            for model in models:\n                model.eval()\n                with torch.no_grad():\n                    yhat = model(Xnumeric, Xcat).sigmoid()\n                    preds += yhat.cpu().numpy()\n            preds = preds/len(models)\n            all_preds += list(preds)\n        \n        df = pd.DataFrame.from_dict({\n            'customer_ID': customerids,\n            'prediction': all_preds\n        })\n        df.fillna(0.0, inplace=True)\n        sub_df.append(df)","metadata":{"execution":{"iopub.status.busy":"2022-06-24T13:51:17.37287Z","iopub.execute_input":"2022-06-24T13:51:17.373345Z","iopub.status.idle":"2022-06-24T13:51:20.239783Z","shell.execute_reply.started":"2022-06-24T13:51:17.373286Z","shell.execute_reply":"2022-06-24T13:51:20.23863Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_df=pd.concat(sub_df)\nsub_df['customer_ID'] = sub_df['customer_ID'].apply(lambda k: test_id2customer[k])\nsub_df.head()\n","metadata":{"execution":{"iopub.status.busy":"2022-06-24T13:51:20.241485Z","iopub.execute_input":"2022-06-24T13:51:20.241805Z","iopub.status.idle":"2022-06-24T13:51:20.265424Z","shell.execute_reply.started":"2022-06-24T13:51:20.241776Z","shell.execute_reply":"2022-06-24T13:51:20.264435Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_df.shape","metadata":{"execution":{"iopub.status.busy":"2022-06-24T13:56:11.385275Z","iopub.execute_input":"2022-06-24T13:56:11.386267Z","iopub.status.idle":"2022-06-24T13:56:11.396013Z","shell.execute_reply.started":"2022-06-24T13:56:11.386227Z","shell.execute_reply":"2022-06-24T13:56:11.394788Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sub_df.to_csv(\"submission.csv\", index=False)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}