{"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 Deep Learning Competition**\n\nThe **Petals to the Metal: Flower Classification on TPU** competition challenges participants computer vision skills by tasking them with creating a convolutional neural network for image classification. The goal of this notebook is to apply what I have learned via Kaggle's **Deep Learning** and **Computer Vision** courses by building my first neural network.","metadata":{}},{"cell_type":"code","source":"# Import: Libraries\nimport re, random, math, os, warnings\nimport IPython.display as display\nimport numpy as np\nimport tensorflow as tf\nprint('Tensorflow Version: ' + tf.__version__)\n# Reproducability\ndef seed_everything(seed=0):\n    random.seed(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    os.environ['TF_DETERMINISTIC_OPS'] = '1'\n\nseed = 0\nseed_everything(seed)\nwarnings.filterwarnings(\"ignore\")","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:35:59.299503Z","iopub.execute_input":"2021-07-05T18:35:59.299906Z","iopub.status.idle":"2021-07-05T18:35:59.308485Z","shell.execute_reply.started":"2021-07-05T18:35:59.299867Z","shell.execute_reply":"2021-07-05T18:35:59.307159Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**TPU Detection and Distribution Strategy**","metadata":{}},{"cell_type":"code","source":"# TPU Detection\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect()\n    strategy = tf.distribute.TPUStrategy(tpu)\n    print('Running on TPU')\n    print('Number of Accelerators: {}'.format(strategy.num_replicas_in_sync))\nexcept ValueError:\n    strategy = tf.distribute.get_strategy()\n    print('Running on CPU / GPU')\n    print('Number of Accelerators: {}'.format(strategy.num_replicas_in_sync))","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:35:59.412803Z","iopub.execute_input":"2021-07-05T18:35:59.413209Z","iopub.status.idle":"2021-07-05T18:36:04.835606Z","shell.execute_reply.started":"2021-07-05T18:35:59.413173Z","shell.execute_reply":"2021-07-05T18:36:04.834391Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Configuration**","metadata":{}},{"cell_type":"code","source":"REPLICAS = strategy.num_replicas_in_sync\nBATCH_SIZE = 16 * REPLICAS\nWARMUP_EPOCHS = 3\nWARMUP_LEARNING_RATE = 1e-4 * REPLICAS\nEPOCHS = 30\nLEARNING_RATE = 3e-5 * REPLICAS\nHEIGHT = 512\nWIDTH = 512\nCHANNELS = 3\nN_CLASSES = 104\nES_PATIENCE = 5\nAUTO = tf.data.experimental.AUTOTUNE","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:36:04.837224Z","iopub.execute_input":"2021-07-05T18:36:04.837523Z","iopub.status.idle":"2021-07-05T18:36:04.843091Z","shell.execute_reply.started":"2021-07-05T18:36:04.837495Z","shell.execute_reply":"2021-07-05T18:36:04.842025Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Defining File Paths**","metadata":{}},{"cell_type":"code","source":"model_path = f'model_{HEIGHT}x{WIDTH}.h5'\n\nGCS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started') + f'/tfrecords-jpeg-{HEIGHT}x{WIDTH}'\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 = [\n    'pink primrose', 'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea', \n    'wild geranium', 'tiger lily', 'moon orchid', 'bird of paradise', 'monkshood', \n    'globe thistle', 'snapdragon', \"colt's foot\", 'king protea', 'spear thistle', \n    'yellow iris', 'globe-flower', 'purple coneflower', 'peruvian lily', \n    'balloon flower', 'giant white arum lily', 'fire lily', 'pincushion flower', \n    'fritillary', 'red ginger', 'grape hyacinth', 'corn poppy', \n    'prince of wales feathers', 'stemless gentian', 'artichoke', 'sweet william', \n    'carnation', 'garden phlox', 'love in the mist', 'cosmos',  'alpine sea holly', \n    'ruby-lipped cattleya', 'cape flower', 'great masterwort',  'siam tulip', \n    'lenten rose', 'barberton daisy', 'daffodil',  'sword lily', 'poinsettia', \n    'bolero deep blue',  'wallflower', 'marigold', 'buttercup', 'daisy', \n    'common dandelion', 'petunia', 'wild pansy', 'primula',  'sunflower', \n    'lilac hibiscus', 'bishop of llandaff', 'gaura',  'geranium', 'orange dahlia', \n    'pink-yellow dahlia', 'cautleya spicata',  'japanese anemone', \n    'black-eyed susan', 'silverbush', 'californian poppy',  'osteospermum', \n    'spring crocus', 'iris', 'windflower',  'tree poppy', 'gazania', 'azalea', \n    'water lily',  'rose', 'thorn apple', 'morning glory', 'passion flower',  \n    'lotus', 'toad lily', 'anthurium', 'frangipani',  'clematis', 'hibiscus', \n    'columbine', 'desert-rose', 'tree mallow', 'magnolia', 'cyclamen ', \n    'watercress',  'canna lily', 'hippeastrum ', 'bee balm', 'pink quill',  \n    'foxglove', 'bougainvillea', 'camellia', 'mallow',  'mexican petunia',  \n    'bromelia', 'blanket flower', 'trumpet creeper',  'blackberry lily', \n    'common tulip', 'wild rose']","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:36:04.84495Z","iopub.execute_input":"2021-07-05T18:36:04.845307Z","iopub.status.idle":"2021-07-05T18:36:13.731065Z","shell.execute_reply.started":"2021-07-05T18:36:04.845274Z","shell.execute_reply":"2021-07-05T18:36:13.730315Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Data Pipelining**","metadata":{}},{"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, [HEIGHT, WIDTH, 3])\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\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # 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-07-05T18:36:13.732698Z","iopub.execute_input":"2021-07-05T18:36:13.7333Z","iopub.status.idle":"2021-07-05T18:36:13.745689Z","shell.execute_reply.started":"2021-07-05T18:36:13.733245Z","shell.execute_reply":"2021-07-05T18:36:13.744633Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Data Augmentation**","metadata":{}},{"cell_type":"code","source":"def data_augment(image, label):\n    crop_size = tf.random.uniform([], int(HEIGHT*.7), HEIGHT, dtype=tf.int32)\n        \n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    image = tf.image.random_saturation(image, lower=0, upper=2)\n\n#     image = tf.image.random_saturation(image, lower=0, upper=2)\n#     image = tf.image.random_contrast(image, lower=.8, upper=2)\n#     image = tf.image.random_brightness(image, max_delta=.2)\n#     image = tf.image.adjust_gamma(image, gamma=.6)\n\n    image = tf.image.random_crop(image, size=[crop_size, crop_size, CHANNELS])\n    image = tf.image.resize(image, size=[HEIGHT, WIDTH])\n\n    return image, label","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:36:13.747102Z","iopub.execute_input":"2021-07-05T18:36:13.747705Z","iopub.status.idle":"2021-07-05T18:36:13.763801Z","shell.execute_reply.started":"2021-07-05T18:36:13.747661Z","shell.execute_reply":"2021-07-05T18:36:13.762938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Defining Dataset Functions**","metadata":{}},{"cell_type":"code","source":"def get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_training_dataset_preview(ordered=True):\n    dataset = load_dataset(TRAINING_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_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 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)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:36:13.765047Z","iopub.execute_input":"2021-07-05T18:36:13.765686Z","iopub.status.idle":"2021-07-05T18:36:13.783409Z","shell.execute_reply.started":"2021-07-05T18:36:13.76564Z","shell.execute_reply":"2021-07-05T18:36:13.782239Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Loading Data**","metadata":{}},{"cell_type":"code","source":"# Train data\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\ntrain_dataset = get_training_dataset_preview(ordered=True)\ny_train = next(iter(train_dataset.unbatch().map(lambda image, label: label).batch(NUM_TRAINING_IMAGES))).numpy()\nprint(f'Number of training images {NUM_TRAINING_IMAGES}')\n\n# Validation data\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\nvalid_dataset = get_validation_dataset(ordered=True)\ny_valid = next(iter(valid_dataset.unbatch().map(lambda image, label: label).batch(NUM_VALIDATION_IMAGES))).numpy()\nprint(f'Number of validation images {NUM_VALIDATION_IMAGES}')\n\n# Test data\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\nprint(f'Number of test images {NUM_TEST_IMAGES}')\ntest_dataset = get_test_dataset(ordered=True)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:36:13.784889Z","iopub.execute_input":"2021-07-05T18:36:13.785215Z","iopub.status.idle":"2021-07-05T18:36:27.273135Z","shell.execute_reply.started":"2021-07-05T18:36:13.785185Z","shell.execute_reply":"2021-07-05T18:36:27.271897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Data Visualization and Data Exploration**","metadata":{}},{"cell_type":"code","source":"# Import: Matplotlib\nimport matplotlib.pyplot as plt\n# Visualization utility functions\nnp.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 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 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 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()","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:36:27.275727Z","iopub.execute_input":"2021-07-05T18:36:27.276103Z","iopub.status.idle":"2021-07-05T18:36:27.294556Z","shell.execute_reply.started":"2021-07-05T18:36:27.276068Z","shell.execute_reply":"2021-07-05T18:36:27.29343Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train\ndisplay_batch_of_images(next(iter(train_dataset.unbatch().batch(20))))","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:36:27.296352Z","iopub.execute_input":"2021-07-05T18:36:27.296907Z","iopub.status.idle":"2021-07-05T18:36:30.118741Z","shell.execute_reply.started":"2021-07-05T18:36:27.296858Z","shell.execute_reply":"2021-07-05T18:36:30.110295Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Valid\ndisplay_batch_of_images(next(iter(valid_dataset.unbatch().batch(20))))","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:36:30.120888Z","iopub.execute_input":"2021-07-05T18:36:30.121413Z","iopub.status.idle":"2021-07-05T18:36:32.618755Z","shell.execute_reply.started":"2021-07-05T18:36:30.121367Z","shell.execute_reply":"2021-07-05T18:36:32.617215Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Test\ndisplay_batch_of_images(next(iter(test_dataset.unbatch().batch(20))))","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:36:32.620282Z","iopub.execute_input":"2021-07-05T18:36:32.62065Z","iopub.status.idle":"2021-07-05T18:36:35.743354Z","shell.execute_reply.started":"2021-07-05T18:36:32.620614Z","shell.execute_reply":"2021-07-05T18:36:35.742334Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Modelling: Defining the Model**","metadata":{}},{"cell_type":"code","source":"# Import: Keras, Layers\nfrom tensorflow import keras\nfrom tensorflow.keras import layers\n# Define Model\nwith strategy.scope():\n    pretrained_model = tf.keras.applications.VGG16(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3]\n    )\n    pretrained_model.trainable = False\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.Dense(len(CLASSES), activation='softmax')\n    ])","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:36:35.74464Z","iopub.execute_input":"2021-07-05T18:36:35.744962Z","iopub.status.idle":"2021-07-05T18:36:38.411012Z","shell.execute_reply.started":"2021-07-05T18:36:35.744931Z","shell.execute_reply":"2021-07-05T18:36:38.410069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Modelling: Compiling the Model, Specifying Optimizer, Loss Function, and Metrics**","metadata":{}},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:36:38.41216Z","iopub.execute_input":"2021-07-05T18:36:38.412441Z","iopub.status.idle":"2021-07-05T18:36:38.444607Z","shell.execute_reply.started":"2021-07-05T18:36:38.412415Z","shell.execute_reply":"2021-07-05T18:36:38.443612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Training: Setting the Learning Rate/Early Stopping/Callbacks**","metadata":{}},{"cell_type":"code","source":"from tensorflow.keras import callbacks\nearly_stopping = callbacks.EarlyStopping(\n    min_delta=0.001, # minimium amount of change to count as an improvement\n    patience=20, # how many epochs to wait before stopping\n    restore_best_weights=True,\n)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T18:36:38.445855Z","iopub.execute_input":"2021-07-05T18:36:38.446161Z","iopub.status.idle":"2021-07-05T18:36:38.45123Z","shell.execute_reply.started":"2021-07-05T18:36:38.446131Z","shell.execute_reply":"2021-07-05T18:36:38.450147Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Training: Fitting the Model**","metadata":{}},{"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nhistory = model.fit(x=get_training_dataset(), \n                    validation_data=get_validation_dataset(),\n                    steps_per_epoch=STEPS_PER_EPOCH,\n                    callbacks=early_stopping,\n                    epochs=5)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T19:03:45.953182Z","iopub.execute_input":"2021-07-05T19:03:45.953532Z","iopub.status.idle":"2021-07-05T19:06:11.650812Z","shell.execute_reply.started":"2021-07-05T19:03:45.953502Z","shell.execute_reply":"2021-07-05T19:06:11.649661Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Training: Plotting Loss and Metrics, Evaluating Over/Underfitting**","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nhistory_frame = pd.DataFrame(history.history)\nhistory_frame.loc[:, ['loss', 'val_loss']].plot()\nhistory_frame.loc[:, ['sparse_categorical_accuracy', 'val_sparse_categorical_accuracy']].plot();","metadata":{"execution":{"iopub.status.busy":"2021-07-05T19:07:02.961745Z","iopub.execute_input":"2021-07-05T19:07:02.962341Z","iopub.status.idle":"2021-07-05T19:07:03.383976Z","shell.execute_reply.started":"2021-07-05T19:07:02.96229Z","shell.execute_reply":"2021-07-05T19:07:03.382951Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Evaluation: Visual Validation**","metadata":{}},{"cell_type":"code","source":"# Visualize model predictions\ndef dataset_to_numpy_util(dataset, N):\n    dataset = dataset.unbatch().batch(N)\n    for images, labels in dataset:\n        numpy_images = images.numpy()\n        numpy_labels = labels.numpy()\n        break;  \n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    label = np.argmax(label, axis=-1)\n    correct = (label == correct_label)\n    return \"{} [{}{}{}]\".format(CLASSES[label], str(correct), ', shoud be ' if not correct else '',\n                                CLASSES[correct_label] if not correct else ''), correct\n\ndef display_one_flower_eval(image, title, subplot, red=False):\n    plt.subplot(subplot)\n    plt.axis('off')\n    plt.imshow(image)\n    plt.title(title, fontsize=14, color='red' if red else 'black')\n    return subplot+1\n\ndef display_9_images_with_predictions(images, predictions, labels):\n    subplot=331\n    plt.figure(figsize=(13,13))\n    for i, image in enumerate(images):\n        title, correct = title_from_label_and_target(predictions[i], labels[i])\n        subplot = display_one_flower_eval(image, title, subplot, not correct)\n        if i >= 8:\n            break;\n              \n    plt.tight_layout()\n    plt.subplots_adjust(wspace=0.1, hspace=0.1)\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-07-05T19:07:10.417468Z","iopub.execute_input":"2021-07-05T19:07:10.41785Z","iopub.status.idle":"2021-07-05T19:07:10.430205Z","shell.execute_reply.started":"2021-07-05T19:07:10.417819Z","shell.execute_reply":"2021-07-05T19:07:10.428892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Train\nx_train_samp, y_train_samp = dataset_to_numpy_util(train_dataset, 9)\ntrain_samp_preds = model.predict(x_train_samp, batch_size=9)\ndisplay_9_images_with_predictions(x_train_samp, train_samp_preds, y_train_samp)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T19:07:11.730811Z","iopub.execute_input":"2021-07-05T19:07:11.731193Z","iopub.status.idle":"2021-07-05T19:07:21.913038Z","shell.execute_reply.started":"2021-07-05T19:07:11.731158Z","shell.execute_reply":"2021-07-05T19:07:21.912073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Valid\nx_valid_samp, y_valid_samp = dataset_to_numpy_util(valid_dataset, 9)\nvalid_samp_preds = model.predict(x_valid_samp, batch_size=9)\ndisplay_9_images_with_predictions(x_valid_samp, valid_samp_preds, y_valid_samp)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T19:07:26.518948Z","iopub.execute_input":"2021-07-05T19:07:26.519569Z","iopub.status.idle":"2021-07-05T19:07:28.60825Z","shell.execute_reply.started":"2021-07-05T19:07:26.519532Z","shell.execute_reply":"2021-07-05T19:07:28.607347Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Prediction and Submission**","metadata":{}},{"cell_type":"code","source":"x_test = test_dataset.map(lambda image, idnum: image)\ntest_preds = model.predict(x_test)\ntest_preds = np.argmax(test_preds, axis=-1)","metadata":{"execution":{"iopub.status.busy":"2021-07-05T19:07:44.847021Z","iopub.execute_input":"2021-07-05T19:07:44.847628Z","iopub.status.idle":"2021-07-05T19:08:11.269301Z","shell.execute_reply.started":"2021-07-05T19:07:44.847593Z","shell.execute_reply":"2021-07-05T19:08:11.268237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_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 = pd.DataFrame(test_ids, columns=['id'])\nsubmission['label'] = test_preds\nsubmission.to_csv('submission.csv', index=False)\nsubmission.head()","metadata":{"execution":{"iopub.status.busy":"2021-07-05T19:10:26.119729Z","iopub.execute_input":"2021-07-05T19:10:26.12013Z","iopub.status.idle":"2021-07-05T19:10:28.714558Z","shell.execute_reply.started":"2021-07-05T19:10:26.120086Z","shell.execute_reply":"2021-07-05T19:10:28.713508Z"},"trusted":true},"execution_count":null,"outputs":[]}]}