{"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":"import math, re, os\nimport numpy as np\nimport tensorflow as tf","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-12-03T01:59:12.264346Z","iopub.execute_input":"2021-12-03T01:59:12.264706Z","iopub.status.idle":"2021-12-03T01:59:18.107845Z","shell.execute_reply.started":"2021-12-03T01:59:12.264607Z","shell.execute_reply":"2021-12-03T01:59:18.106840Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Distribution Strategy**","metadata":{}},{"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver() \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() ","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:18.109778Z","iopub.execute_input":"2021-12-03T01:59:18.110136Z","iopub.status.idle":"2021-12-03T01:59:23.817299Z","shell.execute_reply.started":"2021-12-03T01:59:18.110064Z","shell.execute_reply":"2021-12-03T01:59:23.816498Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Load Data**","metadata":{}},{"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\n\npath = KaggleDatasets().get_gcs_path('tpu-getting-started')","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:23.818284Z","iopub.execute_input":"2021-12-03T01:59:23.818502Z","iopub.status.idle":"2021-12-03T01:59:24.373278Z","shell.execute_reply.started":"2021-12-03T01:59:23.818478Z","shell.execute_reply":"2021-12-03T01:59:24.372421Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_size = [512, 512]\ngcsP = path + '/tfrecords-jpeg-512x512'\nauto = tf.data.experimental.AUTOTUNE\n\ntrainingFiles = tf.io.gfile.glob(gcsP + '/train/*.tfrec')\nvalidationFiles = tf.io.gfile.glob(gcsP + '/val/*.tfrec')\ntestFiles = tf.io.gfile.glob(gcsP + '/test/*.tfrec') \n\nflowers = ['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',        'swee',         # 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","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:24.375830Z","iopub.execute_input":"2021-12-03T01:59:24.376439Z","iopub.status.idle":"2021-12-03T01:59:24.650616Z","shell.execute_reply.started":"2021-12-03T01:59:24.376390Z","shell.execute_reply":"2021-12-03T01:59:24.649548Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Helper Methods**","metadata":{}},{"cell_type":"code","source":"# This method converts image to floats and reshapes to a size needed for TPU\ndef decode_image(data):\n    image = tf.image.decode_jpeg(data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0\n    image = tf.reshape(image, [*image_size, 3])\n    return image\n\n# This method returns a dataset of (image, label) pairs \ndef read_labeled_tfrecord(single):\n    labeledTfRecordFormat = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"class\": tf.io.FixedLenFeature([], tf.int64),\n    }\n    single = tf.io.parse_single_example(single, labeledTfRecordFormat)\n    image = decode_image(single['image'])\n    label = tf.cast(single['class'], tf.int32)\n    return image, label\n\n# This method returns a data of just images without the label like above\ndef read_unlabeled_tfrecord(single):\n    unlabledTfRecordFormat = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"id\": tf.io.FixedLenFeature([], tf.string),\n    }\n    single = tf.io.parse_single_example(single, unlabledTfRecordFormat)\n    image = decode_image(single['image'])\n    idnum = single['id']\n    return image, idnum\n\n# This method returns a dataset of (image, label) pairs if labeled=True or (image, ID) pairs if labeled=False\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # We ignore order because data will be shuffled anyways, also helps with speed\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False\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","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:24.652874Z","iopub.execute_input":"2021-12-03T01:59:24.653164Z","iopub.status.idle":"2021-12-03T01:59:24.665506Z","shell.execute_reply.started":"2021-12-03T01:59:24.653132Z","shell.execute_reply":"2021-12-03T01:59:24.664431Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Pipelines**","metadata":{}},{"cell_type":"code","source":"# This method augments the data so there are more data points for training\ndef data_augment(image, label):\n    image = tf.image.random_flip_left_right(image)\n    return image, label   \n\n# This method gets the training data ready for the model\ndef get_training_dataset():\n    dataset = load_dataset(trainingFiles, labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=auto)\n    dataset = dataset.repeat()\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(batchSize)\n    dataset = dataset.prefetch(auto)\n    return dataset\n\n# This method gets the validation data ready for the model\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(validationFiles, labeled=True, ordered=ordered)\n    dataset = dataset.batch(batchSize)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(auto)\n    return dataset\n\n# This method gets the testing data ready for the model\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(testFiles, labeled=False, ordered=ordered)\n    dataset = dataset.batch(batchSize)\n    dataset = dataset.prefetch(auto)\n    return dataset\n\n# This method returns the number of data points within training, validation, and testing\ndef count_data_items(filenames):\n    x = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(x)\n\nnumTraining = count_data_items(trainingFiles)\nnumValidation = count_data_items(validationFiles)\nnumTest = count_data_items(testFiles)\n","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:24.666706Z","iopub.execute_input":"2021-12-03T01:59:24.666929Z","iopub.status.idle":"2021-12-03T01:59:24.686974Z","shell.execute_reply.started":"2021-12-03T01:59:24.666904Z","shell.execute_reply":"2021-12-03T01:59:24.686288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"batchSize = 16 * strategy.num_replicas_in_sync\n\nds_train = get_training_dataset()\nds_valid = get_validation_dataset()\nds_test = get_test_dataset()","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:24.688129Z","iopub.execute_input":"2021-12-03T01:59:24.688692Z","iopub.status.idle":"2021-12-03T01:59:25.025747Z","shell.execute_reply.started":"2021-12-03T01:59:24.688656Z","shell.execute_reply":"2021-12-03T01:59:25.024779Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Here we are displaying the shape of the training data\nnp.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-12-03T01:59:25.026863Z","iopub.execute_input":"2021-12-03T01:59:25.027110Z","iopub.status.idle":"2021-12-03T01:59:29.935333Z","shell.execute_reply.started":"2021-12-03T01:59:25.027081Z","shell.execute_reply":"2021-12-03T01:59:29.934617Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Here we are displaying the shape of the testing data\nprint(\"Test data shapes:\")\nfor image, idnum in ds_test.take(3):\n    print(image.numpy().shape, idnum.numpy().shape)\nprint(\"Test data IDs:\", idnum.numpy().astype('U')) # U=unicode string","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:29.936497Z","iopub.execute_input":"2021-12-03T01:59:29.936846Z","iopub.status.idle":"2021-12-03T01:59:33.212925Z","shell.execute_reply.started":"2021-12-03T01:59:29.936818Z","shell.execute_reply":"2021-12-03T01:59:33.212234Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Display Data**","metadata":{}},{"cell_type":"code","source":"from matplotlib import pyplot as plt\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:               \n        numpy_labels = [None for _ in enumerate(numpy_images)]\n        \n    return numpy_images, numpy_labels\n\ndef title_from_label_and_target(label, correct_label):\n    if correct_label is None:\n        return flowers[label], True\n    correct = (label == correct_label)\n    \n    return \"{} [{}{}{}]\".format(flowers[label], 'OK' if correct else 'NO', u\"\\u2192\" if not correct else '',\n                                flowers[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    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n    \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 flowers[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\ndef display_training_curves(training, validation, title, subplot):\n    if subplot%10==1: # set up the subplots on the first call\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    #ax.set_ylim(0.28,1.05)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:33.216140Z","iopub.execute_input":"2021-12-03T01:59:33.216778Z","iopub.status.idle":"2021-12-03T01:59:33.237855Z","shell.execute_reply.started":"2021-12-03T01:59:33.216733Z","shell.execute_reply":"2021-12-03T01:59:33.236896Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Here we are displaying a batch of 20 images\nds_iter = iter(ds_train.unbatch().batch(20))\none_batch = next(ds_iter)\ndisplay_batch_of_images(one_batch)","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:33.239245Z","iopub.execute_input":"2021-12-03T01:59:33.239481Z","iopub.status.idle":"2021-12-03T01:59:37.355329Z","shell.execute_reply.started":"2021-12-03T01:59:33.239452Z","shell.execute_reply":"2021-12-03T01:59:37.354595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Define Model**","metadata":{}},{"cell_type":"code","source":"numEpochs = 20\n\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    \n    model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(flowers), activation='relu'),\n        tf.keras.layers.Dropout(0.00625),\n        tf.keras.layers.Dense(len(flowers), activation='relu'),\n        tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.Flatten(),\n        tf.keras.layers.Dense(len(flowers), activation='relu'),\n        tf.keras.layers.Dropout(0.003125),\n        tf.keras.layers.Dense(len(flowers), activation='softmax')\n    ])","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:37.356471Z","iopub.execute_input":"2021-12-03T01:59:37.356861Z","iopub.status.idle":"2021-12-03T01:59:40.553591Z","shell.execute_reply.started":"2021-12-03T01:59:37.356831Z","shell.execute_reply":"2021-12-03T01:59:40.552671Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n)\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:40.554921Z","iopub.execute_input":"2021-12-03T01:59:40.555211Z","iopub.status.idle":"2021-12-03T01:59:40.601408Z","shell.execute_reply.started":"2021-12-03T01:59:40.555175Z","shell.execute_reply":"2021-12-03T01:59:40.600499Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Training**","metadata":{}},{"cell_type":"code","source":"# Here we are establishing the learning rate and how it will change\ndef exponential_lr(epoch,\n                   startLearningRate = 0.0001, minimumLearningRate = 0.0001, maxLearningRate = 0.0007,\n                   rampup_epochs = 20, sustain_epochs = 0,\n                   exp_decay = 0.8):\n\n    def lr(epoch, startLearningRate, minimumLearningRate, maxLearningRate, rampup_epochs, sustain_epochs, exp_decay):\n        if epoch < rampup_epochs:\n            lr = ((maxLearningRate - startLearningRate) /\n                  rampup_epochs * epoch + startLearningRate)\n        elif epoch < rampup_epochs + sustain_epochs:\n            lr = maxLearningRate\n        else:\n            lr = ((maxLearningRate - minimumLearningRate) *\n                  exp_decay**(epoch - rampup_epochs - sustain_epochs) +\n                  minimumLearningRate)\n        return lr\n    return lr(epoch,\n              startLearningRate,\n              minimumLearningRate,\n              maxLearningRate,\n              rampup_epochs,\n              sustain_epochs,\n              exp_decay)\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True)\n","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:40.602884Z","iopub.execute_input":"2021-12-03T01:59:40.603894Z","iopub.status.idle":"2021-12-03T01:59:40.613529Z","shell.execute_reply.started":"2021-12-03T01:59:40.603851Z","shell.execute_reply":"2021-12-03T01:59:40.612419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Fit Model**","metadata":{}},{"cell_type":"code","source":"numEpochs = 20\nnumSteps = numTraining // batchSize\n\nhistory = model.fit(\n    ds_train,\n    validation_data=ds_valid,\n    epochs=numEpochs,\n    steps_per_epoch=numSteps,\n    callbacks=[lr_callback],\n)","metadata":{"execution":{"iopub.status.busy":"2021-12-03T01:59:40.615636Z","iopub.execute_input":"2021-12-03T01:59:40.616083Z","iopub.status.idle":"2021-12-03T02:07:46.850535Z","shell.execute_reply.started":"2021-12-03T01:59:40.616039Z","shell.execute_reply":"2021-12-03T02:07:46.849595Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Here we are displaying the training curves for visuals\ndisplay_training_curves(\n    history.history['loss'],\n    history.history['val_loss'],\n    'loss',\n    211,\n)\ndisplay_training_curves(\n    history.history['sparse_categorical_accuracy'],\n    history.history['val_sparse_categorical_accuracy'],\n    'accuracy',\n    212,\n)","metadata":{"execution":{"iopub.status.busy":"2021-12-03T02:07:46.852152Z","iopub.execute_input":"2021-12-03T02:07:46.853235Z","iopub.status.idle":"2021-12-03T02:07:47.430869Z","shell.execute_reply.started":"2021-12-03T02:07:46.853190Z","shell.execute_reply":"2021-12-03T02:07:47.429813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Evaluation**","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\n\n# Displays the confusion matrix with the F1, precision, and recall scores\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(flowers)))\n    ax.set_xticklabels(flowers, fontdict={'fontsize': 7})\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"left\", rotation_mode=\"anchor\")\n    ax.set_yticks(range(len(flowers)))\n    ax.set_yticklabels(flowers, 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\n# Displays the training curves, used to visualize loss and accuracy of training and validation\ndef display_training_curves(training, validation, title, subplot):\n    if subplot%10==1:\n        plt.subplots(figsize=(10,10), facecolor='#F0F0F0')\n        plt.tight_layout()\n    ax = plt.subplot(subplot)\n    ax.set_facecolor('#F8F8F8')\n    ax.plot(training)\n    ax.plot(validation)\n    ax.set_title('model '+ title)\n    ax.set_ylabel(title)\n    ax.set_xlabel('epoch')\n    ax.legend(['train', 'valid.'])","metadata":{"execution":{"iopub.status.busy":"2021-12-03T02:07:47.432348Z","iopub.execute_input":"2021-12-03T02:07:47.432684Z","iopub.status.idle":"2021-12-03T02:07:48.177755Z","shell.execute_reply.started":"2021-12-03T02:07:47.432641Z","shell.execute_reply":"2021-12-03T02:07:48.177107Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Confusion Matrix**","metadata":{}},{"cell_type":"code","source":"# Creating the confusion matrix\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(numValidation))).numpy()\ncm_probabilities = model.predict(images_ds)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\n\nlabels = range(len(flowers))\ncmat = confusion_matrix(\n    cm_correct_labels,\n    cm_predictions,\n    labels=labels,\n)\ncmat = (cmat.T / cmat.sum(axis=1)).T # normalize","metadata":{"execution":{"iopub.status.busy":"2021-12-03T02:07:48.179022Z","iopub.execute_input":"2021-12-03T02:07:48.179734Z","iopub.status.idle":"2021-12-03T02:08:01.229500Z","shell.execute_reply.started":"2021-12-03T02:07:48.179693Z","shell.execute_reply":"2021-12-03T02:08:01.228536Z"},"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":{"execution":{"iopub.status.busy":"2021-12-03T02:08:01.230965Z","iopub.execute_input":"2021-12-03T02:08:01.231512Z","iopub.status.idle":"2021-12-03T02:08:06.437565Z","shell.execute_reply.started":"2021-12-03T02:08:01.231476Z","shell.execute_reply":"2021-12-03T02:08:06.436533Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Visual**","metadata":{}},{"cell_type":"code","source":"# Here we are displaying a grouping of data images that and the models predictions - right and wrong \ndataset = get_validation_dataset()\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)\n\nimages, labels = next(batch)\nprobabilities = model.predict(images)\npredictions = np.argmax(probabilities, axis=-1)\ndisplay_batch_of_images((images, labels), predictions)","metadata":{"execution":{"iopub.status.busy":"2021-12-03T02:08:06.439143Z","iopub.execute_input":"2021-12-03T02:08:06.439379Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Predictions**","metadata":{}},{"cell_type":"code","source":"# Here we are calculating predictions\ntest_ds = get_test_dataset(ordered=True)\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":"\n# Here we are creating the submission file for the competition \ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(numTest))).numpy().astype('U')\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)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}