{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"!pip install -q efficientnet","execution_count":null,"outputs":[]},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"cell_type":"code","source":"!pip install tensorflow_addons","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import math, re, os\nimport tensorflow as tf\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nimport efficientnet.tfkeras as efn\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nfrom tensorflow.keras.applications import InceptionResNetV2\nfrom tensorflow.keras.applications import DenseNet201\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nprint(\"Tensorflow version \" + tf.__version__)\nfrom tensorflow.keras import backend as K\nimport gc","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow_addons as tfa","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n\n# Create strategy from tpu\ntpu = tf.distribute.cluster_resolver.TPUClusterResolver()\ntf.config.experimental_connect_to_cluster(tpu)\ntf.tpu.experimental.initialize_tpu_system(tpu)\nstrategy = tf.distribute.experimental.TPUStrategy(tpu)\n\n# Data access\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('flower-classification-with-tpus')\n\n# Configuration\nimg_size=512\nIMAGE_SIZE = [img_size, img_size]\nEPOCHS = 20\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"EPOCHS_ = 20\nLR_START = 0.0001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.000005\nLR_RAMPUP_EPOCHS = 3\nLR_SUSTAIN_EPOCHS = 3\nLR_EXP_DECAY = .8\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = np.random.random_sample() * LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)\n\nrng = [i for i in range(EPOCHS_)]\ny = [lrfn(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_PATH_SELECT = { # available image sizes\n    192: GCS_DS_PATH + '/tfrecords-jpeg-192x192',\n    224: GCS_DS_PATH + '/tfrecords-jpeg-224x224',\n    331: GCS_DS_PATH + '/tfrecords-jpeg-331x331',\n    512: GCS_DS_PATH + '/tfrecords-jpeg-512x512'\n}\nGCS_PATH = GCS_PATH_SELECT[IMAGE_SIZE[0]]\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/test/*.tfrec') # predictions on this dataset should be submitted for the competition\n\n# watch out for overfitting!\nSKIP_VALIDATION = True\n# import random\n# random.shuffle(VALIDATION_FILENAMES)\n# TRAINING_FILENAMES = TRAINING_FILENAMES+VALIDATION_FILENAMES[:8]\n# VALIDATION_FILENAMES = VALIDATION_FILENAMES[8:]\n# if SKIP_VALIDATION:\nTRAINING_FILENAMES = TRAINING_FILENAMES + VALIDATION_FILENAMES","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"SKIP_VALIDATION = True\nimport math, re, os\nimport tensorflow as tf\nimport numpy as np\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\n\nGCS_DS_PATH1 = KaggleDatasets().get_gcs_path('mytraindataset')\nTRAINING_FILENAMES_ = tf.io.gfile.glob(GCS_DS_PATH1 + '/*.tfrec')\n\nTRAINING_FILENAMES = TRAINING_FILENAMES + TRAINING_FILENAMES_","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(GCS_DS_PATH1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(TEST_FILENAMES)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len(TRAINING_FILENAMES)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"CLASSES = ['pink primrose',    'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',     'wild geranium',     'tiger lily',           'moon orchid',              'bird of paradise', 'monkshood',        'globe thistle',         # 00 - 09\n           'snapdragon',       \"colt's foot\",               'king protea',      'spear thistle', 'yellow iris',       'globe-flower',         'purple coneflower',        'peruvian lily',    'balloon flower',   'giant white arum lily', # 10 - 19\n           'fire lily',        'pincushion flower',         'fritillary',       'red ginger',    'grape hyacinth',    'corn poppy',           'prince of wales feathers', 'stemless gentian', 'artichoke',        'sweet william',         # 20 - 29\n           'carnation',        'garden phlox',              'love in the mist', 'cosmos',        'alpine sea holly',  'ruby-lipped cattleya', 'cape flower',              'great masterwort', 'siam tulip',       'lenten rose',           # 30 - 39\n           'barberton daisy',  'daffodil',                  'sword lily',       'poinsettia',    'bolero deep blue',  'wallflower',           'marigold',                 'buttercup',        'daisy',            'common dandelion',      # 40 - 49\n           'petunia',          'wild pansy',                'primula',          'sunflower',     'lilac hibiscus',    'bishop of llandaff',   'gaura',                    'geranium',         'orange dahlia',    'pink-yellow dahlia',    # 50 - 59\n           'cautleya spicata', 'japanese anemone',          'black-eyed susan', 'silverbush',    'californian poppy', 'osteospermum',         'spring crocus',            'iris',             'windflower',       'tree poppy',            # 60 - 69\n           'gazania',          'azalea',                    'water lily',       'rose',          'thorn apple',       'morning glory',        'passion flower',           'lotus',            'toad lily',        'anthurium',             # 70 - 79\n           'frangipani',       'clematis',                  'hibiscus',         'columbine',     'desert-rose',       'tree mallow',          'magnolia',                 'cyclamen ',        'watercress',       'canna lily',            # 80 - 89\n           'hippeastrum ',     'bee balm',                  'pink quill',       'foxglove',      'bougainvillea',     'camellia',             'mallow',                   'mexican petunia',  'bromelia',         'blanket flower',        # 90 - 99\n           'trumpet creeper',  'blackberry lily',           'common tulip',     'wild rose']                                                                                                                                               # 100 - 102\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        \"class\": tf.io.FixedLenFeature([], tf.int64),  # 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.one_hot(example['class'], 104)\n#     label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_labeled_tfrecord_train(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # 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.one_hot(example['class'], 104)\n#     label = tf.cast(example['class'], tf.int32)\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, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) \n    dataset = dataset.with_options(ignore_order) \n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    return dataset\n\ndef load_dataset_train(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    dataset = dataset.map(read_labeled_tfrecord_train if labeled else read_unlabeled_tfrecord, 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 get_training_dataset(do_aug=False):\n    dataset = load_dataset_train(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    if do_aug: dataset = dataset.map(transform, num_parallel_calls=AUTO)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\n\n\ndef data_augment(image, 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    return image, label   \n\n# def get_training_dataset():\n#     dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\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#     dataset = dataset.batch(BATCH_SIZE)\n#     dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n#     return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES, 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\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(TEST_FILENAMES, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\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\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = (1 - SKIP_VALIDATION) * count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_mat(rotation, shear, height_zoom, width_zoom, height_shift, width_shift):\n    # returns 3x3 transformmatrix which transforms indicies\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( tf.concat([c1,s1,zero, -s1,c1,zero, zero,zero,one],axis=0),[3,3] )\n        \n    # SHEAR MATRIX\n    c2 = tf.math.cos(shear)\n    s2 = tf.math.sin(shear)\n    shear_matrix = tf.reshape( tf.concat([one,s2,zero, zero,c2,zero, zero,zero,one],axis=0),[3,3] )    \n    \n    # ZOOM MATRIX\n    zoom_matrix = tf.reshape( tf.concat([one/height_zoom,zero,zero, zero,one/width_zoom,zero, zero,zero,one],axis=0),[3,3] )\n    \n    # SHIFT MATRIX\n    shift_matrix = tf.reshape( tf.concat([one,zero,height_shift, zero,one,width_shift, zero,zero,one],axis=0),[3,3] )\n    \n    return K.dot(K.dot(rotation_matrix, shear_matrix), K.dot(zoom_matrix, shift_matrix))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def transform(image,label):\n    # input image - is one image of size [dim,dim,3] not a batch of [b,dim,dim,3]\n    # output - image randomly rotated, sheared, zoomed, and shifted\n    DIM = IMAGE_SIZE[0]\n    XDIM = DIM%2 #fix for size 331\n    \n    rot = 15. * tf.random.normal([1],dtype='float32')\n    shr = 5. * tf.random.normal([1],dtype='float32') \n    h_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n    w_zoom = 1.0 + tf.random.normal([1],dtype='float32')/10.\n    h_shift = 16. * tf.random.normal([1],dtype='float32') \n    w_shift = 16. * 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]),label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\ntest_images_ds = test_ds.map(lambda image, idnum: image)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Peek at training data\ntraining_dataset = get_training_dataset()\ntraining_dataset = training_dataset.unbatch().batch(20)\ntrain_batch = iter(training_dataset)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# data dump\nprint(\"Training data shapes:\")\nfor image, label in get_training_dataset().take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())\nprint(\"Test data shapes:\")\nfor image, idnum in get_test_dataset().take(3):\n    print(image.numpy().shape, idnum.numpy().shape)\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras import backend as K\n\nimport dill\n\n\ndef binary_focal_loss(gamma=2., alpha=.25):\n    \"\"\"\n    Binary form of focal loss.\n      FL(p_t) = -alpha * (1 - p_t)**gamma * log(p_t)\n      where p = sigmoid(x), p_t = p or 1 - p depending on if the label is 1 or 0, respectively.\n    References:\n        https://arxiv.org/pdf/1708.02002.pdf\n    Usage:\n     model.compile(loss=[binary_focal_loss(alpha=.25, gamma=2)], metrics=[\"accuracy\"], optimizer=adam)\n    \"\"\"\n    def binary_focal_loss_fixed(y_true, y_pred):\n        \"\"\"\n        :param y_true: A tensor of the same shape as `y_pred`\n        :param y_pred:  A tensor resulting from a sigmoid\n        :return: Output tensor.\n        \"\"\"\n        pt_1 = tf.where(tf.equal(y_true, 1), y_pred, tf.ones_like(y_pred))\n        pt_0 = tf.where(tf.equal(y_true, 0), y_pred, tf.zeros_like(y_pred))\n\n        epsilon = K.epsilon()\n        # clip to prevent NaN's and Inf's\n        pt_1 = K.clip(pt_1, epsilon, 1. - epsilon)\n        pt_0 = K.clip(pt_0, epsilon, 1. - epsilon)\n\n        return -K.sum(alpha * K.pow(1. - pt_1, gamma) * K.log(pt_1)) \\\n               -K.sum((1 - alpha) * K.pow(pt_0, gamma) * K.log(1. - pt_0))\n\n    return binary_focal_loss_fixed\n\n\ndef categorical_focal_loss(gamma=2., alpha=.25):\n    \"\"\"\n    Softmax version of focal loss.\n           m\n      FL = ∑  -alpha * (1 - p_o,c)^gamma * y_o,c * log(p_o,c)\n          c=1\n      where m = number of classes, c = class and o = observation\n    Parameters:\n      alpha -- the same as weighing factor in balanced cross entropy\n      gamma -- focusing parameter for modulating factor (1-p)\n    Default value:\n      gamma -- 2.0 as mentioned in the paper\n      alpha -- 0.25 as mentioned in the paper\n    References:\n        Official paper: https://arxiv.org/pdf/1708.02002.pdf\n        https://www.tensorflow.org/api_docs/python/tf/keras/backend/categorical_crossentropy\n    Usage:\n     model.compile(loss=[categorical_focal_loss(alpha=.25, gamma=2)], metrics=[\"accuracy\"], optimizer=adam)\n    \"\"\"\n    def categorical_focal_loss_fixed(y_true, y_pred):\n        \"\"\"\n        :param y_true: A tensor of the same shape as `y_pred`\n        :param y_pred: A tensor resulting from a softmax\n        :return: Output tensor.\n        \"\"\"\n\n        # Scale predictions so that the class probas of each sample sum to 1\n        y_pred /= K.sum(y_pred, axis=-1, keepdims=True)\n\n        # Clip the prediction value to prevent NaN's and Inf's\n        epsilon = K.epsilon()\n        y_pred = K.clip(y_pred, epsilon, 1. - epsilon)\n\n        # Calculate Cross Entropy\n        cross_entropy = -y_true * K.log(y_pred)\n\n        # Calculate Focal Loss\n        loss = alpha * K.pow(1 - y_pred, gamma) * cross_entropy\n\n        # Sum the losses in mini_batch\n        return K.sum(loss, axis=1)\n\n    return categorical_focal_loss_fixed\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Learning rate schedule for TPU, GPU and CPU.\n# Using an LR ramp up because fine-tuning a pre-trained model.\n# Starting with a high LR would break the pre-trained weights.\n\nLR_START = 0.00001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 4\nLR_SUSTAIN_EPOCHS = 4\nLR_EXP_DECAY = .8\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)\n\n# rng = [i for i in range(25 if EPOCHS<25 else EPOCHS)]\n# y = [lrfn(x) for x in rng]\n# plt.plot(rng, y)\n# print(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    desnet=tf.keras.applications.Xception(\n        weights='imagenet',\n        include_top=False\n      \n    )\n    model1 = tf.keras.Sequential([\n        desnet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dropout(0.5),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ]) \n\nmodel1.compile(\n    optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n#     loss = [categorical_focal_loss(gamma=2., alpha=.25)],\n    loss = 'categorical_crossentropy',\n    metrics=[tfa.metrics.F1Score(num_classes=104, average=\"macro\")]\n)\nmodel1.summary()\nmodel1.load_weights('../input/mytopmodel/Xception_best.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    desnet=tf.keras.applications.DenseNet201(\n        weights='imagenet',\n        include_top=False\n      \n    )\n    model2 = tf.keras.Sequential([\n        desnet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dropout(0.5),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ]) \n\nmodel2.compile(\n    optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n#     loss = [categorical_focal_loss(gamma=2., alpha=.25)],\n    loss = 'categorical_crossentropy',\n    metrics=[tfa.metrics.F1Score(num_classes=104, average=\"macro\")]\n)\nmodel2.summary()\nmodel2.load_weights('../input/mytopmodel/dense_best.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    desnet=tf.keras.applications.InceptionResNetV2(\n        weights='imagenet',\n        include_top=False\n      \n    )\n    model3 = tf.keras.Sequential([\n        desnet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dropout(0.5),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ]) \n\nmodel3.compile(\n    optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n#     loss = [categorical_focal_loss(gamma=2., alpha=.25)],\n    loss = 'categorical_crossentropy',\n    metrics=[tfa.metrics.F1Score(num_classes=104, average=\"macro\")]\n)\nmodel3.summary()\nmodel3.load_weights('../input/mytopmodel/InceptionResV2_best.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    desnet=tf.keras.applications.VGG19(\n        weights='imagenet',\n        include_top=False\n      \n    )\n    model4 = tf.keras.Sequential([\n        desnet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dropout(0.5),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ]) \n\nmodel4.compile(\n    optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n#     loss = [categorical_focal_loss(gamma=2., alpha=.25)],\n    loss = 'categorical_crossentropy',\n    metrics=[tfa.metrics.F1Score(num_classes=104, average=\"macro\")]\n)\nmodel4.summary()\nmodel4.load_weights('../input/mytopmodel/VGG_best.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    desnet=efn.EfficientNetB5(\n        weights='noisy-student',\n        include_top=False\n      \n    )\n    model5 = tf.keras.Sequential([\n        desnet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dropout(0.5),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ]) \n\nmodel5.compile(\n    optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n#     loss = [categorical_focal_loss(gamma=2., alpha=.25)],\n    loss = 'categorical_crossentropy',\n    metrics=[tfa.metrics.F1Score(num_classes=104, average=\"macro\")]\n)\nmodel5.summary()\nmodel5.load_weights('../input/mytopmodel/B5_best.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    desnet=tf.keras.applications.ResNet152V2(\n        weights='imagenet',\n        include_top=False\n      \n    )\n    model6 = tf.keras.Sequential([\n        desnet,\n        tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dropout(0.5),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ]) \n\nmodel6.compile(\n    optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n#     loss = [categorical_focal_loss(gamma=2., alpha=.25)],\n    loss = 'categorical_crossentropy',\n    metrics=[tfa.metrics.F1Score(num_classes=104, average=\"macro\")]\n)\nmodel6.summary()\nmodel6.load_weights('../input/mytopmodel/Res152_best.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"models = [model1, model2, model3, model4, model5, model6]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprint('Computing predictions...')\n# get the mean probability of the folds models\nprobabilities = np.average([models[i].predict(test_images_ds) for i in range(6)], axis = 0)\npredictions = np.argmax(probabilities, axis=-1)\nprint('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\nreturn histories, models","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model11 = tf.keras.Sequential()\n# for layer in model1.layers[:-2]:\n#     model11.add(layer)\n# for layer in model11.layers:\n#     layer.trainable = False\n# model22 = tf.keras.Sequential()\n# for layer in model2.layers[:-2]:\n#     model22.add(layer)\n# for layer in model22.layers:\n#     layer.trainable = False\n    \n# model33 = tf.keras.Sequential()\n# for layer in model3.layers[:-2]:\n#     model33.add(layer)\n# for layer in model33.layers:\n#     layer.trainable = False\n    \n    \n# model44 = tf.keras.Sequential()\n# for layer in model4.layers[:-2]:\n#     model44.add(layer)\n# for layer in model44.layers:\n#     layer.trainable = False\n    \n# model55 = tf.keras.Sequential()\n# for layer in model5.layers[:-2]:\n#     model55.add(layer)\n# for layer in model55.layers:\n#     layer.trainable = False\n    \n# model66 = tf.keras.Sequential()\n# for layer in model6.layers[:-2]:\n#     model66.add(layer)\n# for layer in model66.layers:\n#     layer.trainable = False","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def get_model():\n#     with strategy.scope():\n#         x = tf.keras.Input(shape = (img_size, img_size, 3))\n#         x1 = model11(x)\n#         x1 = tf.keras.layers.GlobalAveragePooling2D()(x1)\n#         x2 = model22(x)\n#         x2 = tf.keras.layers.GlobalAveragePooling2D()(x2)\n#         x3 = model33(x)\n#         x3 = tf.keras.layers.GlobalAveragePooling2D()(x3)\n#         x4 = model44(x)\n#         x4 = tf.keras.layers.GlobalAveragePooling2D()(x4)\n#         x5 = model55(x)\n#         x5 = tf.keras.layers.GlobalAveragePooling2D()(x5)\n#         x6 = model66(x)\n#         x6 = tf.keras.layers.GlobalAveragePooling2D()(x6)\n#         x7 = tf.keras.layers.concatenate([x1, x2, x3, x4, x5, x6], axis = 1)\n# #         x8 = tf.keras.layers.GlobalAveragePooling2D()(x7)\n#         x9 = tf.keras.layers.Dropout(5/6)(x7)\n#         x9 = tf.keras.layers.Dense(len(CLASSES), activation='softmax')(x9)\n#         out = tf.keras.Model(inputs = x, outputs = x9)\n#     out.compile(\n#         optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n#     #     loss = [categorical_focal_loss(gamma=2., alpha=.25)],\n#         loss = 'categorical_crossentropy',\n#         metrics=[tfa.metrics.F1Score(num_classes=104, average=\"macro\")]\n#     )\n#     return out\n# # out.summary()\n# # model4.load_weights('../input/mytopmodels/weights_efficient_23.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# my_call = tf.keras.callbacks.ModelCheckpoint('ensemble.h5', monitor='val_f1_score', mode='max', verbose=1, save_best_only=True, save_weights_only=True)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# from sklearn.model_selection import KFold","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# FOLDS = 3\n# SEED = 777\n# import pandas as pd","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# def train_cross_validate(folds = 3):\n#     histories = []\n#     models = []\n#     early_stopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_f1_score', patience = 5, restore_best_weights=True)\n#     kfold = KFold(folds, shuffle = True, random_state = SEED)\n#     for f, (trn_ind, val_ind) in enumerate(kfold.split(TRAINING_FILENAMES)):\n#         print(); print('#'*25)\n#         print('### FOLD',f+1)\n#         print('#'*25)\n#         train_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES}).loc[trn_ind]['TRAINING_FILENAMES']), labeled = True)\n#         val_dataset = load_dataset(list(pd.DataFrame({'TRAINING_FILENAMES': TRAINING_FILENAMES}).loc[val_ind]['TRAINING_FILENAMES']), labeled = True, ordered = True)\n#         model = get_model()\n#         history = model.fit(\n#             get_training_dataset(train_dataset), \n#             steps_per_epoch = STEPS_PER_EPOCH,\n#             epochs = EPOCHS,\n#             callbacks = [lr_callback, early_stopping],\n#             validation_data = get_validation_dataset(val_dataset),\n#             verbose=2\n#         )\n#         models.append(model)\n#         histories.append(history)\n#     return histories, models\n\n# def train_and_predict(folds = 3):\n#     test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n#     test_images_ds = test_ds.map(lambda image, idnum: image)\n#     print('Start training %i folds'%folds)\n#     histories, models = train_cross_validate(folds = folds)\n#     print('Computing predictions...')\n#     # get the mean probability of the folds models\n#     probabilities = np.average([models[i].predict(test_images_ds) for i in range(folds)], axis = 0)\n#     predictions = np.argmax(probabilities, axis=-1)\n#     print('Generating submission.csv file...')\n#     test_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\n#     test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\n#     np.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n#     return histories, models\n    \n# # run train and predict\n# histories, models = train_and_predict(folds = FOLDS)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# history = out.fit(\n#     get_training_dataset(), \n#     steps_per_epoch=STEPS_PER_EPOCH,\n#     epochs=EPOCHS,\n#     callbacks=[lr_callback, my_call],\n#     validation_data=None if SKIP_VALIDATION else get_validation_dataset(),\n# #     validation_data = (val_images, val_labels),\n#     shuffle = True\n# )","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# with strategy.scope():\n#     enet = efn.EfficientNetB4(\n#         input_shape=(img_size, img_size, 3),\n#         weights='noisy-student',\n#         include_top=False\n#     )\n\n#     model2 = tf.keras.Sequential([\n#         enet,\n#         tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n#     ]) \n\n# model2.compile(\n#     optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n#     loss = [categorical_focal_loss(gamma=2., alpha=.25)],\n# #     loss = 'categorical_crossentropy',\n#     metrics=[tfa.metrics.F1Score(num_classes=104, average=\"macro\")]\n# )\n# model2.summary()\n# model2.load_weights('../input/mytopmodels/weights_efficient_20.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# with strategy.scope():\n#     enet = efn.EfficientNetB5(\n#         input_shape=(img_size, img_size, 3),\n#         weights='noisy-student',\n#         include_top=False\n#     )\n\n#     model3 = tf.keras.Sequential([\n#         enet,\n#         tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n#     ]) \n\n# model3.compile(\n#     optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n#     loss = [categorical_focal_loss(gamma=2., alpha=.25)],\n# #     loss = 'categorical_crossentropy',\n#     metrics=[tfa.metrics.F1Score(num_classes=104, average=\"macro\")]\n# )\n# model3.summary()\n# model3.load_weights('../input/mytopmodels/weights_efficient_24(1).h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# with strategy.scope():\n#     enet = efn.EfficientNetB6(\n#         input_shape=(img_size, img_size, 3),\n#         weights='noisy-student',\n#         include_top=False\n#     )\n\n#     model4 = tf.keras.Sequential([\n#         enet,\n#         tf.keras.layers.GlobalAveragePooling2D(),\n#         tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n#     ]) \n\n# model4.compile(\n#     optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n#     loss = [categorical_focal_loss(gamma=2., alpha=.25)],\n# #     loss = 'categorical_crossentropy',\n#     metrics=[tfa.metrics.F1Score(num_classes=104, average=\"macro\")]\n# )\n# model4.summary()\n# model4.load_weights('../input/mytopmodels/weights_efficient_23.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# model11 = tf.keras.Sequential()\n# for layer in model1.layers[:-2]:\n#     model11.add(layer)\n# for layer in model11.layers:\n#     layer.trainable = False\n# model22 = tf.keras.Sequential()\n# for layer in model2.layers[:-2]:\n#     model22.add(layer)\n# for layer in model22.layers:\n#     layer.trainable = False\n    \n# model33 = tf.keras.Sequential()\n# for layer in model3.layers[:-2]:\n#     model33.add(layer)\n# for layer in model33.layers:\n#     layer.trainable = False\n    \n    \n# model44 = tf.keras.Sequential()\n# for layer in model4.layers[:-2]:\n#     model44.add(layer)\n# for layer in model44.layers:\n#     layer.trainable = False\n    \n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# with strategy.scope():\n    \n#     x = tf.keras.Input(shape = (img_size, img_size, 3))\n#     x1 = model11(x)\n#     x2 = model22(x)\n#     x3 = model33(x)\n#     x4 = model44(x)\n#     x5 = tf.keras.layers.concatenate([x1, x2, x3, x4], axis = 3)\n#     x6 = tf.keras.layers.GlobalAveragePooling2D()(x5)\n#     x6 = tf.keras.layers.Dropout(0.75)(x6)\n#     x6 = tf.keras.layers.Dense(len(CLASSES), activation='softmax')(x6)\n#     out = tf.keras.Model(inputs = x, outputs = x6)\n\n# out.compile(\n#     optimizer=tf.keras.optimizers.Adam(lr=0.0001),\n# #     loss = [categorical_focal_loss(gamma=2., alpha=.25)],\n#     loss = 'categorical_crossentropy',\n#     metrics=[tfa.metrics.F1Score(num_classes=104, average=\"macro\")]\n# )\n# out.summary()\n# # model4.load_weights('../input/mytopmodels/weights_efficient_23.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# EPOCHS_ = 50\n# LR_START = 0.00001\n# LR_MAX = 0.0004\n# LR_MIN = 0.00001\n# LR_RAMPUP_EPOCHS = 4\n# LR_SUSTAIN_EPOCHS = 4\n# LR_EXP_DECAY = .75\n# test_ds = get_test_dataset(ordered=True)\n# test_images_ds = test_ds.map(lambda image, idnum: image)\n# n = 0\n# def lrfn(epoch):\n#     if epoch > 7:\n#         out.save_weights(\"weights_ensemble_{}.h5\".format(epoch))\n#         print('Generating submission.csv file...')\n#         test_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\n#         test_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\n#         np.savetxt(\"submission_ensemble_{}.csv\".format(epoch), np.rec.fromarrays([test_ids, np.argmax(out.predict(test_images_ds), axis=-1)]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n#     if epoch - (epoch//25)*25 + 1 < LR_RAMPUP_EPOCHS:\n#         lr = np.random.random_sample() * LR_START\n#     elif epoch - (epoch//25)*25 + 1 < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n#         lr = LR_MAX\n#     else:\n#         lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - (epoch//25)*25 + 1 - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n#     return lr\n    \n# lr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=True)\n\n# # rng = [i for i in range(EPOCHS_)]\n# # y = [lrfn(x) for x in rng]\n# # plt.plot(rng, y)\n# # print(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# history = out.fit(\n#     get_training_dataset(), \n#     steps_per_epoch=STEPS_PER_EPOCH,\n#     epochs=EPOCHS,\n#     callbacks=[lr_callback],\n#     validation_data=None if SKIP_VALIDATION else get_validation_dataset(),\n# #     validation_data = (val_images, val_labels),\n#     shuffle = True\n# )","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}