{"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":"## About\n\nThis notebook is a fork of https://www.kaggle.com/hidehisaarai1213/glret21-efficientnetb0-baseline-inference , please upvote the work of @hidehisaarai1213 first","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"code","source":"!pip install ../input/kerasapplications/ > /dev/null\n!pip install ../input/efficientnet-keras-source-code/ > /dev/null","metadata":{"execution":{"iopub.status.busy":"2023-09-25T11:09:45.263633Z","iopub.execute_input":"2023-09-25T11:09:45.264000Z","iopub.status.idle":"2023-09-25T11:10:45.096764Z","shell.execute_reply.started":"2023-09-25T11:09:45.263892Z","shell.execute_reply":"2023-09-25T11:10:45.095709Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import gc\nimport os\nimport math\nimport random\nimport re\nimport warnings\nfrom pathlib import Path\nfrom PIL import Image\nfrom typing import Optional, Tuple\n\nimport efficientnet.tfkeras as efn\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nfrom scipy import spatial\nfrom sklearn.preprocessing import normalize\nfrom tqdm import tqdm\nprint(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2023-09-25T11:10:45.100808Z","iopub.execute_input":"2023-09-25T11:10:45.101137Z","iopub.status.idle":"2023-09-25T11:10:51.139596Z","shell.execute_reply.started":"2023-09-25T11:10:45.101104Z","shell.execute_reply":"2023-09-25T11:10:51.138573Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Settings","metadata":{}},{"cell_type":"code","source":"DATADIR = Path(\"../input/landmark-retrieval-2021/\")\nTEST_IMAGE_DIR = DATADIR / \"test\"\nTRAIN_IMAGE_DIR = DATADIR / \"index\"\n\nDATADIR = Path(\"/kaggle/input/data-matching-dpr/matching dataset/\")\nTEST_IMAGE_DIR = DATADIR / \"Input_images\"\nTRAIN_IMAGE_DIR = DATADIR / \"Segmented_images\"\n\nTOPK = 100\nN_CLASSES = 81313","metadata":{"execution":{"iopub.status.busy":"2023-09-25T11:43:50.595773Z","iopub.execute_input":"2023-09-25T11:43:50.596167Z","iopub.status.idle":"2023-09-25T11:43:50.601728Z","shell.execute_reply.started":"2023-09-25T11:43:50.596132Z","shell.execute_reply":"2023-09-25T11:43:50.600373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Utilities","metadata":{}},{"cell_type":"code","source":"import time\n\nfrom contextlib import contextmanager\n\n\n@contextmanager\ndef timer(name):\n    t0 = time.time()\n    print(f\"[{name}]\")\n    yield\n    print(f'[{name}] done in {time.time() - t0:.0f} s')","metadata":{"execution":{"iopub.status.busy":"2023-09-25T11:43:50.985503Z","iopub.execute_input":"2023-09-25T11:43:50.985819Z","iopub.status.idle":"2023-09-25T11:43:50.991069Z","shell.execute_reply.started":"2023-09-25T11:43:50.985787Z","shell.execute_reply":"2023-09-25T11:43:50.990021Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def set_seed(seed=42):\n    random.seed(seed)\n    os.environ[\"PYTHONHASHSEED\"] = str(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n\n\nset_seed(1213)","metadata":{"execution":{"iopub.status.busy":"2023-09-25T11:43:51.166408Z","iopub.execute_input":"2023-09-25T11:43:51.166781Z","iopub.status.idle":"2023-09-25T11:43:51.179201Z","shell.execute_reply.started":"2023-09-25T11:43:51.166741Z","shell.execute_reply":"2023-09-25T11:43:51.178093Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def auto_select_accelerator():\n    try:\n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        tf.config.experimental_connect_to_cluster(tpu)\n        tf.tpu.experimental.initialize_tpu_system(tpu)\n        strategy = tf.distribute.experimental.TPUStrategy(tpu)\n        print(\"Running on TPU:\", tpu.master())\n    except ValueError:\n        strategy = tf.distribute.get_strategy()\n    print(f\"Running on {strategy.num_replicas_in_sync} replicas\")\n    return strategy","metadata":{"execution":{"iopub.status.busy":"2023-09-25T11:43:51.356081Z","iopub.execute_input":"2023-09-25T11:43:51.356415Z","iopub.status.idle":"2023-09-25T11:43:51.363146Z","shell.execute_reply.started":"2023-09-25T11:43:51.356385Z","shell.execute_reply":"2023-09-25T11:43:51.362069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"strategy = auto_select_accelerator()\nREPLICAS = strategy.num_replicas_in_sync\nAUTO = tf.data.experimental.AUTOTUNE","metadata":{"execution":{"iopub.status.busy":"2023-09-25T11:43:51.567794Z","iopub.execute_input":"2023-09-25T11:43:51.568117Z","iopub.status.idle":"2023-09-25T11:43:51.573714Z","shell.execute_reply.started":"2023-09-25T11:43:51.568087Z","shell.execute_reply":"2023-09-25T11:43:51.572818Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Model","metadata":{}},{"cell_type":"code","source":"class GeM(tf.keras.layers.Layer):\n    def __init__(self, pool_size, init_norm=3.0, normalize=False, **kwargs):\n        self.pool_size = pool_size\n        self.init_norm = init_norm\n        self.normalize = normalize\n\n        super(GeM, self).__init__(**kwargs)\n\n    def get_config(self):\n        config = super().get_config().copy()\n        config.update({\n            'pool_size': self.pool_size,\n            'init_norm': self.init_norm,\n            'normalize': self.normalize,\n        })\n        return config\n\n    def build(self, input_shape):\n        feature_size = input_shape[-1]\n        self.p = self.add_weight(name='norms', shape=(feature_size,),\n                                 initializer=tf.keras.initializers.constant(self.init_norm),\n                                 trainable=True)\n        super(GeM, self).build(input_shape)\n\n    def call(self, inputs):\n        x = inputs\n        x = tf.math.maximum(x, 1e-6)\n        x = tf.pow(x, self.p)\n\n        x = tf.nn.avg_pool(x, self.pool_size, self.pool_size, 'VALID')\n        x = tf.pow(x, 1.0 / self.p)\n\n        if self.normalize:\n            x = tf.nn.l2_normalize(x, 1)\n        return x\n\n    def compute_output_shape(self, input_shape):\n        return tuple([None, input_shape[-1]])","metadata":{"execution":{"iopub.status.busy":"2023-09-25T11:43:52.104595Z","iopub.execute_input":"2023-09-25T11:43:52.104924Z","iopub.status.idle":"2023-09-25T11:43:52.116139Z","shell.execute_reply.started":"2023-09-25T11:43:52.104891Z","shell.execute_reply":"2023-09-25T11:43:52.115195Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class ArcMarginProduct(tf.keras.layers.Layer):\n    '''\n    Implements large margin arc distance.\n\n    Reference:\n        https://arxiv.org/pdf/1801.07698.pdf\n        https://github.com/lyakaap/Landmark2019-1st-and-3rd-Place-Solution/\n            blob/master/src/modeling/metric_learning.py\n    '''\n    def __init__(self, n_classes, s=30, m=0.50, easy_margin=False,\n                 ls_eps=0.0, **kwargs):\n\n        super(ArcMarginProduct, self).__init__(**kwargs)\n\n        self.n_classes = n_classes\n        self.s = s\n        self.m = m\n        self.ls_eps = ls_eps\n        self.easy_margin = easy_margin\n        self.cos_m = tf.math.cos(m)\n        self.sin_m = tf.math.sin(m)\n        self.th = tf.math.cos(math.pi - m)\n        self.mm = tf.math.sin(math.pi - m) * m\n\n    def get_config(self):\n\n        config = super().get_config().copy()\n        config.update({\n            'n_classes': self.n_classes,\n            's': self.s,\n            'm': self.m,\n            'ls_eps': self.ls_eps,\n            'easy_margin': self.easy_margin,\n        })\n        return config\n\n    def build(self, input_shape):\n        super(ArcMarginProduct, self).build(input_shape[0])\n\n        self.W = self.add_weight(\n            name='W',\n            shape=(int(input_shape[0][-1]), self.n_classes),\n            initializer='glorot_uniform',\n            dtype='float32',\n            trainable=True,\n            regularizer=None)\n\n    def call(self, inputs):\n        X, y = inputs\n        y = tf.cast(y, dtype=tf.int32)\n        cosine = tf.matmul(\n            tf.math.l2_normalize(X, axis=1),\n            tf.math.l2_normalize(self.W, axis=0)\n        )\n        sine = tf.math.sqrt(1.0 - tf.math.pow(cosine, 2))\n        phi = cosine * self.cos_m - sine * self.sin_m\n        if self.easy_margin:\n            phi = tf.where(cosine > 0, phi, cosine)\n        else:\n            phi = tf.where(cosine > self.th, phi, cosine - self.mm)\n        one_hot = tf.cast(\n            tf.one_hot(y, depth=self.n_classes),\n            dtype=cosine.dtype\n        )\n        if self.ls_eps > 0:\n            one_hot = (1 - self.ls_eps) * one_hot + self.ls_eps / self.n_classes\n\n        output = (one_hot * phi) + ((1.0 - one_hot) * cosine)\n        output *= self.s\n        return output","metadata":{"execution":{"iopub.status.busy":"2023-09-25T11:43:52.519791Z","iopub.execute_input":"2023-09-25T11:43:52.520148Z","iopub.status.idle":"2023-09-25T11:43:52.537239Z","shell.execute_reply.started":"2023-09-25T11:43:52.520116Z","shell.execute_reply":"2023-09-25T11:43:52.536174Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def build_model(size=256, efficientnet_size=0, weights=\"imagenet\", count=0):\n    inp = tf.keras.layers.Input(shape=(size, size, 3), name=\"inp1\")\n    label = tf.keras.layers.Input(shape=(), name=\"inp2\")\n    x = getattr(efn, f\"EfficientNetB{efficientnet_size}\")(\n        weights=weights, include_top=False, input_shape=(size, size, 3))(inp)\n    x = GeM(8)(x)\n    x = tf.keras.layers.Flatten()(x)\n    x = tf.keras.layers.Dense(512, name=\"dense_before_arcface\", kernel_initializer=\"he_normal\")(x)\n    x = tf.keras.layers.BatchNormalization()(x)\n    x = ArcMarginProduct(\n        n_classes=N_CLASSES,\n        s=30,\n        m=0.5,\n        name=\"head/arc_margin\",\n        dtype=\"float32\"\n    )([x, label])\n    output = tf.keras.layers.Softmax(dtype=\"float32\")(x)\n    model = tf.keras.Model(inputs=[inp, label], outputs=[output])\n    opt = tf.optimizers.Adam(learning_rate=1e-4)\n    model.compile(\n        optimizer=opt,\n        loss=[tf.keras.losses.SparseCategoricalCrossentropy()],\n        metrics=[tf.keras.metrics.SparseCategoricalAccuracy()]\n    )\n    return model","metadata":{"execution":{"iopub.status.busy":"2023-09-25T11:43:52.846370Z","iopub.execute_input":"2023-09-25T11:43:52.846678Z","iopub.status.idle":"2023-09-25T11:43:52.856671Z","shell.execute_reply.started":"2023-09-25T11:43:52.846649Z","shell.execute_reply":"2023-09-25T11:43:52.855537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_model_for_inference(weights_path: str):\n    with strategy.scope():\n        base_model = build_model(\n            size=256,\n            efficientnet_size=5,\n            weights='imagenet',\n            count=0)\n        model = tf.keras.Model(inputs=base_model.get_layer(\"inp1\").input,\n                               outputs=base_model.get_layer(\"dense_before_arcface\").output)\n        return model","metadata":{"execution":{"iopub.status.busy":"2023-09-25T11:43:53.446322Z","iopub.execute_input":"2023-09-25T11:43:53.446720Z","iopub.status.idle":"2023-09-25T11:43:53.452360Z","shell.execute_reply.started":"2023-09-25T11:43:53.446679Z","shell.execute_reply":"2023-09-25T11:43:53.451427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Feature Extraction","metadata":{}},{"cell_type":"code","source":"def to_hex(image_id) -> str:\n    return '{0:0{1}x}'.format(image_id, 16)\n\n\ndef get_image_path(subset, image_id):\n    name = to_hex(image_id)\n    return os.path.join(DATASET_DIR, subset, name[0], name[1], name[2], '{}.jpg'.format(name))\n\n\ndef load_image_tensor(image_path):\n    tensor = tf.convert_to_tensor(np.array(Image.open(image_path).convert(\"RGB\")))\n    tensor = tf.image.resize(tensor, size=(256, 256))\n    tensor = tf.expand_dims(tensor, axis=0)\n    return tf.cast(tensor, tf.float32) / 255.0\n\n\ndef create_batch(files):\n    images = []\n    for f in files:\n        images.append(load_image_tensor(f))\n    return tf.concat(images, axis=0)","metadata":{"execution":{"iopub.status.busy":"2023-09-25T11:43:54.370071Z","iopub.execute_input":"2023-09-25T11:43:54.370416Z","iopub.status.idle":"2023-09-25T11:43:54.378408Z","shell.execute_reply.started":"2023-09-25T11:43:54.370385Z","shell.execute_reply":"2023-09-25T11:43:54.377402Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def extract_global_features(image_root_dir, n_models=4):\n    image_paths = []\n    for root, dirs, files in os.walk(image_root_dir):\n        for file in files:\n            image_paths.append(os.path.join(root, file))\n                    \n    num_embeddings = len(image_paths)\n\n    ids = num_embeddings * [None]\n    ids = []\n    for path in image_paths:\n        ids.append(path.split('/')[-1][:-4])\n    \n    embeddings = np.zeros((num_embeddings, 512))\n    image_paths = np.array(image_paths)\n    chunk_size = 512\n    \n    n_chunks = len(image_paths) // chunk_size\n    if len(image_paths) % chunk_size != 0:\n        n_chunks += 1\n\n    for n in range(n_models):\n        print(f\"Getting Embedding for fold{n} model.\")\n        model = create_model_for_inference(f\"../input/landmark-models/fold{n}.h5\")\n        for i in tqdm(range(n_chunks)):\n            files = image_paths[i * chunk_size:(i + 1) * chunk_size]\n            batch = create_batch(files)\n            embedding_tensor = model.predict(batch)\n            embeddings[i * chunk_size:(i + 1) * chunk_size] += embedding_tensor / n_models\n        del model\n        gc.collect()\n        tf.keras.backend.clear_session()\n\n    embeddings = normalize(embeddings, axis=1)\n\n    return ids, embeddings","metadata":{"execution":{"iopub.status.busy":"2023-09-25T11:43:54.856579Z","iopub.execute_input":"2023-09-25T11:43:54.856904Z","iopub.status.idle":"2023-09-25T11:43:54.867520Z","shell.execute_reply.started":"2023-09-25T11:43:54.856871Z","shell.execute_reply":"2023-09-25T11:43:54.866500Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Main","metadata":{}},{"cell_type":"code","source":"def get_predictions():\n    with timer(\"Getting Test Embeddings\"):\n        test_ids, test_embeddings  = extract_global_features(str(TEST_IMAGE_DIR))\n\n    with timer(\"Getting Train Embeddings\"):\n        train_ids, train_embeddings = extract_global_features(str(TRAIN_IMAGE_DIR))\n\n    PredictionString_list = []\n    with timer(\"Matching...\"):\n        for test_index in range(test_embeddings.shape[0]):\n            distances = spatial.distance.cdist(test_embeddings[np.newaxis, test_index, :], train_embeddings, 'cosine')[0]\n            TOPK = min(distances.size, 3)  # Set TOPK to a value less than or equal to 4\n            partition = np.argpartition(distances, TOPK)[:TOPK]\n            nearest = sorted([(train_ids[p], distances[p]) for p in partition], key=lambda x: x[1])\n            pred_str = \"\"\n            for train_id, cosine_distance in nearest:\n                pred_str += train_id\n                pred_str += \" \"\n            PredictionString_list.append(pred_str)\n\n    return test_ids, PredictionString_list\n\n\ndef main():\n    test_image_list = []\n    for root, dirs, files in os.walk(str(TEST_IMAGE_DIR)):\n        for file in files:\n            test_image_list.append(os.path.join(root, file))\n                    \n    \n    test_ids, PredictionString_list = get_predictions()\n    sub_df = pd.DataFrame(data={'id': test_ids, 'images': PredictionString_list})\n    print(sub_df)","metadata":{"execution":{"iopub.status.busy":"2023-09-25T12:08:02.267065Z","iopub.execute_input":"2023-09-25T12:08:02.267425Z","iopub.status.idle":"2023-09-25T12:08:02.280921Z","shell.execute_reply.started":"2023-09-25T12:08:02.267389Z","shell.execute_reply":"2023-09-25T12:08:02.279998Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"main()","metadata":{"execution":{"iopub.status.busy":"2023-09-25T12:08:02.528780Z","iopub.execute_input":"2023-09-25T12:08:02.529168Z","iopub.status.idle":"2023-09-25T12:09:14.172263Z","shell.execute_reply.started":"2023-09-25T12:08:02.529132Z","shell.execute_reply":"2023-09-25T12:09:14.171314Z"},"trusted":true},"execution_count":null,"outputs":[]}]}