{"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 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\n\n#import efficientnet.tfkeras as efn\nimport numpy as np\nimport pandas as pd\nimport tensorflow as tf\nimport tensorflow_hub as hub\nfrom scipy import spatial\nfrom sklearn.preprocessing import normalize\nfrom tqdm import tqdm","metadata":{"execution":{"iopub.status.busy":"2021-10-01T21:56:30.037038Z","iopub.execute_input":"2021-10-01T21:56:30.037679Z","iopub.status.idle":"2021-10-01T21:56:31.886611Z","shell.execute_reply.started":"2021-10-01T21:56:30.037579Z","shell.execute_reply":"2021-10-01T21:56:31.885679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"tf.__version__","metadata":{"execution":{"iopub.status.busy":"2021-10-01T21:56:31.888831Z","iopub.execute_input":"2021-10-01T21:56:31.889192Z","iopub.status.idle":"2021-10-01T21:56:31.896924Z","shell.execute_reply.started":"2021-10-01T21:56:31.889155Z","shell.execute_reply":"2021-10-01T21:56:31.896131Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Num GPUs Available: \", len(tf.config.experimental.list_physical_devices('GPU')))","metadata":{"execution":{"iopub.status.busy":"2021-10-01T21:56:31.89851Z","iopub.execute_input":"2021-10-01T21:56:31.899035Z","iopub.status.idle":"2021-10-01T21:56:31.946869Z","shell.execute_reply.started":"2021-10-01T21:56:31.898998Z","shell.execute_reply":"2021-10-01T21:56:31.94603Z"},"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\nTOPK = 100\nN_CLASSES = 81313\nIMAGE_SIZE=420\nN_CHANNELS=3\nFOLDS=[0,1,2,3]\n#FOLDS=[0,1]\nN_FOLDS=4\nTEST=False","metadata":{"execution":{"iopub.status.busy":"2021-10-01T21:56:31.9485Z","iopub.execute_input":"2021-10-01T21:56:31.948962Z","iopub.status.idle":"2021-10-01T21:56:31.958562Z","shell.execute_reply.started":"2021-10-01T21:56:31.948921Z","shell.execute_reply":"2021-10-01T21:56:31.957718Z"},"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":"2021-10-01T21:56:31.961641Z","iopub.execute_input":"2021-10-01T21:56:31.962066Z","iopub.status.idle":"2021-10-01T21:56:31.968507Z","shell.execute_reply.started":"2021-10-01T21:56:31.962039Z","shell.execute_reply":"2021-10-01T21:56:31.96763Z"},"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":"2021-10-01T21:56:31.97064Z","iopub.execute_input":"2021-10-01T21:56:31.970881Z","iopub.status.idle":"2021-10-01T21:56:31.97728Z","shell.execute_reply.started":"2021-10-01T21:56:31.970858Z","shell.execute_reply":"2021-10-01T21:56:31.97601Z"},"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":"2021-10-01T21:56:31.978941Z","iopub.execute_input":"2021-10-01T21:56:31.979356Z","iopub.status.idle":"2021-10-01T21:56:31.986978Z","shell.execute_reply.started":"2021-10-01T21:56:31.979322Z","shell.execute_reply":"2021-10-01T21:56:31.985995Z"},"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":"2021-10-01T21:56:31.99024Z","iopub.execute_input":"2021-10-01T21:56:31.990682Z","iopub.status.idle":"2021-10-01T21:56:31.999155Z","shell.execute_reply.started":"2021-10-01T21:56:31.99065Z","shell.execute_reply":"2021-10-01T21:56:31.998223Z"},"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":"2021-10-01T21:56:32.000717Z","iopub.execute_input":"2021-10-01T21:56:32.000992Z","iopub.status.idle":"2021-10-01T21:56:32.011345Z","shell.execute_reply.started":"2021-10-01T21:56:32.000965Z","shell.execute_reply":"2021-10-01T21:56:32.010371Z"},"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":"2021-10-01T21:56:32.012837Z","iopub.execute_input":"2021-10-01T21:56:32.013309Z","iopub.status.idle":"2021-10-01T21:56:32.03009Z","shell.execute_reply.started":"2021-10-01T21:56:32.013153Z","shell.execute_reply":"2021-10-01T21:56:32.029187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"FOLDER_EFF_ORG0=\"../input/efficientnetv2-tfhub-weight-files/tfhub_models/efficientnetv2-m-21k-ft1k/classification\"\nFOLDER_EFF_ORG1=\"../input/efficientnetv2-tfhub-weight-files/tfhub_models/efficientnetv2-l-21k-ft1k/classification\"\ndef build_model(size=384, count=0,eff_org=FOLDER_EFF_ORG0):\n    inp = tf.keras.layers.Input(shape=(size, size, 3), name=\"inp1\")\n    label = tf.keras.layers.Input(shape=(), name=\"inp2\")\n    x=hub.KerasLayer(eff_org, trainable=True)(inp)\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(1000, 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":"2021-10-01T21:56:58.536519Z","iopub.execute_input":"2021-10-01T21:56:58.536989Z","iopub.status.idle":"2021-10-01T21:56:58.551843Z","shell.execute_reply.started":"2021-10-01T21:56:58.536946Z","shell.execute_reply":"2021-10-01T21:56:58.549979Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_model_for_inference(weights_path: str,flg_eo=0):\n    with strategy.scope():\n        if flg_eo>0:\n            base_model = build_model(\n                size=IMAGE_SIZE,\n                count=0,\n                eff_org=FOLDER_EFF_ORG1)\n        else:\n            base_model = build_model(\n                size=IMAGE_SIZE,\n                count=0,\n                eff_org=FOLDER_EFF_ORG0)            \n        base_model.load_weights(weights_path)\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":"2021-10-01T21:56:58.555998Z","iopub.execute_input":"2021-10-01T21:56:58.557654Z","iopub.status.idle":"2021-10-01T21:56:58.569323Z","shell.execute_reply.started":"2021-10-01T21:56:58.557578Z","shell.execute_reply":"2021-10-01T21:56:58.568414Z"},"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\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=(IMAGE_SIZE, IMAGE_SIZE))\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":"2021-10-01T21:56:58.57265Z","iopub.execute_input":"2021-10-01T21:56:58.573788Z","iopub.status.idle":"2021-10-01T21:56:58.584816Z","shell.execute_reply.started":"2021-10-01T21:56:58.573746Z","shell.execute_reply":"2021-10-01T21:56:58.583871Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def extract_global_features(image_root_dir):\n    n_models=N_FOLDS\n    image_paths = []\n    for root, dirs, files in os.walk(image_root_dir):\n        for file in files:\n            if file.endswith('.jpg'):\n                 image_paths.append(os.path.join(root, file))\n    if TEST:\n        image_paths=image_paths[:1000]\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((n_models,num_embeddings, 1000))\n    image_paths = np.array(image_paths)\n    #chunk_size = 512\n    chunk_size = 128\n    models=[create_model_for_inference(f\"../input/glr21-my-model/M420_fold{n}.h5\",n%2) for n in range(n_models)]\n    n_chunks = len(image_paths) // chunk_size\n    if len(image_paths) % chunk_size != 0:\n        n_chunks += 1\n\n    for i in tqdm(range(n_chunks)):\n        #print(f\"Getting Embedding for fold{n} model.\")\n        files = image_paths[i * chunk_size:(i + 1) * chunk_size]\n        batch = create_batch(files)\n        for n in range(n_models):\n            #model = create_model_for_inference(f\"../input/glr21-my-model/fold{n}.h5\")\n            embedding_tensor = models[n].predict(batch)\n            embeddings[n,i * chunk_size:(i + 1) * chunk_size] = embedding_tensor\n        #del model\n        gc.collect()\n    tf.keras.backend.clear_session()\n    for n in range(n_models):\n        embeddings[n] = normalize(embeddings[n], axis=1)\n\n    return ids, embeddings","metadata":{"execution":{"iopub.status.busy":"2021-10-01T21:56:58.586465Z","iopub.execute_input":"2021-10-01T21:56:58.587044Z","iopub.status.idle":"2021-10-01T21:56:58.602006Z","shell.execute_reply.started":"2021-10-01T21:56:58.587008Z","shell.execute_reply":"2021-10-01T21:56:58.601079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def extract_global_features_org(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            if file.endswith('.jpg'):\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    chunk_size = 128\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/glr21-my-model/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    embeddings = normalize(embeddings, axis=1)\n\n    return ids, embeddings","metadata":{"execution":{"iopub.status.busy":"2021-10-01T21:56:58.604071Z","iopub.execute_input":"2021-10-01T21:56:58.604609Z","iopub.status.idle":"2021-10-01T21:56:58.632191Z","shell.execute_reply.started":"2021-10-01T21:56:58.604574Z","shell.execute_reply":"2021-10-01T21:56:58.631185Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Main","metadata":{}},{"cell_type":"code","source":"def get_predictions():\n    n_models=N_FOLDS\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    \n    with timer(\"Matching...\"):\n        for test_index in range(test_embeddings.shape[1]):\n            distances=[]\n            for n in range(n_models):\n                if n==0:\n                    distances = spatial.distance.cdist(test_embeddings[n][np.newaxis, test_index, :], train_embeddings[n], 'cosine')[0]\n                else:\n                    p_distances = spatial.distance.cdist(test_embeddings[n][np.newaxis, test_index, :], train_embeddings[n], 'cosine')[0]\n                    distances +=p_distances\n            distances = distances / n_models\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\ndef get_predictions_org():\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            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            if file.endswith('.jpg'):\n                 test_image_list.append(os.path.join(root, file))\n                    \n    if (len(test_image_list)==1129) and not TEST:\n        sub_df = pd.read_csv('../input/landmark-retrieval-2021/sample_submission.csv')\n        sub_df.to_csv('submission.csv', index=False)\n        return\n    test_ids, PredictionString_list = get_predictions()\n    sub_df = pd.DataFrame(data={'id': test_ids, 'images': PredictionString_list})\n    sub_df.to_csv('submission.csv', index=False)","metadata":{"execution":{"iopub.status.busy":"2021-10-01T21:56:58.716707Z","iopub.execute_input":"2021-10-01T21:56:58.717058Z","iopub.status.idle":"2021-10-01T21:56:58.741383Z","shell.execute_reply.started":"2021-10-01T21:56:58.717023Z","shell.execute_reply":"2021-10-01T21:56:58.740428Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"main()","metadata":{"execution":{"iopub.status.busy":"2021-10-01T21:56:58.746085Z","iopub.execute_input":"2021-10-01T21:56:58.748639Z","iopub.status.idle":"2021-10-01T22:06:06.598788Z","shell.execute_reply.started":"2021-10-01T21:56:58.748602Z","shell.execute_reply":"2021-10-01T22:06:06.597794Z"},"trusted":true},"execution_count":null,"outputs":[]}]}