{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\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\nimport os\nfor 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","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimport re\nimport math, os\nfrom kaggle_datasets import KaggleDatasets\nAUTO = tf.data.experimental.AUTOTUNE\n\nprint('Tensorflow Version {}'.format(tf.__version__))","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# TPU or GPU Detection"},{"metadata":{"trusted":true},"cell_type":"code","source":"# NEW on TPU in TensorFlow 24: shorter cross-compatible TPU/GPU/multi-GPU/cluster-GPU detection code\n\ntry: # detect TPUs\n\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print('Device:', tpu.master())\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.TPUStrategy(tpu)\n\nexcept ValueError: # detect GPUs\n    \n    #strategy = tf.distribute.MirroredStrategy() # for GPU or multi-GPU machines\n    strategy = tf.distribute.get_strategy() # default strategy that works on CPU and single GPU\n    #strategy = tf.distribute.experimental.MultiWorkerMirroredStrategy() # for clusters of multi-GPU machines\n\nprint(\"Number of accelerators: \", strategy.num_replicas_in_sync)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Directory"},{"metadata":{"trusted":true},"cell_type":"code","source":"TFrec_selected = '512x512'\nfor dir_path, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        if TFrec_selected in dir_path:\n            print(os.path.join(dir_path, filename))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path()\n\nprint(GCS_DS_PATH)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Parameters"},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_SIZE = [512,512]\nHEIGHT  =IMAGE_SIZE[0]\nWIDTH = IMAGE_SIZE[1]\nEPOCHS = 15\nBATCH_SIZE = 16*strategy.num_replicas_in_sync\nNUM_TRAIN_IMAGES = 12753 # how to calculate this using ro?\nNUM_VAL_IMAGES = 3712\nNUM_TEST_IMAGES = 7382\n\nSTEPS_PER_EPOCH = NUM_TRAIN_IMAGES//BATCH_SIZE\nAUTO = tf.data.experimental.AUTOTUNE\nTRAIN_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/train/*.tfrec')\nVAL_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/val/*.tfrec')                                   \nTEST_FILENAME = tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/test/*.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":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels =3)\n    image = tf.cast(image, tf.float32) / 255.0\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"class\": tf.io.FixedLenFeature([], tf.int64)\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\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"id\" : tf.io.FixedLenFeature([], tf.string)\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\n\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    # auto interleaves reads from multiple file\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\n\ndef get_validation_dataset(filenames):\n    dataset = load_dataset(filenames, labeled=True, ordered=False)\n    dataset = dataset.cache()\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\n    return dataset\n\ndef get_test_dataset(filenames, ordered=True):\n    dataset = load_dataset(filenames, labeled = False, ordered = ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO)\n    return dataset","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Data Augmentation\n\nWay to reduce overfitting by randomly altering the training images as they fir into the model for training, thus increasing the size of the train dataset."},{"metadata":{"trusted":true},"cell_type":"code","source":"# Preprocessing layer for Data Augmentation\n\ndata_aug_layer = tf.keras.Sequential([\n    tf.keras.layers.experimental.preprocessing.RandomRotation(0.1, fill_mode='constant'),\n    tf.keras.layers.experimental.preprocessing.RandomContrast(0.5, seed=None),\n    #tf.keras.layers.experimental.preprocessing.RandomZoom((0.2,0.3), fill_mode='nearest'),\n    #tf.keras.layers.experimental.preprocessing.RandomFlip( mode=\"horizontal_and_vertical\")\n])\n\n# Create ImageDataGenerator\nimg_gen = tf.keras.preprocessing.image.ImageDataGenerator(\nrotation_range = 30, width_shift_range=0.15, height_shift_range=0.15,\nbrightness_range=None, zoom_range=[1.0,1.25], fill_mode='constant',\nhorizontal_flip=True, preprocessing_function=None)\n\n\ndef img_gen_random_transform(image, label):\n    # apply random transform in single image\n    image = img_gen.random_transform(image)\n    return image, label\n\n\ndef data_augment(image, label):\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_contrast(image, 0.9,0.99)\n    image = tf.image.random_brightness(image, 0.5)\n    image = tf.image.random_saturation(image, 0.8,0.9)\n    return image, label","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Image Augmentation using tf.image"},{"metadata":{"trusted":true},"cell_type":"code","source":"# function to show data aug \n\ndef show_data_aug(images):\n    ROW = len(images)\n    COL = 7\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(\"rd Flip L/R\")\n        plt.axis('off')\n        plt.imshow(tf.image.random_flip_left_right(image))\n        #plt.show()\n        \n        plt.subplot(ROW, COL, i*COL+2)\n        plt.title(\"resize & rdm crop\")\n        plt.axis(\"off\")\n        image1 = tf.image.resize_with_crop_or_pad(image, HEIGHT+180,WIDTH+180)\n        image1 = tf.image.random_crop(image1, size=[*IMAGE_SIZE,3])\n        plt.imshow(image1)\n        #plt.show()\n        \n        \n        plt.subplot(ROW, COL, i*COL+3)\n        plt.title(\"rdm contrast\")\n        plt.axis(\"off\")\n        plt.imshow(tf.image.random_contrast(image, 0.90,0.99))\n        #plt.show()\n        \n        plt.subplot(ROW, COL, i*COL+4)\n        plt.title(\"rndm brightness\")\n        plt.axis(\"off\")\n        plt.imshow(tf.image.random_brightness(image, 0.5))\n        #plt.show()\n        \n        plt.subplot(ROW, COL, i*COL+5)\n        plt.title(\"No Aug\", color=\"r\")\n        plt.axis(\"off\")\n        plt.imshow(image)\n        #plt.show()\n        \n        plt.subplot(ROW, COL, i*COL+6)\n        plt.title(\"rdm saturation\")\n        plt.axis(\"off\")\n        plt.imshow(tf.image.random_saturation(image, 0.9,0.95))\n        #plt.show()\n        \n        \n        plt.subplot(ROW, COL, i*COL+7)\n        plt.title(\"rdm hue\")\n        plt.axis(\"off\")\n        plt.imshow(tf.image.random_hue(image, 0.3))\n        i+=1\n    plt.tight_layout()\n    plt.subplots_adjust(top=0.95)\n    plt.show()  \n        ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Training Dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"# trainign dataset with data augmentation\ndef get_training_dataset(filenames, augmentation=False):\n    dataset = load_dataset(filenames, labeled=True, ordered=False)\n    if augmentation:\n        dataset = dataset.map(data_augment, num_parallel_calls = AUTO)\n    dataset = dataset.repeat()\n    dataset = dataset.shuffle(buffer_size=1920)\n    dataset = dataset.batch(BATCH_SIZE)\n    \n    if augmentation:\n        dataset = dataset.map(lambda image, y: (data_aug_layer(image, training=True), y))\n        #dataset = dataset.map(data_aug_layer)\n        dataset = dataset.prefetch(AUTO)\n    return dataset\n    \n    \n#Get training dataset without any augmentation\nno_aug_train_set = get_training_dataset(TRAIN_FILENAMES, augmentation=False)\n\nprint(no_aug_train_set)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Visulaization of Images in Batch"},{"metadata":{"trusted":true},"cell_type":"code","source":"def batch_to_numpy_images_and_labels(databatch):\n    images, labels = databatch\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    \n    if numpy_labels.dtype == \"O\":\n        numpy_labels = [None for _ in enumerate(numpy_images)]\n    return numpy_images, numpy_labels\n\n    \ndef show_images(databatch, row = 6, col = 8):\n    FIGSIZE = (col*2, row*2)\n    plt.figure(figsize=FIGSIZE)\n    images, num_label = 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(Classes[num_label[j]])\n        plt.imshow(images[j])\n    plt.show()\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"no_aug_train_batch = next(iter(no_aug_train_set.unbatch().batch(16)))\n# print(no_aug_train_batch)                    \nimages, _ = batch_to_numpy_images_and_labels(no_aug_train_batch)\n\nprint(\"Image Augmentation in Train using tf.image\")\nshow_data_aug(images)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Image Augmentaton: ImageDataGenerator"},{"metadata":{"trusted":true},"cell_type":"code","source":"img_dgen = tf.keras.preprocessing.image.ImageDataGenerator(rotation_range=36,\n                                                          width_shift_range = 20,\n                                                          height_shift_range=0.2,\n                                                          horizontal_flip=True,\n                                                          fill_mode = \"constant\",\n                                                          brightness_range=None,\n                                                          zoom_range =[0.75, 1.0],\n                                                          preprocessing_function = None)\n\nprint(\"Training Dataset\")\nprint(\"Image  Augmentation by using random transformation using Image Data Generator\")\ni = 0\nROW = 8\nCOL = 4\nplt.figure(figsize=(COL*3, ROW*3.5))\nfor image in images:\n    plt.subplot(ROW, COL, i*2+1)\n    plt.title(\"No Aug\")\n    plt.axis(\"off\")\n    plt.imshow(image)\n    \n    plt.subplot(ROW, COL, i*2+2)\n    plt.title('rndm trns from img d_gene')\n    plt.axis(\"off\")\n    plt.imshow(img_dgen.random_transform(image))\n    i = i+1\nplt.show()    ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Image Augmentation: Keras Layers"},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Image Augmentation using tf.keras.preprocessing\")\n\nROW = len(images)\nCOL = 4 \nplt.figure(figsize=(COL*3, ROW*3))\ni = 0\n\nfor image in images:\n    \n    plt.subplot(ROW, COL, i*4+1)\n    plt.title(\"No Aug\", color='red')\n    plt.imshow(image)\n    plt.axis(\"off\")\n    \n    plt.subplot(ROW, COL, i*4+2)\n    plt.title(\"Rndm Zoom\")\n    img = tf.keras.preprocessing.image.random_zoom(image, (-0.3,-0.2),  fill_mode=\"reflect\")\n    plt.imshow(img)\n    plt.axis(\"off\")\n    \n    plt.subplot(ROW, COL, i*4+3)\n    plt.title(\"Rndm Shear\")\n    img = tf.keras.preprocessing.image.random_shear(image,20, fill_mode = \"nearest\")\n    plt.imshow(img)\n    plt.axis(\"off\")\n    \n    plt.subplot(ROW, COL, i*4+4)\n    plt.title(\"Rndm Rotate\")\n    img = tf.keras.preprocessing.image.random_rotation(image,20, fill_mode = \"nearest\")\n    plt.imshow(img)\n    plt.axis(\"off\")\n    \n    plt.subplot(ROW, COL, i*4+4)\n    plt.title(\"Rndm Brightness\")\n    img = tf.keras.preprocessing.image.random_brightness(image, (0.02,0.035))\n    \n    plt.imshow(img)\n    plt.axis(\"off\")\n    \n    i += 1 \nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Setting Train, Test and Validation dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"training_dataset = get_training_dataset(TRAIN_FILENAMES, augmentation=True)\nvalidation_dataset = get_validation_dataset(VAL_FILENAMES)\ntest_dataset = get_test_dataset(TEST_FILENAME)\n\n\nprint(\"Training dataset {}\".format(training_dataset))\nprint(\"Validation dataset {}\".format(validation_dataset))\nprint(\"Test dataset {}\".format(test_dataset))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# display training dataset\n\nR = 10\nC = 10\nB = R*C  #batch size\n\nprint(\"Displaying Training Dataset with Keras Layers Augmentation\")\nshow_images(next(iter(training_dataset.unbatch().batch(B))), row=R, col=C)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# displaying validation dataset\nshow_images(next(iter(validation_dataset.unbatch().batch(B))), row = R, col = C)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"#This callback will stop the training when there is no improvement in the validation loss for the 3 consecutive epochs.\nes_callback = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience = 3)\nBEST_MODEL_PATH = \"/kaggle/working/model_best.h5\"\nFILE_DIR = os.path.dirname(BEST_MODEL_PATH)\n\n# create a checkpoint to save the best trained model locally\nsave_locally = tf.saved_model.SaveOptions(experimental_io_device = '/job:localhost')\ncp_callback = tf.keras.callbacks.ModelCheckpoint(filepath = BEST_MODEL_PATH,\n                                                options = save_locally, monitor = 'val_loss', verbose=1, \n                                                save_best_only = True, save_weights_only =False, mode='min')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    pretrained_base_model = tf.keras.applications.DenseNet121 (weights = 'imagenet',\n                                                          include_top = False,\n                                                          input_shape = [*IMAGE_SIZE, 3])\n    for layer in pretrained_base_model.layers:\n        layer.trainable = False\n    \n    model = tf.keras.Sequential([\n        pretrained_base_model,\n        #tf.keras.layers.Flatten(),\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dropout(0.4),\n        tf.keras.layers.Dense(len(Classes), activation = 'softmax', kernel_regularizer = tf.keras.regularizers.L2(0.00011))\n    ])\n\n    model.summary()\n    \n    model.compile(\n    optimizer = 'adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics = ['sparse_categorical_accuracy']\n    )\n    \n    history = model.fit(\n    training_dataset,\n    steps_per_epoch = STEPS_PER_EPOCH,\n    epochs = EPOCHS,\n    validation_data = validation_dataset,\n    callbacks = [es_callback, cp_callback]\n\n    )","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Plot Accuracy and Loss curve"},{"metadata":{"trusted":true},"cell_type":"code","source":"history.history.keys()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"epoch_range = range(1, len(history.history['loss'])+1)\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\nplt.figure(figsize=(25,5))\nplt.subplot(1,2,1)\nplt.plot(epoch_range, acc, label = \"Training Accuracy\")\nplt.plot(epoch_range, val_acc, label = \"Validation Accuracy\")\nplt.legend(loc='best')\nplt.title(\"Training and Validation Accuracy\", size=15)\nplt.xlabel('Epochs')\n\nplt.subplot(1,2,2)\nplt.plot(epoch_range, loss, label = \"Training Loss\")\nplt.plot(epoch_range, val_loss, label = \"Validation Loss\")\nplt.legend(loc='best')\nplt.title(\"Training and Validation Loss\", size=15)\nplt.xlabel('Epochs')\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"List of al entries in {}: {}\".format(FILE_DIR, tf.io.gfile.listdir(FILE_DIR)))\nbest_model = tf.keras.models.load_model(BEST_MODEL_PATH)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Computing predictions\")\ntest_dataset_ds = test_dataset.map(lambda image, idnum: image)\nprobabilities = model.predict(test_dataset_ds)\n\nprediction = np.argmax(probabilities, axis=-1)\nprint(\"Predictions {}\".format(prediction))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"print(\"Generating submission file\")\ntest_ids_ds = test_dataset.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U')\n\nsubmission_df = pd.DataFrame({'id': test_ids, 'label': prediction })\nsubmission_df.to_csv('submission.csv', index = False)\n\nprint('Submitting output...... ')\n#np.savetxt('submission.csv', np.rec.fromarrays([test_ids,prediction]), fmt = ['%s', '%d'], delimiter = ',', header = 'id, label')","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}