{"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":"markdown","source":"# Flower Classification Dataset","metadata":{"id":"wA0Wr1iw_oGJ"}},{"cell_type":"markdown","source":"## Import packges","metadata":{}},{"cell_type":"code","source":"# General Libs\nfrom tensorflow import keras\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.models import Sequential, Model\nfrom tensorflow.keras.layers import GlobalAveragePooling2D, Dense, BatchNormalization, Dropout, Flatten, Conv2D, MaxPooling2D\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.optimizers import *\nfrom tensorflow.keras.initializers import *\nimport numpy as np\nimport random\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n%matplotlib inline\n\nimport os\nimport re\n\nfrom kaggle_datasets import KaggleDatasets","metadata":{"execution":{"iopub.status.busy":"2021-10-30T04:47:53.132025Z","iopub.execute_input":"2021-10-30T04:47:53.13254Z","iopub.status.idle":"2021-10-30T04:47:53.146227Z","shell.execute_reply.started":"2021-10-30T04:47:53.132491Z","shell.execute_reply":"2021-10-30T04:47:53.14545Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nimport PIL\nimport PIL.Image","metadata":{"execution":{"iopub.status.busy":"2021-10-30T04:47:53.148117Z","iopub.execute_input":"2021-10-30T04:47:53.148702Z","iopub.status.idle":"2021-10-30T04:47:53.164669Z","shell.execute_reply.started":"2021-10-30T04:47:53.14866Z","shell.execute_reply":"2021-10-30T04:47:53.163391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Load Dataset","metadata":{}},{"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)","metadata":{"execution":{"iopub.status.busy":"2021-10-30T04:47:53.166268Z","iopub.execute_input":"2021-10-30T04:47:53.166959Z","iopub.status.idle":"2021-10-30T04:47:53.17931Z","shell.execute_reply.started":"2021-10-30T04:47:53.166914Z","shell.execute_reply":"2021-10-30T04:47:53.178602Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\n\nGCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\nDprint(GCS_DS_PATH) # what do gcs paths look like?","metadata":{"execution":{"iopub.status.busy":"2021-10-30T04:47:53.181418Z","iopub.execute_input":"2021-10-30T04:47:53.182206Z","iopub.status.idle":"2021-10-30T04:48:13.266436Z","shell.execute_reply.started":"2021-10-30T04:47:53.18213Z","shell.execute_reply":"2021-10-30T04:48:13.262607Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [512, 512]\nGCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'\nAUTO = tf.data.experimental.AUTOTUNE\n\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\nCLASSES = ['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\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\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\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    # 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 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","metadata":{"execution":{"iopub.status.busy":"2021-10-30T04:48:13.267665Z","iopub.status.idle":"2021-10-30T04:48:13.268095Z"},"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    # for free on TPU. Data pipeline code is executed on the \"CPU\"\n    # part of the TPU while the TPU itself is computing gradients.\n    image = tf.image.random_flip_left_right(image)\n    #image = tf.image.random_saturation(image, 0, 2)\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    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)\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\n    # 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 = count_data_items(VALIDATION_FILENAMES)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","metadata":{"execution":{"iopub.status.busy":"2021-10-30T04:48:13.269609Z","iopub.status.idle":"2021-10-30T04:48:13.270414Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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\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":{"execution":{"iopub.status.busy":"2021-10-30T04:48:13.271834Z","iopub.status.idle":"2021-10-30T04:48:13.272613Z"},"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())","metadata":{"execution":{"iopub.status.busy":"2021-10-30T04:48:13.274009Z","iopub.status.idle":"2021-10-30T04:48:13.274724Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"seed = random.randint(1, 1000)\nlearning_rate = 0.0001","metadata":{"execution":{"iopub.status.busy":"2021-10-30T04:48:13.275975Z","iopub.status.idle":"2021-10-30T04:48:13.276666Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Creating a simple CNN Model","metadata":{"id":"kSjVIWfkvQaL"}},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Conv2D(20, kernel_size=(3, 3),\n                 activation='relu',\n                 input_shape=(im_shape[0],im_shape[1],3)))\n\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Conv2D(40, kernel_size=(3,3), activation='relu'))\nmodel.add(Flatten())\nmodel.add(Dense(100, activation='relu'))\nmodel.add(Dropout(0.2))\nmodel.add(Dense(num_classes, activation='softmax'))\nmodel.summary()\n\n# Compila o modelo\nmodel.compile(loss='categorical_crossentropy',\n              optimizer=Adam(),\n              metrics=['accuracy'])","metadata":{"id":"MROFFdCavBn0","execution":{"iopub.status.busy":"2021-10-30T04:48:13.278079Z","iopub.status.idle":"2021-10-30T04:48:13.278772Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"epochs = 80\n\n#Callback to save the best model\ncallbacks_list = [\n    keras.callbacks.ModelCheckpoint(\n        filepath='model.h5',\n        monitor='val_loss', save_best_only=True, verbose=1),\n    keras.callbacks.EarlyStopping(monitor='val_loss', patience=10,verbose=1)\n]\n\n#Training\nhistory = model.fit(\n        train_generator,\n        steps_per_epoch= ds_train // BATCH_SIZE,\n        epochs= epochs,\n        callbacks = callbacks_list,\n        validation_data= validation_generator,\n        verbose = 1,\n        validation_steps= ds_valid // BATCH_SIZE)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Training curves\nimport matplotlib.pyplot as plt\n\nhistory_dict = history.history\nloss_values = history_dict['loss']\nval_loss_values = history_dict['val_loss']\n\nepochs_x = range(1, len(loss_values) + 1)\nplt.figure(figsize=(10,10))\nplt.subplot(2,1,1)\nplt.plot(epochs_x, loss_values, 'bo', label='Training loss')\nplt.plot(epochs_x, val_loss_values, 'b', label='Validation loss')\nplt.title('Training and validation Loss and Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.subplot(2,1,2)\nacc_values = history_dict['accuracy']\nval_acc_values = history_dict['val_accuracy']\nplt.plot(epochs_x, acc_values, 'bo', label='Training acc')\nplt.plot(epochs_x, val_acc_values, 'b', label='Validation acc')\n#plt.title('Training and validation accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Acc')\nplt.legend()\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Evaluating the model","metadata":{}},{"cell_type":"code","source":"# Load the best saved model\nfrom tensorflow.keras.models import load_model\n\nmodel = load_model('model.h5')","metadata":{"execution":{"iopub.status.busy":"2021-10-30T04:48:13.280024Z","iopub.status.idle":"2021-10-30T04:48:13.280708Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Using the validation dataset\nscore = model.evaluate_generator(validation_generator)\nprint('Val loss:', score[0])\nprint('Val accuracy:', score[1])\n\n","metadata":{"id":"OzmBvqTPFVo-","outputId":"88011256-19ed-4abf-820f-0999bf8475d4","execution":{"iopub.status.busy":"2021-10-30T04:48:13.281975Z","iopub.status.idle":"2021-10-30T04:48:13.282661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Using the test dataset\nscore = model.evaluate_generator(test_generator)\nprint('Test loss:', score[0])\nprint('Test accuracy:', score[1])","metadata":{"id":"wNXNy3vViRZH","outputId":"474e2452-5948-45e5-c6dd-cc7d7204c039","execution":{"iopub.status.busy":"2021-10-30T04:48:13.283997Z","iopub.status.idle":"2021-10-30T04:48:13.284679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import itertools\n\n#Plot the confusion matrix. Set Normalize = True/False\ndef plot_confusion_matrix(cm, classes, normalize=True, title='Confusion matrix', cmap=plt.cm.Blues):\n    \"\"\"\n    This function prints and plots the confusion matrix.\n    Normalization can be applied by setting `normalize=True`.\n    \"\"\"\n    plt.figure(figsize=(10,10))\n    plt.imshow(cm, interpolation='nearest', cmap=cmap)\n    plt.title(title)\n    plt.colorbar()\n    tick_marks = np.arange(len(classes))\n    plt.xticks(tick_marks, classes, rotation=45)\n    plt.yticks(tick_marks, classes)\n    if normalize:\n        cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n        cm = np.around(cm, decimals=2)\n        cm[np.isnan(cm)] = 0.0\n    thresh = cm.max() / 2.\n    for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n        plt.text(j, i, cm[i, j],\n                 horizontalalignment=\"center\",\n                 color=\"white\" if cm[i, j] > thresh else \"black\")\n    plt.tight_layout()\n    plt.ylabel('True label')\n    plt.xlabel('Predicted label')","metadata":{"id":"nIefwCkLRuCS","outputId":"e10e6f84-9a42-4b9a-a94c-d5c022f8d09a","execution":{"iopub.status.busy":"2021-10-30T04:48:13.285979Z","iopub.status.idle":"2021-10-30T04:48:13.286663Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Some reports\nfrom sklearn.metrics import classification_report, confusion_matrix\nimport numpy as np\n\n#On test dataset\nY_pred = model.predict_generator(test_generator)\ny_pred = np.argmax(Y_pred, axis=1)\ntarget_names = classes\n\n#Confution Matrix\ncm = confusion_matrix(test_generator.classes, y_pred)\nplot_confusion_matrix(cm, target_names, normalize=False, title='Confusion Matrix')\n\n#Classification Report\nprint('Classification Report')\nprint(classification_report(test_generator.classes, y_pred, target_names=target_names))\n","metadata":{"id":"-S7L2wOMiWY1","outputId":"9db70d71-de30-4968-a900-d24b94339321","execution":{"iopub.status.busy":"2021-10-30T04:48:13.287765Z","iopub.status.idle":"2021-10-30T04:48:13.288215Z"},"trusted":true},"execution_count":null,"outputs":[]}]}