{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import os\nimport pandas as pd\nimport numpy as np \nimport matplotlib.pyplot as plt\nimport tensorflow as tf\nfrom tensorflow.keras import regularizers  \nimport re","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Detect TPU, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver() \n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\nGCS_DS_PATH = KaggleDatasets().get_gcs_path()\n!gsutil ls $GCS_DS_PATH","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"Train_path=GCS_DS_PATH+'/tfrecords-jpeg-512x512/train/'\nval_path=GCS_DS_PATH+'/tfrecords-jpeg-512x512/val/'\ntest_path=GCS_DS_PATH+'/tfrecords-jpeg-512x512/test/'\ntrain_files=tf.io.gfile.glob(Train_path +'*.tfrec')\nval_files=tf.io.gfile.glob(val_path +'*.tfrec')\ntest_files=tf.io.gfile.glob(test_path +'*.tfrec')","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']   ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_SIZE        = [512, 512] \nHEIGHT            = IMAGE_SIZE[0]\nWIDTH             = IMAGE_SIZE[1]\nEPOCHS            = 20\nBATCH_SIZE        = 16 * strategy.num_replicas_in_sync\nNUM_TRAIN_IMAGES  = 12753\nNUM_VAL_IMAGES    = 3712\nNUM_TEST_IMAGES   = 7382\nSTEPS_PER_EPOCH   = NUM_TRAIN_IMAGES // BATCH_SIZE\nAUTO              = tf.data.experimental.AUTOTUNE","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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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, to be predicted 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, idnum) pairs","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n    \n    # automatically interleaves reads from multiple file\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) \n    \n    # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.with_options(ignore_order) \n    \n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    dataset = dataset.map(read_labeled_tfrecord if labeled \n                          else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def get_validation_dataset(filenames):\n    dataset = load_dataset(filenames,labeled=True, ordered=False)\n    dataset = dataset.cache()\n    dataset = dataset.shuffle(buffer_size=1920)\n    dataset = dataset.batch(BATCH_SIZE)\n    # prefetch next batch while training (autotune prefetch buffer size)\n    dataset = dataset.prefetch(AUTO) \n    return dataset\n\ndef get_test_dataset(filenames, ordered=True):  # order matters to submit predictions to Kaggle\n    dataset = load_dataset(filenames, labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    # prefetch next batch while training (autotune prefetch buffer size)\n    dataset = dataset.prefetch(AUTO) \n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# image augmentation, one image at a time                                \ndef data_augment(image, label):\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_contrast(image, 0.90, 0.99)\n    image = tf.image.random_brightness(image, 0.1) \n    image = tf.image.random_saturation(image, 0.8, 0.9)\n\n    # Pad the image with a black, 90-pixel border\n    image = tf.image.resize_with_crop_or_pad(image, HEIGHT + 180, WIDTH + 180)\n    # Randomly crop to original size from the padded image\n    image = tf.image.random_crop(image, size=[*IMAGE_SIZE,3])\n     \n    return image, label \n\n# get training datatset with augmentation option\ndef get_training_dataset(filenames, augmentation=False):\n    dataset = load_dataset(filenames, labeled=True, ordered=False)\n    if augmentation: # map the data_augment function to the dataset during training\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(buffer_size=1920)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)  # prefetch next batch while training\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"np.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 show_images(databatch, row=6, col=8):\n    FIGSIZE = col*2\n    plt.figure(figsize=(FIGSIZE,FIGSIZE/col*row))\n    images, num_labl = batch_to_numpy_images_and_labels(databatch)\n    for j in range(row*col):\n        plt.subplot(row,col,j+1)\n        plt.axis('off')\n        plt.title(num_labl[j])\n        plt.imshow(images[j,])\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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(train_files)\nNUM_VALIDATION_IMAGES = count_data_items(val_files)\nNUM_TEST_IMAGES = count_data_items(test_files)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# get original training_dataset WITHOUT data augmentation\nori_train_set = get_training_dataset(train_files, augmentation=False)\nori_image_batch = (next(iter(ori_train_set.unbatch().batch(16)))) # get a batch for \nimages, _ = batch_to_numpy_images_and_labels(ori_image_batch)\n\n# function to show image with random data augmentation\ndef show_aug(image):\n    plt.figure(figsize=(16,2))\n    \n    plt.subplot(1,7,1)\n    plt.title('no augmentation')\n    plt.axis('off')\n    plt.imshow(image)\n    \n    plt.subplot(1,7,3)\n    plt.title('resize & rdm crop')\n    plt.axis('off')    \n    # Pad the image with a black, 90-pixel border\n    image1 = tf.image.resize_with_crop_or_pad(image, HEIGHT + 180, WIDTH + 180)\n    # Randomly crop to original size from the padded image\n    image1 = tf.image.random_crop(image1, size=[*IMAGE_SIZE,3])\n    plt.imshow(image1)\n    \n    plt.subplot(1,7,4)\n    plt.title('rdm flip L/R')\n    plt.axis('off')    \n    plt.imshow(tf.image.random_flip_left_right(image))       # augmented with random flip\n    \n    plt.subplot(1,7,5)\n    plt.title('rdm contrast')\n    plt.axis('off')\n    plt.imshow(tf.image.random_contrast(image, 0.90, 0.99))  # augmented with contrast\n    \n    plt.subplot(1,7,6)\n    plt.title('rdm brightness')\n    plt.axis('off')\n    plt.imshow(tf.image.random_brightness(image, 0.15))       # augmented with brightness\n    \n    plt.subplot(1,7,7)\n    plt.title('rdm saturation')\n    plt.axis('off')\n    plt.imshow(tf.image.random_saturation(image, 0.75, 0.9))  # augmented with saturation\n     \n    # any random combinations of the above augmenations, if any\n    plt.subplot(1,7,2)\n    plt.title('rdm aug combo')\n    plt.axis('off')    \n    image = data_augment(image, None)\n    plt.imshow(image[0])  \n    plt.show()\n\n# show images\nprint('Training Dataset')\nprint('Sample Images: Original versus w/ Random Augmentation')\nfor im in images:\n    show_aug(im)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ds_train = get_training_dataset(train_files)\nds_valid = get_validation_dataset(val_files)\nds_test = get_test_dataset(test_files)\n\nprint(\"Training:\", ds_train)\nprint (\"Validation:\", ds_valid)\nprint(\"Test:\", ds_test)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Training data shapes:\")\nfor image, label in ds_train.take(3):\n    print(image.numpy().shape, label.numpy().shape)\nprint(\"Training data label examples:\", label.numpy())","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"image_input, label_val = next(iter(ds_train))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"fig = plt.figure(figsize=(10,5)) # define plot area\nax = fig.gca() # define axis    \ncounts = pd.DataFrame(label_val.numpy()).value_counts() # find the counts for each unique category\ncounts.plot.bar(ax = ax, color = 'blue') # Use the plot.bar method on the counts data frame\n\nax.set_xlabel('Labels') # Set text for the x axis\nax.set_ylabel('Number of occurences')# Set text for y axis\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pd.DataFrame(label_val.numpy()).value_counts()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\n\nfrom PIL import Image\nimport numpy as np\n\nfor i in range(0,5):\n    \n    im = image_input[i]\n  \n\n   # Create figure and axes\n    fig,ax = plt.subplots(1)\n\n    # Display the image\n    ax.imshow(im)\n    plt.title(CLASSES[label_val[i].numpy()])\n    plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"index=4\nname=CLASSES[index]\nprint(name)\nfor i in range(len(image_input)):\n    \n    if label_val[i].numpy()==index:\n        \n        im = image_input[i]\n\n\n       # Create figure and axes\n        fig,ax = plt.subplots(1)\n\n        # Display the image\n        ax.imshow(im)\n        \n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"index=53\nname=CLASSES[index]\nprint(name)\nfor i in range(len(image_input)):\n    \n    if label_val[i].numpy()==index:\n        \n        im = image_input[i]\n\n\n       # Create figure and axes\n        fig,ax = plt.subplots(1)\n\n        # Display the image\n        ax.imshow(im)\n        \n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"index=102\nname=CLASSES[index]\nprint(name)\nfor i in range(len(image_input)):\n    \n    if label_val[i].numpy()==index:\n        \n        im = image_input[i]\n\n\n       # Create figure and axes\n        fig,ax = plt.subplots(1)\n\n        # Display the image\n        ax.imshow(im)\n        \n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"index=72\nname=CLASSES[index]\nprint(name)\nfor i in range(len(image_input)):\n    \n    if label_val[i].numpy()==index:\n        \n        im = image_input[i]\n\n\n       # Create figure and axes\n        fig,ax = plt.subplots(1)\n\n        # Display the image\n        ax.imshow(im)\n        \n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"index=67\nname=CLASSES[index]\nprint(name)\nfor i in range(len(image_input)):\n    \n    if label_val[i].numpy()==index:\n        \n        im = image_input[i]\n\n\n       # Create figure and axes\n        fig,ax = plt.subplots(1)\n\n        # Display the image\n        ax.imshow(im)\n        \n        plt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_great_2=pd.DataFrame(label_val.numpy()).value_counts()[pd.DataFrame(label_val.numpy()).value_counts()>=2]","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Learning Rate Schedule for Fine Tuning #\ndef exponential_lr(epoch,\n                   start_lr = 0.00001, min_lr = 0.00001, max_lr = 0.00005,\n                   rampup_epochs = 5, sustain_epochs = 0,\n                   exp_decay = 0.8):\n\n    def lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay):\n        # linear increase from start to rampup_epochs\n        if epoch < rampup_epochs:\n            lr = ((max_lr - start_lr) /\n                  rampup_epochs * epoch + start_lr)\n        # constant max_lr during sustain_epochs\n        elif epoch < rampup_epochs + sustain_epochs:\n            lr = max_lr\n        # exponential decay towards min_lr\n        else:\n            lr = ((max_lr - min_lr) *\n                  exp_decay**(epoch - rampup_epochs - sustain_epochs) +\n                  min_lr)\n        return lr\n    return lr(epoch,\n              start_lr,\n              min_lr,\n              max_lr,\n              rampup_epochs,\n              sustain_epochs,\n              exp_decay)\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True)\n\nrng = [i for i in range(EPOCHS)]\ny = [exponential_lr(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":"with strategy.scope():\n    pretrained_model = tf.keras.applications.DenseNet201(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    pretrained_model.trainable = False\n    \n    model = tf.keras.Sequential([\n        # To a base pretrained on ImageNet to extract features from images...\n        pretrained_model,\n        # ... attach a new head to act as a classifier.\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dropout(0.3),\n        tf.keras.layers.Dense(512,kernel_regularizer=regularizers.l2(0.001)),\n        \n        tf.keras.layers.Dense(256,kernel_regularizer=regularizers.l2(0.001)),\n        \n        tf.keras.layers.Dense(128,kernel_regularizer=regularizers.l2(0.001)),\n        \n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])\n    model.compile(\n        optimizer='adam',\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy'],\n    )\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Define the batch size. This will be 16 with TPU off and 128 with TPU on\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\n# Define training epochs for committing/submitting. (TPU on)\n\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nhistory = model.fit(\n    ds_train,\n    validation_data=ds_valid,\n    epochs=EPOCHS,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    callbacks=[lr_callback]\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def 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":{"trusted":true},"cell_type":"code","source":"display_training_curves(\n    history.history['loss'],\n    history.history['val_loss'],\n    'loss',\n    211,\n)\ndisplay_training_curves(\n    history.history['sparse_categorical_accuracy'],\n    history.history['val_sparse_categorical_accuracy'],\n    'accuracy',\n    212,\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"#model.save('model_vgc.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"# With pretrained model: DenseNet201\nwith strategy.scope():    \n    pretrain_model = tf.keras.applications.InceptionV3(\n        weights='imagenet', \n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    pretrain_model.trainable = False # transfer learning\n    model_incep = tf.keras.Sequential([\n        pretrain_model,\n#        tf.keras.layers.experimental.preprocessing.RandomRotation(0.15),\n#        tf.keras.layers.experimental.preprocessing.RandomZoom(0.75),\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dropout(0.3),  \n        tf.keras.layers.Dense(len(CLASSES), kernel_regularizer=regularizers.l2(0.001), \n                              activation='softmax')\n    ])\n    \n    model_incep.compile(\n        optimizer='adam',\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy'],\n    )\n\nmodel_incep.summary()\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nhistorical = model_incep.fit(\n    ds_train,\n    validation_data=ds_valid,\n    epochs=EPOCHS,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    callbacks=[lr_callback]\n)\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"display_training_curves(\n    historical.history['loss'],\n    historical.history['val_loss'],\n    'loss',\n    211,\n)\ndisplay_training_curves(\n    historical.history['sparse_categorical_accuracy'],\n    historical.history['val_sparse_categorical_accuracy'],\n    'accuracy',\n    212,\n)\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"# With pretrained model: DenseNet201\nwith strategy.scope():    \n    pretrain_model_Inceptio = tf.keras.applications.InceptionResNetV2(\n        weights='imagenet', \n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    pretrain_model_Inceptio.trainable = False # transfer learning\n    model_Inceptio = tf.keras.Sequential([\n         pretrain_model_Inceptio,\n#        tf.keras.layers.experimental.preprocessing.RandomRotation(0.15),\n#        tf.keras.layers.experimental.preprocessing.RandomZoom(0.75),\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dropout(0.3),  \n        tf.keras.layers.Dense(len(CLASSES), kernel_regularizer=regularizers.l2(0.001), \n                              activation='softmax')\n    ])\n    \n    model_Inceptio.compile(\n        optimizer='adam',\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy'],\n    )\n\nmodel_Inceptio.summary()\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\nhistorical_inc = model_Inceptio.fit(\n    ds_train,\n    validation_data=ds_valid,\n    epochs=EPOCHS,\n    steps_per_epoch=STEPS_PER_EPOCH,\n    callbacks=[lr_callback]\n)\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"display_training_curves(\n    historical_inc.history['loss'],\n    historical.history['val_loss'],\n    'loss',\n    211,\n)\ndisplay_training_curves(\n    historical_inc.history['sparse_categorical_accuracy'],\n    historical.history['val_sparse_categorical_accuracy'],\n    'accuracy',\n    212,\n)\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\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":{"trusted":true},"cell_type":"code","source":"cmdataset = get_validation_dataset(val_files)\nimages_ds = cmdataset.map(lambda image, label: image)\nlabels_ds = cmdataset.map(lambda image, label: label).unbatch()\n\ncm_correct_labels = next(iter(labels_ds.batch(NUM_VALIDATION_IMAGES))).numpy()\ncm_probabilities = model.predict(images_ds)\n\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\n\nlabels = range(len(CLASSES))\ncmat = confusion_matrix(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n)\ncmat = (cmat.T / cmat.sum(axis=1)).T # normalize","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"score = f1_score(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\nprecision = precision_score(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\nrecall = recall_score(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n    average='macro',\n)\ndisplay_confusion_matrix(cmat, score, precision, recall)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_images_ds = ds_test.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"\n\nprint('Computing predictions...')\ntest_images_ds = ds_test.map(lambda image, idnum: image)\nprobabilities_1 = model.predict(test_images_ds)\nprobabilities_2 = model_incep.predict(test_images_ds)\nprobabilities_3 = model_Inceptio.predict(test_images_ds)\nensemble_11=probabilities_1 *.5 +  probabilities_2*.5\nensemble_12=probabilities_1 *.25 +  probabilities_2*.75\nensemble_13=probabilities_1 *.75 +  probabilities_2*.25\n\nensemble_21=probabilities_1 *.5 +  probabilities_3*.5\nensemble_22=probabilities_1 *.25 +  probabilities_3*.75\nensemble_23=probabilities_1 *.75 +  probabilities_3*.25\n\nensemble_31=probabilities_2 *.5 +  probabilities_3*.5\nensemble_32=probabilities_2 *.25 +  probabilities_3*.75\nensemble_33=probabilities_2 *.75 +  probabilities_3*.25\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"predictions11 = np.argmax(ensemble_11, axis=-1)\nprint(predictions)\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"predictions12 = np.argmax(ensemble_12, axis=-1)\nprint(predictions12)\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"predictions13 = np.argmax(ensemble_13, axis=-1)\nprint(predictions13)\"\"\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"predictions21 = np.argmax(ensemble_21, axis=-1)\npredictions22 = np.argmax(ensemble_22, axis=-1)\npredictions23 = np.argmax(ensemble_23, axis=-1)\n\npredictions31 = np.argmax(ensemble_31, axis=-1)\npredictions32 = np.argmax(ensemble_32, axis=-1)\npredictions33 = np.argmax(ensemble_33, axis=-1)\n\n\"\"\"\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print('Generating submission.csv file...')\n\n# Get image ids from test set and convert to unicode\ntest_ids_ds = ds_test.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n# Write the submission file\nnp.savetxt(\n    'submission.csv',\n    np.rec.fromarrays([test_ids, predictions]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Look at the first few predictions\n!head submission.csv","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"\"\"\"print('Generating submission.csv file...')\n\n# Get image ids from test set and convert to unicode\ntest_ids_ds = ds_test.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\n# Write the submission file\nnp.savetxt(\n    'submission2.csv',\n    np.rec.fromarrays([test_ids, predictions12]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Write the submission file\nnp.savetxt(\n    'submission3.csv',\n    np.rec.fromarrays([test_ids, predictions13]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Write the submission file\nnp.savetxt(\n    'submission4.csv',\n    np.rec.fromarrays([test_ids, predictions21]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Write the submission file\nnp.savetxt(\n    'submission5.csv',\n    np.rec.fromarrays([test_ids, predictions22]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Write the submission file\nnp.savetxt(\n    'submission6.csv',\n    np.rec.fromarrays([test_ids, predictions23]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Write the submission file\nnp.savetxt(\n    'submission7.csv',\n    np.rec.fromarrays([test_ids, predictions31]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Write the submission file\nnp.savetxt(\n    'submission8.csv',\n    np.rec.fromarrays([test_ids, predictions32]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Write the submission file\nnp.savetxt(\n    'submission9.csv',\n    np.rec.fromarrays([test_ids, predictions33]),\n    fmt=['%s', '%d'],\n    delimiter=',',\n    header='id,label',\n    comments='',\n)\n\n# Look at the first few predictions\n!head submission2.csv\"\"\"","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}