{"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":"# Intro\nInference notebook for [Hotel-ID starter - similarity - training](https://www.kaggle.com/code/michaln/hotel-id-starter-similarity-training)\n\nUsing model and embeddings from the training notebook to generate embeddings for test data and find similar images.","metadata":{"id":"DAY5rHgTm7e8","papermill":{"duration":0.024896,"end_time":"2022-03-24T14:00:54.588459","exception":false,"start_time":"2022-03-24T14:00:54.563563","status":"completed"},"tags":[]}},{"cell_type":"markdown","source":"# Setup","metadata":{}},{"cell_type":"code","source":"import sys\nsys.path.append('../input/timm-pytorch-image-models/pytorch-image-models-master')","metadata":{"executionInfo":{"elapsed":16271,"status":"ok","timestamp":1619310548121,"user":{"displayName":"Jeom Jin-Ho","photoUrl":"","userId":"00155613517919499503"},"user_tz":-120},"id":"alleged-legislation","outputId":"c6541e5f-ffb4-4609-d6c6-39784e6a07b1","papermill":{"duration":0.036572,"end_time":"2022-03-24T14:00:54.649254","exception":false,"start_time":"2022-03-24T14:00:54.612682","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:18.613039Z","iopub.execute_input":"2022-05-30T23:33:18.613559Z","iopub.status.idle":"2022-05-30T23:33:18.617382Z","shell.execute_reply.started":"2022-05-30T23:33:18.613522Z","shell.execute_reply":"2022-05-30T23:33:18.616697Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Imports","metadata":{"id":"cZoSOL9Qm-Yr","papermill":{"duration":0.023644,"end_time":"2022-03-24T14:00:54.696898","exception":false,"start_time":"2022-03-24T14:00:54.673254","status":"completed"},"tags":[]}},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport random\nimport os\nimport math","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","executionInfo":{"elapsed":14459,"status":"ok","timestamp":1619310548121,"user":{"displayName":"Jeom Jin-Ho","photoUrl":"","userId":"00155613517919499503"},"user_tz":-120},"id":"expired-matter","papermill":{"duration":0.030271,"end_time":"2022-03-24T14:00:54.751131","exception":false,"start_time":"2022-03-24T14:00:54.72086","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:18.663419Z","iopub.execute_input":"2022-05-30T23:33:18.664233Z","iopub.status.idle":"2022-05-30T23:33:18.668363Z","shell.execute_reply.started":"2022-05-30T23:33:18.664197Z","shell.execute_reply":"2022-05-30T23:33:18.667354Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from PIL import Image as pil_image\nfrom tqdm import tqdm","metadata":{"executionInfo":{"elapsed":16003,"status":"ok","timestamp":1619310550014,"user":{"displayName":"Jeom Jin-Ho","photoUrl":"","userId":"00155613517919499503"},"user_tz":-120},"id":"extreme-problem","papermill":{"duration":3.220402,"end_time":"2022-03-24T14:00:57.995239","exception":false,"start_time":"2022-03-24T14:00:54.774837","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:18.708108Z","iopub.execute_input":"2022-05-30T23:33:18.708735Z","iopub.status.idle":"2022-05-30T23:33:18.713168Z","shell.execute_reply.started":"2022-05-30T23:33:18.708691Z","shell.execute_reply":"2022-05-30T23:33:18.71224Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import torch\nimport torch.nn as nn\nfrom torch.utils.data import DataLoader\n\nimport timm\nfrom sklearn.metrics.pairwise import cosine_similarity","metadata":{"executionInfo":{"elapsed":19672,"status":"ok","timestamp":1619310554099,"user":{"displayName":"Jeom Jin-Ho","photoUrl":"","userId":"00155613517919499503"},"user_tz":-120},"id":"angry-domain","papermill":{"duration":2.727834,"end_time":"2022-03-24T14:01:00.766951","exception":false,"start_time":"2022-03-24T14:00:58.039117","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:18.777678Z","iopub.execute_input":"2022-05-30T23:33:18.778428Z","iopub.status.idle":"2022-05-30T23:33:18.782971Z","shell.execute_reply.started":"2022-05-30T23:33:18.778372Z","shell.execute_reply":"2022-05-30T23:33:18.782173Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Global","metadata":{"id":"0B00pe7mnBTj","papermill":{"duration":0.023573,"end_time":"2022-03-24T14:01:00.814976","exception":false,"start_time":"2022-03-24T14:01:00.791403","status":"completed"},"tags":[]}},{"cell_type":"code","source":"SEED = 42\nIMG_SIZE = 256\nN_MATCHES = 5\n\nPROJECT_FOLDER = \"../input/hotel-id-to-combat-human-trafficking-2022-fgvc9/\"\nTRAIN_DATA_FOLDER = \"../input/hotelid-2022-train-images-256x256/images/\"\nTEST_DATA_FOLDER = PROJECT_FOLDER + \"test_images/\"","metadata":{"executionInfo":{"elapsed":589,"status":"ok","timestamp":1619310979015,"user":{"displayName":"Jeom Jin-Ho","photoUrl":"","userId":"00155613517919499503"},"user_tz":-120},"id":"contained-brief","papermill":{"duration":0.03175,"end_time":"2022-03-24T14:01:00.871686","exception":false,"start_time":"2022-03-24T14:01:00.839936","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:18.864149Z","iopub.execute_input":"2022-05-30T23:33:18.864741Z","iopub.status.idle":"2022-05-30T23:33:18.869093Z","shell.execute_reply.started":"2022-05-30T23:33:18.864702Z","shell.execute_reply":"2022-05-30T23:33:18.868281Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\n#temp block for testing\nimport shutil\n\nos.listdir(TEST_DATA_FOLDER)\n#os.mkdir(\"../temp_test_dir\")\nshutil.copy(TEST_DATA_FOLDER + \"/abc.jpg\", \"../temp_test_dir/\")\nos.rename(\"../temp_test_dir/abc.jpg\", \"../temp_test_dir/abc2.jpg\")\nshutil.copy(TEST_DATA_FOLDER + \"/abc.jpg\", \"../temp_test_dir\")\nprint(os.listdir(\"../temp_test_dir/\"))\nTEST_DATA_FOLDER = \"../temp_test_dir/\"\n'''","metadata":{"execution":{"iopub.status.busy":"2022-05-30T23:33:18.920658Z","iopub.execute_input":"2022-05-30T23:33:18.921276Z","iopub.status.idle":"2022-05-30T23:33:18.928779Z","shell.execute_reply.started":"2022-05-30T23:33:18.921236Z","shell.execute_reply":"2022-05-30T23:33:18.927877Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(os.listdir(PROJECT_FOLDER))","metadata":{"executionInfo":{"elapsed":879,"status":"ok","timestamp":1619310979515,"user":{"displayName":"Jeom Jin-Ho","photoUrl":"","userId":"00155613517919499503"},"user_tz":-120},"id":"PZvmFng7ctO3","outputId":"dce0cc91-8e70-4acc-a0b8-6763ffffd5ca","papermill":{"duration":0.031651,"end_time":"2022-03-24T14:01:00.927239","exception":false,"start_time":"2022-03-24T14:01:00.895588","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:18.953592Z","iopub.execute_input":"2022-05-30T23:33:18.954192Z","iopub.status.idle":"2022-05-30T23:33:18.96238Z","shell.execute_reply.started":"2022-05-30T23:33:18.95415Z","shell.execute_reply":"2022-05-30T23:33:18.961292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def seed_everything(seed):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    torch.manual_seed(seed)\n    torch.cuda.manual_seed(seed)\n    torch.backends.cudnn.deterministic = True","metadata":{"executionInfo":{"elapsed":600,"status":"ok","timestamp":1619310981653,"user":{"displayName":"Jeom Jin-Ho","photoUrl":"","userId":"00155613517919499503"},"user_tz":-120},"id":"eastern-content","papermill":{"duration":0.032105,"end_time":"2022-03-24T14:01:01.031949","exception":false,"start_time":"2022-03-24T14:01:00.999844","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:18.98494Z","iopub.execute_input":"2022-05-30T23:33:18.985199Z","iopub.status.idle":"2022-05-30T23:33:18.992323Z","shell.execute_reply.started":"2022-05-30T23:33:18.985168Z","shell.execute_reply":"2022-05-30T23:33:18.991104Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Dataset and transformations","metadata":{"id":"xaJKvvuKnW4k","papermill":{"duration":0.023988,"end_time":"2022-03-24T14:01:01.080488","exception":false,"start_time":"2022-03-24T14:01:01.0565","status":"completed"},"tags":[]}},{"cell_type":"code","source":"import albumentations as A\nimport albumentations.pytorch as APT\nimport cv2 \n\nbase_transform = A.Compose([\n    A.ToFloat(),\n    APT.transforms.ToTensorV2(),\n])","metadata":{"executionInfo":{"elapsed":1519,"status":"ok","timestamp":1619310984075,"user":{"displayName":"Jeom Jin-Ho","photoUrl":"","userId":"00155613517919499503"},"user_tz":-120},"id":"revolutionary-membership","papermill":{"duration":0.747421,"end_time":"2022-03-24T14:01:01.852072","exception":false,"start_time":"2022-03-24T14:01:01.104651","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:19.018463Z","iopub.execute_input":"2022-05-30T23:33:19.019071Z","iopub.status.idle":"2022-05-30T23:33:19.023979Z","shell.execute_reply.started":"2022-05-30T23:33:19.019026Z","shell.execute_reply":"2022-05-30T23:33:19.023198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def pad_image(img):\n    w, h, c = np.shape(img)\n    if w > h:\n        pad = int((w - h) / 2)\n        img = cv2.copyMakeBorder(img, 0, 0, pad, pad, cv2.BORDER_CONSTANT, value=0)\n    else:\n        pad = int((h - w) / 2)\n        img = cv2.copyMakeBorder(img, pad, pad, 0, 0, cv2.BORDER_CONSTANT, value=0)\n        \n    return img\n\n\ndef open_and_preprocess_image(image_path):\n    img = cv2.imread(image_path)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img = pad_image(img)\n    return cv2.resize(img, (IMG_SIZE, IMG_SIZE))","metadata":{"execution":{"iopub.status.busy":"2022-05-30T23:33:19.050324Z","iopub.execute_input":"2022-05-30T23:33:19.050785Z","iopub.status.idle":"2022-05-30T23:33:19.058086Z","shell.execute_reply.started":"2022-05-30T23:33:19.050749Z","shell.execute_reply":"2022-05-30T23:33:19.057318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class HotelImageDataset:\n    def __init__(self, data, transform=None, data_folder=\"train_images/\"):\n        self.data = data\n        self.data_folder = data_folder\n        self.transform = transform\n\n    def __len__(self):\n        return len(self.data)\n    \n    def __getitem__(self, idx):\n        record = self.data.iloc[idx]\n        image_path = self.data_folder + record[\"image_id\"]\n        \n        image = np.array(open_and_preprocess_image(image_path)).astype(np.uint8)\n\n        if self.transform:\n            transformed = self.transform(image=image)\n            image = transformed[\"image\"]\n        \n        return {\n            \"image\" : image,\n        }","metadata":{"executionInfo":{"elapsed":1058,"status":"ok","timestamp":1619310984077,"user":{"displayName":"Jeom Jin-Ho","photoUrl":"","userId":"00155613517919499503"},"user_tz":-120},"id":"found-mouth","papermill":{"duration":0.037507,"end_time":"2022-03-24T14:01:01.914352","exception":false,"start_time":"2022-03-24T14:01:01.876845","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:19.082912Z","iopub.execute_input":"2022-05-30T23:33:19.083376Z","iopub.status.idle":"2022-05-30T23:33:19.090644Z","shell.execute_reply.started":"2022-05-30T23:33:19.083337Z","shell.execute_reply":"2022-05-30T23:33:19.089806Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model","metadata":{"id":"NMDM4PwPnced","papermill":{"duration":0.023902,"end_time":"2022-03-24T14:01:01.962307","exception":false,"start_time":"2022-03-24T14:01:01.938405","status":"completed"},"tags":[]}},{"cell_type":"code","source":"class EmbeddingModel(nn.Module):\n    def __init__(self, n_classes=100, embedding_size=64, backbone_name=\"efficientnet_b0\"):\n        super(EmbeddingModel, self).__init__()\n        \n        self.backbone = timm.create_model(backbone_name, num_classes=n_classes, pretrained=False)\n        in_features = self.backbone.get_classifier().in_features\n        if backbone_name == 'resnet50':\n            self.backbone.fc = nn.Identity()\n        else:\n            self.backbone.classifier = nn.Identity()\n        self.embedding = nn.Linear(in_features, embedding_size)\n        self.classifier = nn.Linear(embedding_size, n_classes)\n\n    def embed_and_classify(self, x):\n        x = self.forward(x)\n        return x, self.classifier(x)\n\n    def forward(self, x):\n        x = self.backbone(x)\n        x = x.view(x.size(0), -1)\n        x = self.embedding(x)\n        return x","metadata":{"papermill":{"duration":0.032166,"end_time":"2022-03-24T14:01:02.018479","exception":false,"start_time":"2022-03-24T14:01:01.986313","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:19.136651Z","iopub.execute_input":"2022-05-30T23:33:19.137319Z","iopub.status.idle":"2022-05-30T23:33:19.145593Z","shell.execute_reply.started":"2022-05-30T23:33:19.13728Z","shell.execute_reply":"2022-05-30T23:33:19.144454Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model helper functions","metadata":{"id":"YMZYKhUSneMY","papermill":{"duration":0.024153,"end_time":"2022-03-24T14:01:02.067537","exception":false,"start_time":"2022-03-24T14:01:02.043384","status":"completed"},"tags":[]}},{"cell_type":"code","source":"def generate_embeddings(args, loader, model, bar_desc=\"Generating embeds\"):\n    outputs_all = []\n    \n    model.eval()\n    with torch.no_grad():\n        t = tqdm(loader, desc=bar_desc)\n        for i, sample in enumerate(t):\n            #print(sample, '\\n', sample['image'])\n            input = sample['image'].to(args.device)\n            output = model(input)\n            outputs_all.extend(output.detach().cpu().numpy())\n            \n    return outputs_all","metadata":{"execution":{"iopub.status.busy":"2022-05-30T23:33:19.210319Z","iopub.execute_input":"2022-05-30T23:33:19.210905Z","iopub.status.idle":"2022-05-30T23:33:19.216881Z","shell.execute_reply.started":"2022-05-30T23:33:19.210867Z","shell.execute_reply":"2022-05-30T23:33:19.216105Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"'''\ndef find_matches(query, base_embeds, base_targets, k=N_MATCHES):\n    distance_df = pd.DataFrame(index=np.arange(len(base_targets)), data={\"hotel_id\": base_targets})\n    # calculate cosine distance of query embeds to all base embeds\n    distance_df[\"distance\"] = cosine_similarity([query], list(base_embeds))[0]\n    # sort by distance and hotel_id\n    distance_df = distance_df.sort_values(by=[\"distance\", \"hotel_id\"], ascending=False).reset_index(drop=True)\n    # return first 5 different hotel_id_codes\n    return distance_df[\"hotel_id\"].unique()[:N_MATCHES]\n\n\ndef predict(args, base_embeddings_df, test_loader, model):\n    test_embeds = generate_embeddings(args, test_loader, model, \"Generate test embeddings\")\n    \n    preds = []\n    for query_embeds in tqdm(test_embeds, desc=\"Similarity - match finding\"):\n        tmp = find_matches(query_embeds, \n                           base_embeddings_df[\"embeddings\"].values, \n                           base_embeddings_df[\"hotel_id\"].values)\n        preds.extend([tmp])\n        \n    return preds\n'''","metadata":{"papermill":{"duration":0.034692,"end_time":"2022-03-24T14:01:02.127372","exception":false,"start_time":"2022-03-24T14:01:02.09268","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:19.243753Z","iopub.execute_input":"2022-05-30T23:33:19.244547Z","iopub.status.idle":"2022-05-30T23:33:19.250972Z","shell.execute_reply.started":"2022-05-30T23:33:19.244506Z","shell.execute_reply":"2022-05-30T23:33:19.250221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#for every model, take the array of all distances of every test image and sum it to an existing array. \n#At the end, take the mean and return the hotel id of the 5 highest scores\n\n# https://stackoverflow.com/questions/480214/how-do-you-remove-duplicates-from-a-list-whilst-preserving-order\ndef f7(seq): #unique without sorting\n    seen = set()\n    seen_add = seen.add\n    return [x for x in seq if not (x in seen or seen_add(x))]\n        \n\ndef find_matches_distances(query, base_embeds, base_targets, k=N_MATCHES):\n    distance_df = pd.DataFrame(index=np.arange(len(base_targets)), data={\"hotel_id\": base_targets})\n    # calculate cosine distance of query embeds to all base embeds\n    distance_df[\"distance\"] = cosine_similarity([query], list(base_embeds))[0]\n    # return vector of distances\n    return distance_df\n\ndef predict(args, base_embeddings_df, test_loader, model): #input i args and models\n    preds = np.zeros([len(test_loader[0].dataset), len(base_embeddings_df[0])]) #num test imgs x num train imgs\n    hotel_order = 0\n    \n    for i, (arg, mod, base, t_loader) in enumerate(zip(args, model, base_embeddings_df, test_loader)):\n        test_embeds = generate_embeddings(arg, t_loader, mod, f\"Generate test embeddings for model {i}\")\n        \n        preds_model = []\n        for query_embeds in tqdm(test_embeds, desc=\"Similarity - match finding\"): #for every test image\n            tmp = find_matches_distances(query_embeds, # should return an array of all distances for that query and model\n                               base[\"embeddings\"].values, \n                               base[\"hotel_id\"].values)\n            preds_model.append(tmp[\"distance\"])\n            hotel_order = tmp[\"hotel_id\"]\n        \n        preds += np.array(preds_model)\n        \n    # sort and return only the hotel ids\n    order = np.argsort(preds/len(args), axis = 1)\n    final = []\n    for img in range(len(test_loader[0].dataset)): #for every test image \n        tmp = [hotel_order[i] for i in order[img]]\n        final.append(f7(tmp[::-1])[:N_MATCHES])\n    \n    return np.array(final)\n","metadata":{"execution":{"iopub.status.busy":"2022-05-30T23:33:19.275623Z","iopub.execute_input":"2022-05-30T23:33:19.27609Z","iopub.status.idle":"2022-05-30T23:33:19.290985Z","shell.execute_reply.started":"2022-05-30T23:33:19.276051Z","shell.execute_reply":"2022-05-30T23:33:19.290054Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prepare data","metadata":{"id":"AwShW1wXniD6","papermill":{"duration":0.023807,"end_time":"2022-03-24T14:01:02.175822","exception":false,"start_time":"2022-03-24T14:01:02.152015","status":"completed"},"tags":[]}},{"cell_type":"code","source":"test_df = pd.DataFrame(data={\"image_id\": os.listdir(TEST_DATA_FOLDER), \"hotel_id\": \"\"}).sort_values(by=\"image_id\")","metadata":{"executionInfo":{"elapsed":3742,"status":"ok","timestamp":1619311036476,"user":{"displayName":"Jeom Jin-Ho","photoUrl":"","userId":"00155613517919499503"},"user_tz":-120},"id":"discrete-right","outputId":"c21ed589-3139-4919-b5d5-07bcf6f1df15","papermill":{"duration":0.103381,"end_time":"2022-03-24T14:01:02.453866","exception":false,"start_time":"2022-03-24T14:01:02.350485","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:19.308009Z","iopub.execute_input":"2022-05-30T23:33:19.308546Z","iopub.status.idle":"2022-05-30T23:33:19.316879Z","shell.execute_reply.started":"2022-05-30T23:33:19.308509Z","shell.execute_reply":"2022-05-30T23:33:19.316045Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Prepare model","metadata":{"id":"5JPdD2bpnniP","papermill":{"duration":0.023835,"end_time":"2022-03-24T14:01:02.502786","exception":false,"start_time":"2022-03-24T14:01:02.478951","status":"completed"},"tags":[]}},{"cell_type":"code","source":"def get_model(backbone_name, checkpoint_path, args):\n    model = EmbeddingModel(args.n_classes, args.embedding_size, backbone_name)\n        \n    checkpoint = torch.load(checkpoint_path)\n    model.load_state_dict(checkpoint[\"model\"])\n    model = model.to(args.device)\n    \n    return model","metadata":{"papermill":{"duration":0.031082,"end_time":"2022-03-24T14:01:02.557921","exception":false,"start_time":"2022-03-24T14:01:02.526839","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:19.339045Z","iopub.execute_input":"2022-05-30T23:33:19.339589Z","iopub.status.idle":"2022-05-30T23:33:19.34467Z","shell.execute_reply.started":"2022-05-30T23:33:19.339553Z","shell.execute_reply":"2022-05-30T23:33:19.343854Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class args1:\n    batch_size = 32\n    num_workers = 2\n    embedding_size = 128\n    device = ('cuda' if torch.cuda.is_available() else 'cpu')\n    \nclass args2:\n    batch_size = 16\n    num_workers = 2\n    embedding_size = 128\n    device = ('cuda' if torch.cuda.is_available() else 'cpu')\n    \nclass args3:\n    batch_size = 32\n    num_workers = 2\n    embedding_size = 128\n    device = ('cuda' if torch.cuda.is_available() else 'cpu')\n\n    \nargs = [args1, args2, args3]\nseed_everything(seed=SEED)\n\ntest_dataset = HotelImageDataset(test_df, base_transform, data_folder=TEST_DATA_FOLDER)\n\ntest_loader = []\nfor arg in args:\n    test_loader.append(DataLoader(test_dataset, num_workers=arg.num_workers, batch_size=arg.batch_size, shuffle=False))\n","metadata":{"executionInfo":{"elapsed":450,"status":"ok","timestamp":1619311064188,"user":{"displayName":"Jeom Jin-Ho","photoUrl":"","userId":"00155613517919499503"},"user_tz":-120},"id":"appointed-machinery","papermill":{"duration":0.069839,"end_time":"2022-03-24T14:01:02.65177","exception":false,"start_time":"2022-03-24T14:01:02.581931","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:19.373283Z","iopub.execute_input":"2022-05-30T23:33:19.373801Z","iopub.status.idle":"2022-05-30T23:33:19.385342Z","shell.execute_reply.started":"2022-05-30T23:33:19.373763Z","shell.execute_reply":"2022-05-30T23:33:19.384428Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#base_embeddings_df = pd.read_pickle('../input/hotel-id-starter-similarity-training/embedding-model-efficientnet_b0-256x256_image-embeddings.pkl')\n#backbone_names = [\"efficientnet_b0\", \"efficientnet_b3\", \"tf_efficientnet_b5\"]\nbackbone_names = [\"efficientnet_b3\", \"tf_efficientnetv2_b3\", \"resnet50\"]\nbase_embeddings_df = []\nfor name in backbone_names:\n    base_embeddings_df.append(pd.read_pickle(f'../input/final2/embedding-model-{name}-256x256_image-embeddings.pkl'))\n    \ndisplay(base_embeddings_df[0].head())","metadata":{"execution":{"iopub.status.busy":"2022-05-30T23:33:19.418375Z","iopub.execute_input":"2022-05-30T23:33:19.419307Z","iopub.status.idle":"2022-05-30T23:33:19.909777Z","shell.execute_reply.started":"2022-05-30T23:33:19.419264Z","shell.execute_reply":"2022-05-30T23:33:19.908991Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = []\n\nfor arg, base, name in zip(args, base_embeddings_df, backbone_names):\n    arg.n_classes = base[\"hotel_id\"].nunique()\n\n    #model = get_model(\"efficientnet_b0\",\n    #                  \"../input/hotel-id-starter-similarity-training/checkpoint-embedding-model-efficientnet_b0-256x256.pt\", \n    #                  args)\n\n    model.append(get_model(name,\n                      f\"../input/final2/checkpoint-embedding-model-{name}-256x256.pt\",\n                      arg))","metadata":{"papermill":{"duration":5.553999,"end_time":"2022-03-24T14:01:08.229948","exception":false,"start_time":"2022-03-24T14:01:02.675949","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:19.911684Z","iopub.execute_input":"2022-05-30T23:33:19.912533Z","iopub.status.idle":"2022-05-30T23:33:21.993197Z","shell.execute_reply.started":"2022-05-30T23:33:19.91249Z","shell.execute_reply":"2022-05-30T23:33:21.992416Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission","metadata":{"papermill":{"duration":0.024227,"end_time":"2022-03-24T14:01:08.278753","exception":false,"start_time":"2022-03-24T14:01:08.254526","status":"completed"},"tags":[]}},{"cell_type":"code","source":"%%time\n\npreds = predict(args, base_embeddings_df, test_loader, model)\n#preds = predict(args[0], base_embeddings_df[0], test_loader[0], model[0])\n\n# transform array of hotel_ids into string\ntest_df[\"hotel_id\"] = [str(list(l)).strip(\"[]\").replace(\",\", \"\") for l in preds]\ntest_df.to_csv(\"submission.csv\", index=False)\ntest_df.head()","metadata":{"papermill":{"duration":0.047156,"end_time":"2022-03-24T14:01:08.414557","exception":false,"start_time":"2022-03-24T14:01:08.367401","status":"completed"},"tags":[],"execution":{"iopub.status.busy":"2022-05-30T23:33:21.995446Z","iopub.execute_input":"2022-05-30T23:33:21.995858Z","iopub.status.idle":"2022-05-30T23:33:24.433375Z","shell.execute_reply.started":"2022-05-30T23:33:21.995818Z","shell.execute_reply":"2022-05-30T23:33:24.432558Z"},"trusted":true},"execution_count":null,"outputs":[]}]}