{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\n#import os\n#for dirname, _, filenames in os.walk('/kaggle/input'):\n#    for filename in filenames:\n#        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install -q -U tensorflow-addons\n# install EfficientNet\n!pip install -q efficientnet","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math, re, os\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport efficientnet.tfkeras as efn\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\nfrom tensorflow.keras import regularizers   \n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Detect hardware TPU and return appropriate distribution strategy\n# TFRecord is a binary file that contains sequences of byte-strings.\ntry:\n    # TPU detection\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    # default distribution strategy in Tensorflow\n    strategy = tf.distribute.get_strategy() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\n\n# We'll use the distribution strategy when we create our neural network model. \n# Then, TensorFlow will distribute the training among the eight TPU cores \n# by creating eight different replicas of the model, one for each core.","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets  # import kaggle data files\n\n# store datasets into google cloud service\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nprint(GCS_DS_PATH) \nprint('Entries in the bucket:')\n!gsutil ls $GCS_DS_PATH # list items in the bucket \n\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# parameters set for tfrecords-jpeg-512x512 TFRecord files in the bucket\nIMAGE_SIZE = [512, 512]\nGCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'\nAUTO = tf.data.experimental.AUTOTUNE\nHEIGHT             = IMAGE_SIZE[0]\nWIDTH              = IMAGE_SIZE[1]\nEPOCHS             = 12\n# Define the batch size. This will be 16 with TPU off and 128 (=16*8) with TPU on\nBATCH_SIZE         = 16 * strategy.num_replicas_in_sync\n\n# current competition data: \"tpu-getting-started\" \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') \n\ndef count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec files\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nNUM_TRAIN_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VAL_IMAGES   = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES  = count_data_items(TEST_FILENAMES)\nSTEPS_PER_EPOCH  = NUM_TRAIN_IMAGES // BATCH_SIZE\nAUTO             = tf.data.experimental.AUTOTUNE\n\nprint('No. of training images:')\nprint (NUM_TRAIN_IMAGES)\nprint('No. of validation images:')\nprint (NUM_VAL_IMAGES)\nprint('No. of testing images:')\nprint (NUM_TEST_IMAGES)\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CLASSES = [\n    'pink primrose',        'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',      'wild geranium',         # 00-04\n    'tiger lily',           'moon orchid',               'bird of paradise', 'monkshood',      'globe thistle',         # 05-09\n    'snapdragon',           \"colt's foot\",               'king protea',      'spear thistle',  'yellow iris',           # 10-14\n    'globe-flower',         'purple coneflower',         'peruvian lily',    'balloon flower', 'giant white arum lily', # 15-19\n    'fire lily',            'pincushion flower',         'fritillary',       'red ginger',     'grape hyacinth',        # 20-24\n    'corn poppy',           'prince of wales feathers',  'stemless gentian', 'artichoke',      'sweet william',         # 25-29\n    'carnation',            'garden phlox',              'love in the mist', 'cosmos',         'alpine sea holly',      # 30-34\n    'ruby-lipped cattleya', 'cape flower',               'great masterwort', 'siam tulip',     'lenten rose',           # 35-39\n    'barberton daisy',      'daffodil',                  'sword lily',       'poinsettia',     'bolero deep blue',      # 40-44\n    'wallflower',           'marigold',                  'buttercup',        'daisy',          'common dandelion',      # 45-49\n    'petunia',              'wild pansy',                'primula',          'sunflower',      'lilac hibiscus',        # 50-54\n    'bishop of llandaff',   'gaura',                     'geranium',         'orange dahlia',  'pink-yellow dahlia',    # 55-59\n    'cautleya spicata',     'japanese anemone',          'black-eyed susan', 'silverbush',     'californian poppy',     # 60-64\n    'osteospermum',         'spring crocus',             'iris',             'windflower',     'tree poppy',            # 65-69\n    'gazania',              'azalea',                    'water lily',       'rose',           'thorn apple',           # 70-74\n    'morning glory',        'passion flower',            'lotus',            'toad lily',      'anthurium',             # 75-79\n    'frangipani',           'clematis',                  'hibiscus',         'columbine',      'desert-rose',           # 80-84\n    'tree mallow',          'magnolia',                  'cyclamen ',        'watercress',     'canna lily',            # 85-89\n    'hippeastrum ',         'bee balm',                  'pink quill',       'foxglove',       'bougainvillea',         # 90-94\n    'camellia',             'mallow',                    'mexican petunia',  'bromelia',       'blanket flower',        # 95-99\n    'trumpet creeper',      'blackberry lily',           'common tulip',     'wild rose'                                #100-103\n]    \n\ndef 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\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.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\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    # 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  # 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\n","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def data_augment(image, label):\n    # Thanks to the dataset.prefetch(AUTO)\n    # statement in the next function (below), this happens essentially\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_contrast(image, lower=0.8, upper=1.2)\n    image = tf.image.random_brightness(image, max_delta=0.1) \n    image = tf.image.random_saturation(image, lower=0.7, upper=1.3)\n\n    return image, label  \n\ndef 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    # prefetch next batch while training (autotune prefetch buffer size)\n    dataset = dataset.prefetch(AUTO) \n    return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(VALIDATION_FILENAMES,labeled=True, ordered= ordered)\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(ordered=False):  # order matters to submit predictions to Kaggle\n    dataset = load_dataset(TEST_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\n\nds_train = get_training_dataset()\nds_valid = get_validation_dataset()\nds_test = get_test_dataset()\n\nprint(\"Training:\", ds_train)\nprint (\"Validation:\", ds_valid)\nprint(\"Test:\", ds_test)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.set_printoptions(threshold=15, linewidth=80)\n\nprint(\"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())\nprint(\"Test data shapes:\")\nfor image, idnum in ds_test.take(3):\n    print(image.numpy().shape, idnum.numpy().shape)  # idnum here is the unique identifier given to the image that we'll use later when we make our submission as a csv file.\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import pyplot as plt\n\ndef batch_to_numpy_images_and_labels(databatch):\n    images, labels = databatch\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()  \n    class_labels = []\n    if numpy_labels.dtype == object: # binary string in this case, these are image ID strings\n        class_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    else:\n        for num in enumerate(numpy_labels):\n            class_labels.append(CLASSES[num[1]])\n    return numpy_images, class_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 show_images(databatch, row=6, col=8):  # row, col of subplots\n    FIGSIZE = (col*3, row*3)  # 3X3 inch per image\n    plt.figure(figsize=FIGSIZE)\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()\n\n    \n\n    \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\n    # 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        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\n\n    \n    \n    \n    \n    \n\ndef show_data_aug(image):\n    ROW=len(images)\n    COL=7  # 1 no-aug plus 6 aug images\n    plt.figure(figsize=(COL*2,ROW*2))\n    i=0\n    for image in images:\n        plt.subplot(ROW,COL,i*COL+1)\n        plt.title('Flip L/R')\n        plt.axis('off')  \n        # augmented with random flip\n        plt.imshow(tf.image.random_flip_left_right(image))       \n\n        plt.subplot(ROW,COL,i*COL+2)\n        plt.title('Resize & Crop')\n        plt.axis('off')    \n        # Pad the image with a black, 90-pixel border\n        image1 = tf.image.resize_with_crop_or_pad(\n            image, HEIGHT + 180, WIDTH + 180\n        )\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(ROW,COL,i*COL+3)\n        plt.title('Contrast')\n        plt.axis('off')\n        # augmented with contrast\n        plt.imshow(tf.image.random_contrast(image, 0.8, 1.2))  \n\n        plt.subplot(ROW,COL,i*COL+4)\n        plt.title('Brightness')\n        plt.axis('off')\n        # augmented with brightness\n        plt.imshow(tf.image.random_brightness(image, 0.1))       \n\n        plt.subplot(ROW,COL,i*COL+5)\n        plt.title('No Augmentation')\n        plt.axis('off')\n        plt.imshow(image)\n\n        plt.subplot(ROW,COL,i*COL+6)\n        plt.title('Saturation')\n        plt.axis('off')\n        # augmented with saturation\n        plt.imshow(tf.image.random_saturation(image, 0.7, 1.3))  \n\n        plt.subplot(ROW,COL,i*COL+7)\n        plt.title('Blur')\n        plt.axis('off')        \n        # ouput a value from a normal distribtion \n        rdm_filter2d = tf.random.normal([1], mean=0, stddev=1, dtype=tf.float32)              \n        if rdm_filter2d > 2.0:  # 2 stddev above mean  \n            # blur 2.5% of the images\n            # using tfa.image mean filter\n            plt.imshow(tfa.image.mean_filter2d(image, filter_shape = 3,padding='constant'))  \n        else:\n            plt.imshow(image)\n\n        i+=1\n        \n    plt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"get_training_dataset = (next(iter(ds_train.unbatch().batch(16)))) # get a batch for \nimages, _ = batch_to_numpy_images_and_labels(get_training_dataset)\n\nprint('Training Dataset')\nprint('Image Augmentation with tf.image and tfa.image')\n#one_batch = next(ds_iter)\n#display_batch_of_images(one_batch)\nshow_data_aug(images)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Visualize effects before implementing in\n# tf.keras.layers.experimental.preprocessing.Random___()\nprint('Training Dataset')\nprint('Image Augmentation with tf.keras.preprocesing.image.random')\nROW=len(images)\nCOL=4  # 1 no-augmentation plus 3 augmented images\nplt.figure(figsize=(COL*3.5,ROW*3))\ni=0\nfor image in images:\n    plt.subplot(ROW,COL,i*4+1)\n    plt.title('No Augmentation')\n    plt.axis('off')\n    plt.imshow(image)\n    \n    plt.subplot(ROW,COL,i*4+2)\n    plt.title('Shift')\n    plt.axis('off')\n    # random shift on one numpy image tensor \n    # compared to tf.keras.layers.experimental.preprocessing.RandomTranslation(...)\n    image2 = tf.keras.preprocessing.image.random_shift(\n        image, wrg=0.15, hrg=0.15, row_axis=1, col_axis=2, channel_axis=2,\n        fill_mode='constant'\n    )    \n    plt.imshow(image2) \n\n    plt.subplot(ROW,COL,i*4+3)\n    plt.title('45-degree Rotation')\n    plt.axis('off')\n    # random rotation on one numpy image tensor\n    # compared to tf.keras.layers.experimental.preprocessing.RandomRotation(...)\n    image3 = tf.keras.preprocessing.image.random_rotation(\n        image, rg=45, row_axis=1, col_axis=2, channel_axis=2, fill_mode='constant'\n    )\n    plt.imshow(image3)\n\n    plt.subplot(ROW,COL,i*4+4)\n    plt.title('Zoom')\n    plt.axis('off')\n    # random zoom on one numpy image tensor\n    # comapred to tf.keras.layers.experimental.preprocessing.RandomZoom(...)\n    image4 = tf.keras.preprocessing.image.random_zoom(\n        image, (.75, 1.0), row_axis=1, col_axis=2, channel_axis=2, fill_mode='constant'\n    )\n    plt.imshow(image4)\n    i+=1\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"explore_img_gen = tf.keras.preprocessing.image.ImageDataGenerator(\n    rotation_range=45, width_shift_range=0.15, height_shift_range=0.15,\n    brightness_range=None, zoom_range=[0.75, 1.0], fill_mode='constant', \n    horizontal_flip=True, preprocessing_function=None\n)\n\nprint('Training Dataset')\nprint('Image Augmentation with random transform method with ImageDataGenerator')\ni = 0\nROW=8  # no. of rows\nCOL=4  # no . of cols\nplt.figure(figsize=(COL*3.5,ROW*3))\nfor im in images:\n    plt.subplot(ROW,COL,i*2+1)\n    plt.title('No Augmentation')\n    plt.axis('off')\n    plt.imshow(im)\n    plt.subplot(ROW,COL,i*2+2)\n    plt.title('Transform With Image Gen.')\n    plt.axis('off')\n    plt.imshow(explore_img_gen.random_transform(im))\n    i+=1\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"R = 7     # rows of subplots/images\nC = 6     # cols of subplots/images\nB = R*C   # number of images in a batch\n\nprint('Training Images WITH Random Data Augmentation')\nshow_data_aug(next(iter(ds_train.unbatch().batch(B))))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"validation_dataset = get_validation_dataset(VALIDATION_FILENAMES)\n# you may run these lines multiple times to view different samples from the image sets\nprint('Validation Images')\nshow_images(next(iter(validation_dataset.unbatch().batch(B))), row=R, col=C)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# this needs TPU to run\n# randomly shuffles the test for visualization\nprint('Test Images - Shuffled')\nshow_images(next(iter(ds_test.shuffle(buffer_size=NUM_TEST_IMAGES).unbatch().batch(B))), \n            row=R, col=C)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# With pretrained model: DenseNet201\nwith strategy.scope():    \n    pretrained_model = efn.EfficientNetB7(\n        weights='imagenet', \n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    pretrained_model.trainable = True # transfer learning\n    model = tf.keras.Sequential([\n        pretrained_model,                   \n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), kernel_regularizer=regularizers.L2(0.001), \n            activation='softmax')\n    ])\n\n# display model summary\nmodel.summary()\n    ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    optimizer='adam', #implemet adam algorithm\n    loss = 'sparse_categorical_crossentropy', #specifies that crossentropy metric is computed between the labels and predictions\n    metrics=['sparse_categorical_accuracy'] #metric is set to use sparse categorical accuracy, which calculates how often predictions matches the integer labels\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Learning Rate Schedule Callback\n# define a fine-tuned schedule for the Learning Rate Scheduler \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    def lr(epoch, start_lr, min_lr,max_lr,rampup_epochs,sustain_epochs,\n          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        else:\n            lr = ((max_lr - min_lr)* exp_decay ** (epoch-rampup_epochs-sustain_epochs)\n                  + min_lr)\n            \n        return lr\n    return lr(epoch,start_lr,min_lr,max_lr,rampup_epochs,sustain_epochs,exp_decay)\n\n# set learning rate scheduler for callback\nlr_callback = tf.keras.callbacks.LearningRateScheduler(schedule=exponential_lr,verbose=True)\n\n# learning rate chart\nepoch_rng = [i for i in range(EPOCHS+15)] \ny = [exponential_lr(x) for x in epoch_rng]\nplt.plot(epoch_rng,y)\nplt.xlim(-1, EPOCHS+15)\n\nprint(\"Learning rate schedule: start = {:.3g}; peak = {:.3g}; end = {:.3g}\".format(y[0], max(y), y[-1]))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# EarlyStopping callback\n# Stop training when a monitored metric has stopped improving\nes_callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=3)\n# training stop safter 3 epochs if no improvement","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#we have already defined epochs in the start\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, es_callback],\n)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Create plots of loss and accuracy on the training and validation datasets\n\nacc = history.history['sparse_categorical_accuracy']\nval_acc = history.history['val_sparse_categorical_accuracy']\n\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs_range = range(1, len(history.history['loss'])+1)\n\nplt.figure(figsize=(14, 14))\nplt.subplot(2, 1, 1)\nplt.plot(epochs_range, acc, label='Training Accuracy')\nplt.plot(epochs_range, val_acc, label='Validation Accuracy')\nplt.legend(loc='lower right')\nplt.title('Training and Validation Accuracy')\nplt.xlabel('Epoch')\n\nplt.subplot(2, 1, 2)\nplt.plot(epochs_range, loss, label='Training Loss')\nplt.plot(epochs_range, val_loss, label='Validation Loss')\nplt.legend(loc='upper right')\nplt.title('Training and Validation Loss')\nplt.xlabel('Epoch')\nplt.show()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#evaluate predictions with confusion matrix\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\ncmdataset = get_validation_dataset(ordered=True)\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_VAL_IMAGES))).numpy()\ncm_probabilities = model.predict(images_ds)\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","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"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)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = get_validation_dataset()\ndataset = dataset.unbatch().batch(16)\nbatch = iter(dataset)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#Create file to submit to competitiomn\nprint('Generating submission.csv file...')\n\n# Get image ids from test set and convert to unicode\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')\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","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}