{"cells":[{"metadata":{},"cell_type":"markdown","source":"Reference: \n1. https://www.kaggle.com/azaemon/analysis-of-melanoma-metadata-and-effnet-ensemble#Machine-Learning-to-Neural-Networks\n2. https://www.kaggle.com/cdeotte/rotation-augmentation-gpu-tpu-0-96/comments\n3. https://www.kaggle.com/c/landmark-recognition-2020/discussion/172231","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import pandas as pd\nimport numpy as np\n\n#\n\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.gridspec as gridspec\n\n#\n\nimport seaborn as sns\nimport plotly.express as px\n\n#\n\nimport os\nimport random\nimport re\nimport math\nimport time\n\nfrom tqdm import tqdm\nfrom tqdm.keras import TqdmCallback\n\n\nfrom pandas_summary import DataFrameSummary\n\nimport warnings\n\n\nwarnings.filterwarnings('ignore') # Disabling warnings for clearer outputs\n\n\n\nseed_val = 42\nrandom.seed(seed_val)\nnp.random.seed(seed_val)\nimport tensorflow as tf\nimport tensorflow.keras.backend as K\nimport efficientnet.tfkeras as efn\nfrom kaggle_datasets import KaggleDatasets\n\ntf.random.set_seed(seed_val)","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"GCS_PATH1 = KaggleDatasets().get_gcs_path('landmarktfv31')\nGCS_PATH2 = KaggleDatasets().get_gcs_path('landmarktfv32')\nGCS_PATH3 = KaggleDatasets().get_gcs_path('landmarktfv33')\nGCS_PATH4 = KaggleDatasets().get_gcs_path('landmarktfrecordtest')\n\n\nfilenames_train1 = tf.io.gfile.glob(GCS_PATH1 + '/*.tfrec')\nfilenames_train2 = tf.io.gfile.glob(GCS_PATH2 + '/*.tfrec')\nfilenames_train3 = tf.io.gfile.glob(GCS_PATH3 + '/*.tfrec')\n\nfilenames_test = np.array(tf.io.gfile.glob(GCS_PATH4 + '/*.tfrec'))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#filenames_validation= np.array(tf.io.gfile.glob(GCS_PATH1 + '/*.tfrec'))\nfilenames_train=  np.array(filenames_train1 + filenames_train2 + filenames_train3)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"raw_dataset = tf.data.TFRecordDataset(filenames_train)\nfor raw_record in raw_dataset.take(1):\n  example = tf.train.Example()\n  example.ParseFromString(raw_record.numpy())\n  #li= raw_record.numpy()\n  print(example)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cfg = dict(\n           batch_size=16,\n           img_size=256,\n    \n           lr_start=0.000005,\n           lr_max=0.00000125,\n           lr_min=0.000001,\n           lr_rampup=5,\n           lr_sustain=0,\n           lr_decay=0.8,\n           epochs=18,\n    \n           transform_prob=1.0,\n           rot=180.0,\n           shr=2.0,\n           hzoom=8.0,\n           wzoom=8.0,\n           hshift=8.0,\n           wshift=8.0,\n    \n           optimizer='adam',\n           label_smooth_fac=0.05,\n           tta_steps=20\n            \n        )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"DEVICE = 'TPU'\nif DEVICE == 'TPU':\n    print('connecting to TPU...')\n    try:        \n        tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n        print('Running on TPU ', tpu.master())\n    except ValueError:\n        print('Could not connect to TPU')\n        tpu = None\n\n    if tpu:\n        try:\n            print('Initializing  TPU...')\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('TPU initialized')\n        except _:\n            print('Failed to initialize TPU!')\n    else:\n        DEVICE = 'GPU'\n\nif DEVICE != 'TPU':\n    print('Using default strategy for CPU and single GPU')\n    strategy = tf.distribute.get_strategy()\n\nif DEVICE == 'GPU':\n    print('Num GPUs Available: ',\n          len(tf.config.experimental.list_physical_devices('GPU')))\n\nprint('REPLICAS: ', strategy.num_replicas_in_sync)\nAUTO = tf.data.experimental.AUTOTUNE","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_SIZE = [256, 256] # At this size, a GPU will run out of memory. Use the TPU.\n                        # For GPU training, please select 224 x 224 px image size.\nEPOCHS = 12\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**VISUALIZATION**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"# numpy and matplotlib defaults\nnp.set_printoptions(threshold=15, linewidth=80)\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    # If no labels, only image IDs, return None for labels (this is the case for test data)\n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return CLASSES[label], True\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower(image, title, subplot, red=False, titlesize=16):\n    plt.subplot(*subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    if len(title) > 0:\n        plt.title(title, fontsize=int(titlesize) if not red else int(titlesize/1.2), color='red' if red else 'black', fontdict={'verticalalignment':'center'}, pad=int(titlesize/1.5))\n    return (subplot[0], subplot[1], subplot[2]+1)\n    \ndef display_batch_of_images(databatch, predictions=None):\n    \"\"\"This will work with:\n    display_batch_of_images(images)\n    display_batch_of_images(images, predictions)\n    display_batch_of_images((images, labels))\n    display_batch_of_images((images, labels), predictions)\n    \"\"\"\n    # data\n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n        \n    # auto-squaring: this will drop data that does not fit into square or square-ish rectangle\n    rows = int(math.sqrt(len(images)))\n    cols = len(images)//rows\n        \n    # size and spacing\n    FIGSIZE = 13.0\n    SPACING = 0.1\n    subplot=(rows,cols,1)\n    if rows < cols:\n        plt.figure(figsize=(FIGSIZE,FIGSIZE/cols*rows))\n    else:\n        plt.figure(figsize=(FIGSIZE/rows*cols,FIGSIZE))\n    \n    # display\n    for i, (image, label) in enumerate(zip(images[:rows*cols], labels[:rows*cols])):\n        #title = '' if label is None else CLASSES[label]\n        title='Landmark'\n        correct = True\n        if predictions is not None:\n            title, correct = title_from_label_and_target(predictions[i], label)\n        dynamic_titlesize = FIGSIZE*SPACING/max(rows,cols)*40+3 # magic formula tested to work from 1x1 to 10x10 images\n        subplot = display_one_flower(image, title, subplot, not correct, titlesize=dynamic_titlesize)\n    \n    #layout\n    plt.tight_layout()\n    if label is None and predictions is None:\n        plt.subplots_adjust(wspace=0, hspace=0)\n    else:\n        plt.subplots_adjust(wspace=SPACING, hspace=SPACING)\n    plt.show()\n\ndef display_confusion_matrix(cmat, score, precision, recall):\n    plt.figure(figsize=(15,15))\n    ax = plt.gca()\n    ax.matshow(cmat, cmap='Reds')\n    ax.set_xticks(range(len(CLASSES)))\n    ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"left\", rotation_mode=\"anchor\")\n    ax.set_yticks(range(len(CLASSES)))\n    ax.set_yticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_yticklabels(), rotation=45, ha=\"right\", rotation_mode=\"anchor\")\n    titlestring = \"\"\n    if score is not None:\n        titlestring += 'f1 = {:.3f} '.format(score)\n    if precision is not None:\n        titlestring += '\\nprecision = {:.3f} '.format(precision)\n    if recall is not None:\n        titlestring += '\\nrecall = {:.3f} '.format(recall)\n    if len(titlestring) > 0:\n        ax.text(101, 1, titlestring, fontdict={'fontsize': 18, 'horizontalalignment':'right', 'verticalalignment':'top', 'color':'#804040'})\n    plt.show()\n    \ndef display_training_curves(training, validation, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**DATA AUGMENTATION**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_mat(rotation, shear, height_zoom, width_zoom, height_shift,\n            width_shift):\n    \n    ''' Settings for image preparations '''\n\n    # CONVERT DEGREES TO RADIANS\n    rotation = math.pi * rotation / 180.\n    shear = math.pi * shear / 180.\n\n    # ROTATION MATRIX\n    c1 = tf.math.cos(rotation)\n    s1 = tf.math.sin(rotation)\n    one = tf.constant([1], dtype='float32')\n    zero = tf.constant([0], dtype='float32')\n    rotation_matrix = tf.reshape(\n        tf.concat([c1, s1, zero, -s1, c1, zero, zero, zero, one], axis=0),\n        [3, 3])\n\n    # SHEAR MATRIX\n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)\n    shear_matrix = tf.reshape(\n        tf.concat([one, s2, zero, zero, c2, zero, zero, zero, one], axis=0),\n        [3, 3])\n\n    # ZOOM MATRIX\n    zoom_matrix = tf.reshape(\n        tf.concat([\n            one / height_zoom, zero, zero, zero, one / width_zoom, zero, zero,\n            zero, one\n        ],\n                  axis=0), [3, 3])\n\n    # SHIFT MATRIX\n    shift_matrix = tf.reshape(\n        tf.concat(\n            [one, zero, height_shift, zero, one, width_shift, zero, zero, one],\n            axis=0), [3, 3])\n\n    return K.dot(K.dot(rotation_matrix, shear_matrix),\n                 K.dot(zoom_matrix, shift_matrix))\n\n\ndef transform(image, cfg):\n    \n    ''' This function takes input images of [: , :, 3] sizes and returns them as randomly rotated, sheared, shifted and zoomed. '''\n\n    DIM = cfg['img_size']\n    XDIM = DIM % 2  # fix for size 331\n\n    rot = cfg['rot'] * tf.random.normal([1], dtype='float32')\n    shr = cfg['shr'] * tf.random.normal([1], dtype='float32')\n    h_zoom = 1.0 + tf.random.normal([1], dtype='float32') / cfg['hzoom']\n    w_zoom = 1.0 + tf.random.normal([1], dtype='float32') / cfg['wzoom']\n    h_shift = cfg['hshift'] * tf.random.normal([1], dtype='float32')\n    w_shift = cfg['wshift'] * tf.random.normal([1], dtype='float32')\n\n    # GET TRANSFORMATION MATRIX\n    m = get_mat(rot, shr, h_zoom, w_zoom, h_shift, w_shift)\n\n    # LIST DESTINATION PIXEL INDICES\n    x = tf.repeat(tf.range(DIM // 2, -DIM // 2, -1), DIM)\n    y = tf.tile(tf.range(-DIM // 2, DIM // 2), [DIM])\n    z = tf.ones([DIM * DIM], dtype='int32')\n    idx = tf.stack([x, y, z])\n\n    # ROTATE DESTINATION PIXELS ONTO ORIGIN PIXELS\n    idx2 = K.dot(m, tf.cast(idx, dtype='float32'))\n    idx2 = K.cast(idx2, dtype='int32')\n    idx2 = K.clip(idx2, -DIM // 2 + XDIM + 1, DIM // 2)\n\n    # FIND ORIGIN PIXEL VALUES\n    idx3 = tf.stack([DIM // 2 - idx2[0, ], DIM // 2 - 1 + idx2[1, ]])\n    d = tf.gather_nd(image, tf.transpose(idx3))\n\n    return tf.reshape(d, [DIM, DIM, 3])\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**DATASET**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_f_data():\n    dataset = load_dataset(filenames_train, labeled=True)\n    #print(dataset)\n\n    dataset = dataset.shuffle(2048)\n    \n    return dataset\n\ndef get_t_data(dataset):\n    DATASET_SIZE= count_data_items(filenames_train)\n    print(\"Dataset Size: \",DATASET_SIZE)\n    train_size = int(0.8 * DATASET_SIZE)\n    train_dataset = dataset.take(train_size)\n    train_dataset = train_dataset.map(data_augment, num_parallel_calls=AUTO)\n\n    train_dataset = train_dataset.repeat()\n    train_dataset = train_dataset.batch(BATCH_SIZE)\n    train_dataset = train_dataset.prefetch(AUTO)\n    \n    return train_dataset\n\ndef get_v_data(dataset):\n    DATASET_SIZE= count_data_items(filenames_train)\n    train_size = int(0.8 * DATASET_SIZE)\n    val_size = int(0.20 * DATASET_SIZE)\n    valid_dataset = dataset.skip(train_size)\n    valid_dataset = valid_dataset.take(val_size)\n    \n    \n    #valid_dataset = valid_dataset.repeat()\n    valid_dataset = valid_dataset.batch(BATCH_SIZE)\n    valid_dataset = valid_dataset.prefetch(AUTO)\n    \n    return valid_dataset\n    \n    ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # convert image to floats in [0, 1] range\n    image = tf.reshape(image, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"landmark_id\": tf.io.FixedLenFeature([890], tf.float32 ),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['landmark_id'], tf.float32)\n    #print(label)\n    #l= K.argmax(label)\n    #print(label,l)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    if labeled:   \n        dataset = dataset.map(read_labeled_tfrecord, num_parallel_calls=AUTO)\n    else:\n        dataset = dataset.map(lambda example: read_unlabeled_tfrecord(example), num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef data_augment(img, label):\n    # data augmentation. Thanks to the dataset.prefetch(AUTO) statement in the next function (below),\n    # this happens essentially for free on TPU. Data pipeline code is executed on the \"CPU\" part\n    # of the TPU while the TPU itself is computing gradients.\n    #image = tf.image.random_flip_left_right(image)\n    #img = tf.cast(img, tf.float32) / 255.0\n    img = transform(img, cfg)\n\n    img = tf.image.random_flip_left_right(img)\n    img = tf.image.random_saturation(img, 0.7, 1.3)\n    img = tf.image.random_contrast(img, 0.8, 1.2)\n    img = tf.image.random_brightness(img, 0.1)\n    \n    return img, label   \n\ndef get_test_dataset(ordered=True):\n    dataset = load_dataset(filenames_test, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\n\"\"\"\n\ndef get_training_dataset():\n    dataset = load_dataset(filenames_train, labeled=True)\n    #print(dataset)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    #dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    \n    #i=1\n    #for e in dataset:\n    #    print(i)\n    #    i=i+1\n    \n    DATASET_SIZE= count_data_items(filenames_train)\n    train_size = int(0.8 * DATASET_SIZE)\n    val_size = int(0.20 * DATASET_SIZE)\n    train_dataset = dataset.take(train_size)\n    train_dataset = train_dataset.repeat()\n    valid_dataset = dataset.skip(train_size)\n    valid_dataset = valid_dataset.take(val_size)\n    \n    train_dataset = train_dataset.batch(BATCH_SIZE)\n    train_dataset = train_dataset.prefetch(AUTO)\n    valid_dataset = valid_dataset.batch(BATCH_SIZE)\n    valid_dataset = valid_dataset.cache()\n    valid_dataset = valid_dataset.prefetch(AUTO)\n    \n    #dataset = dataset.batch(BATCH_SIZE)\n    #dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return train_dataset,valid_dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(filenames_validation, labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\n\nNUM_TRAINING_IMAGES =  int(0.8 * count_data_items(filenames_train))\n#NUM_VALIDATION_IMAGES = count_data_items(filenames_validation)\nNUM_TEST_IMAGES = count_data_items(filenames_test)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_TEST_IMAGES))\n\n\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# data dump\ndataset= get_f_data()\n#NUM_TRAINING_IMAGES =  count_data_items(filenames_train)\n#print(\"Dataset: \", NUM_TRAINING_IMAGES)\n\nprint(\"Training data shapes:\")\ntraining_dataset = get_t_data(dataset)\nfor image, label in training_dataset.take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())\n\nvalidation_dataset= get_t_data(dataset)\nprint(\"Validation data shapes:\")\nfor image, label in validation_dataset.take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Validation data label examples:\", label.numpy())\n\nprint(\"Test data shapes:\")\nfor image in get_test_dataset().take(3):\n    print(image.numpy().shape)\n#print(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Peek at training data\n#training_dataset = get_training_dataset()\ntraining_dataset = training_dataset.unbatch().batch(20)\nprint(training_dataset)\ntrain_batch = iter(training_dataset)\nprint(train_batch)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# run this cell again for next set of images\ndisplay_batch_of_images(next(train_batch))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# peer at test data\ntest_dataset = get_test_dataset()\ntest_dataset = test_dataset.unbatch().batch(20)\ntest_batch = iter(test_dataset)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true,"_kg_hide-output":true},"cell_type":"code","source":"# run this cell again for next set of images\ndisplay_batch_of_images(next(test_batch))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def getLearnRateCallback(cfg):\n    \n    ''' Using callbacks for learning rate adjustments. '''\n    \n    lr_start = cfg['lr_start']\n    lr_max = cfg['lr_max'] * strategy.num_replicas_in_sync * cfg['batch_size']\n    lr_min = cfg['lr_min']\n    lr_rampup = cfg['lr_rampup']\n    lr_sustain = cfg['lr_sustain']\n    lr_decay = cfg['lr_decay']\n\n    def lrfn(epoch):\n        if epoch < lr_rampup:\n            lr = (lr_max - lr_start) / lr_rampup * epoch + lr_start\n        elif epoch < lr_rampup + lr_sustain:\n            lr = lr_max\n        else:\n            lr = (lr_max - lr_min) * lr_decay**(epoch - lr_rampup -\n                                                lr_sustain) + lr_min\n        return lr\n\n    lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)\n    return lr_callback\n\ncallbacks = [getLearnRateCallback(cfg)]","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"**EFFNET**","execution_count":null},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_model():\n    \n    ''' This function gets the layers inclunding efficientnet ones. '''\n    with strategy.scope():\n        model_input = tf.keras.Input(shape=(cfg['img_size'], cfg['img_size'], 3),\n                                     name='img_input')\n\n        dummy = tf.keras.layers.Lambda(lambda x: x)(model_input)\n\n        outputs = []\n        \n        x = efn.EfficientNetB3(include_top=False,\n                               weights='noisy-student',\n                               input_shape=(cfg['img_size'], cfg['img_size'], 3),\n                               pooling='avg')(dummy)\n        x = tf.keras.layers.Dense(890, activation='softmax')(x)\n        \"\"\"\n        outputs.append(x)\n\n        x = efn.EfficientNetB4(include_top=False,\n                               weights='noisy-student',\n                               input_shape=(cfg['img_size'], cfg['img_size'], 3),\n                               pooling='avg')(dummy)\n        x = tf.keras.layers.Dense(890, activation='softmax')(x)\n        outputs.append(x)\n\n        x = efn.EfficientNetB5(include_top=False,\n                               weights='noisy-student',\n                               input_shape=(cfg['img_size'], cfg['img_size'], 3),\n                               pooling='avg')(dummy)\n        x = tf.keras.layers.Dense(890, activation='softmax')(x)\n        outputs.append(x)\n        \"\"\"\n        model = tf.keras.Model(model_input, x, name='aNetwork')\n    \n    with strategy.scope():\n        model.compile(optimizer=cfg['optimizer'],\n                      loss=[\n                          tf.keras.losses.BinaryCrossentropy(\n                              label_smoothing=cfg['label_smooth_fac'])\n                      ],\n                      metrics=[tf.keras.metrics.AUC(name='auc')])\n    model.summary()\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def pre_model():\n    with strategy.scope():\n        pretrained_model = tf.keras.applications.DenseNet201(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        #pretrained_model = tf.keras.applications.Xception(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        #pretrained_model = tf.keras.applications.DenseNet169(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n        pretrained_model.trainable = False # False = transfer learning, True = fine-tuning\n\n        model = tf.keras.Sequential([\n            pretrained_model,\n            tf.keras.layers.GlobalAveragePooling2D(),\n            tf.keras.layers.Dense(890, activation='softmax')\n        ])\n    with strategy.scope():\n        model.compile(\n            optimizer= tf.keras.optimizers.SGD(lr=0.0001),\n            loss = 'categorical_crossentropy',\n            metrics=['accuracy']\n        )\n    model.summary()\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"dataset= get_f_data()\nNUM_TRAINING_IMAGES =  int(0.8 * count_data_items(filenames_train))\nNUM_VALIDATION_IMAGES = int(0.2 * count_data_items(filenames_train))\nNUM_TEST_IMAGES = count_data_items(filenames_test)\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nprint('Dataset: {} training images,{} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))\n\nmodel= get_model()\n\nhistory = model.fit(get_t_data(dataset), steps_per_epoch=STEPS_PER_EPOCH, \n                    epochs=5,validation_data=get_v_data(dataset),callbacks=callbacks\n                   )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"cnt_test= count_data_items(filenames_test)\nsteps      = cnt_test / (BATCH_SIZE) \n#ds_testAug = get_testdataset(files_test, CFG, augment=True, repeat=True, \n#                         labeled=False, return_image_names=False)\n\nprobs = model.predict(get_test_dataset(), verbose=1, steps=steps)\n\n#probs = np.stack(probs)\n#probs = probs[:,:cnt_test * CFG['tta_steps']]\n#probs = np.stack(np.split(probs, CFG['tta_steps'], axis=1), axis=1)\n#probs = np.mean(probs, axis=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#probs = np.mean(probs,axis=0)\nlen(probs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"classes=[*range(1, 891, 1)] \nprint(classes)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels=[]\nfor i in range(len(probs)):\n    \n    index = np.argsort(probs[i,:])\n    label= classes[index[1]]\n    p=round(probs[i,index[1]],6)\n    #print(p)\n    labels.append(f'{label} {p:.6f}')\n    \nlen(labels)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub= pd.read_csv('../input/landmark-recognition-2020/sample_submission.csv')\nsub['landmarks']=labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"sub.to_csv('submission.csv', index=False, float_format='%.6f')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}