{"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":"Reference Notebooks used : \n\nhttps://www.kaggle.com/code/ryanholbrook/create-your-first-submission/notebook\n\n\nhttps://colab.research.google.com/notebooks/tpu.ipynb","metadata":{}},{"cell_type":"code","source":"import numpy as np \nimport pandas as pd \n\nimport tensorflow as tf","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:08.535466Z","iopub.execute_input":"2022-06-03T04:15:08.535787Z","iopub.status.idle":"2022-06-03T04:15:08.539957Z","shell.execute_reply.started":"2022-06-03T04:15:08.535754Z","shell.execute_reply":"2022-06-03T04:15:08.538904Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(tf.__version__)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:08.605438Z","iopub.execute_input":"2022-06-03T04:15:08.606192Z","iopub.status.idle":"2022-06-03T04:15:08.610966Z","shell.execute_reply.started":"2022-06-03T04:15:08.606151Z","shell.execute_reply":"2022-06-03T04:15:08.610074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import pandas as pd \nimport numpy as np\nimport re\n\nimport matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:08.6643Z","iopub.execute_input":"2022-06-03T04:15:08.665185Z","iopub.status.idle":"2022-06-03T04:15:08.670159Z","shell.execute_reply.started":"2022-06-03T04:15:08.665134Z","shell.execute_reply":"2022-06-03T04:15:08.669411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"try : \n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print(\"Running on  TPU \" , tpu.cluster_spec().as_dict()['worker'])\nexcept ValueError : \n    raise BaseException (\"Not Connected to TPU\")\n\ntf.config.experimental_connect_to_cluster(tpu)\ntf.tpu.experimental.initialize_tpu_system(tpu)\ntpu_stratergy = tf.distribute.experimental.TPUStrategy(tpu)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:08.726626Z","iopub.execute_input":"2022-06-03T04:15:08.727119Z","iopub.status.idle":"2022-06-03T04:15:14.759982Z","shell.execute_reply.started":"2022-06-03T04:15:08.727072Z","shell.execute_reply":"2022-06-03T04:15:14.758939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# used for optimising the data feyching \nAUTO = tf.data.experimental.AUTOTUNE\nIMAGE_SIZE = [512 , 512 ]\nBATCH_SIZE = 16 * tpu_stratergy.num_replicas_in_sync","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:14.762388Z","iopub.execute_input":"2022-06-03T04:15:14.763186Z","iopub.status.idle":"2022-06-03T04:15:14.76907Z","shell.execute_reply.started":"2022-06-03T04:15:14.763134Z","shell.execute_reply":"2022-06-03T04:15:14.768026Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"#colab-346513_147341481926_tpu-getting-started is my personal GCS storage. Not accessible over public ;) \nTRAIN  = 'gs://colab-346513_147341481926_tpu-getting-started/tfrecords-jpeg-512x512/train/*.tfrec'\nTEST  = 'gs://colab-346513_147341481926_tpu-getting-started/tfrecords-jpeg-512x512/test/*.tfrec'\nVAL  = 'gs://colab-346513_147341481926_tpu-getting-started/tfrecords-jpeg-512x512/val/*.tfrec'","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:14.771197Z","iopub.execute_input":"2022-06-03T04:15:14.771872Z","iopub.status.idle":"2022-06-03T04:15:14.786223Z","shell.execute_reply.started":"2022-06-03T04:15:14.77173Z","shell.execute_reply":"2022-06-03T04:15:14.785456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAINING_FILENAMES = tf.io.gfile.glob(TRAIN)\nTEST_FILENAMES = tf.io.gfile.glob(TEST)\nVALIDATION_FILENAMES = tf.io.gfile.glob(VAL)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:14.7891Z","iopub.execute_input":"2022-06-03T04:15:14.789574Z","iopub.status.idle":"2022-06-03T04:15:15.04222Z","shell.execute_reply.started":"2022-06-03T04:15:14.789517Z","shell.execute_reply":"2022-06-03T04:15:15.041097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Classes can be retrieved based on reading / analysing all TFR records. Here this was provided as reference.\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']","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:15.043843Z","iopub.execute_input":"2022-06-03T04:15:15.044201Z","iopub.status.idle":"2022-06-03T04:15:15.056333Z","shell.execute_reply.started":"2022-06-03T04:15:15.044155Z","shell.execute_reply":"2022-06-03T04:15:15.055115Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# For converting image to np array so that it can be handled by TPUs\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","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:15.057652Z","iopub.execute_input":"2022-06-03T04:15:15.058346Z","iopub.status.idle":"2022-06-03T04:15:15.078472Z","shell.execute_reply.started":"2022-06-03T04:15:15.058311Z","shell.execute_reply":"2022-06-03T04:15:15.077375Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# a way to read TFR  records\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    }\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)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:15.080132Z","iopub.execute_input":"2022-06-03T04:15:15.080437Z","iopub.status.idle":"2022-06-03T04:15:15.0958Z","shell.execute_reply.started":"2022-06-03T04:15:15.080403Z","shell.execute_reply":"2022-06-03T04:15:15.094725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# a way to read TFR  records\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","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:15.097843Z","iopub.execute_input":"2022-06-03T04:15:15.098374Z","iopub.status.idle":"2022-06-03T04:15:15.115509Z","shell.execute_reply.started":"2022-06-03T04:15:15.098321Z","shell.execute_reply":"2022-06-03T04:15:15.114413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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":"2022-06-03T04:15:15.117333Z","iopub.execute_input":"2022-06-03T04:15:15.117926Z","iopub.status.idle":"2022-06-03T04:15:15.130488Z","shell.execute_reply.started":"2022-06-03T04:15:15.117887Z","shell.execute_reply":"2022-06-03T04:15:15.128997Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import re\n\ndef 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    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":"2022-06-03T04:15:15.13429Z","iopub.execute_input":"2022-06-03T04:15:15.135198Z","iopub.status.idle":"2022-06-03T04:15:15.154617Z","shell.execute_reply.started":"2022-06-03T04:15:15.135118Z","shell.execute_reply":"2022-06-03T04:15:15.1532Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"training_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()\ntest_dataset = get_test_dataset(ordered=True)\n","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:15.156225Z","iopub.execute_input":"2022-06-03T04:15:15.156633Z","iopub.status.idle":"2022-06-03T04:15:15.339982Z","shell.execute_reply.started":"2022-06-03T04:15:15.156587Z","shell.execute_reply":"2022-06-03T04:15:15.3388Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\n\ndef display_one_flower(image, title, subplot, color):\n  plt.subplot(subplot)\n  plt.axis('off')\n  plt.imshow(image)\n  plt.title(title, fontsize=16, color=color)\n  \n# If model is provided, use it to generate predictions.\ndef display_nine_flowers(images, titles, title_colors=None):\n  subplot = 331\n  plt.figure(figsize=(20,20))\n  for i in range(9):\n    color = 'black' if title_colors is None else title_colors[i]\n    display_one_flower(images[i], titles[i], subplot+i, color)\n  plt.tight_layout()\n  plt.subplots_adjust(wspace=0.1, hspace=0.1)\n  plt.show()\n\ndef get_dataset_iterator(dataset, n_examples):\n  return dataset.unbatch().batch(n_examples).as_numpy_iterator()\n\ntraining_viz_iterator = get_dataset_iterator(training_dataset, 9)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:15.3419Z","iopub.execute_input":"2022-06-03T04:15:15.342227Z","iopub.status.idle":"2022-06-03T04:15:15.367001Z","shell.execute_reply.started":"2022-06-03T04:15:15.342185Z","shell.execute_reply":"2022-06-03T04:15:15.36586Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Re-run this cell to show a new batch of images\nimages, classes = next(training_viz_iterator)\nlabels = [CLASSES[idx] for idx in classes]\ndisplay_nine_flowers(images, labels)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:15.370132Z","iopub.execute_input":"2022-06-03T04:15:15.370698Z","iopub.status.idle":"2022-06-03T04:15:20.31304Z","shell.execute_reply.started":"2022-06-03T04:15:15.370657Z","shell.execute_reply":"2022-06-03T04:15:20.312076Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def create_model():\n  pretrained_model = tf.keras.applications.ResNet50(input_shape=[*IMAGE_SIZE, 3], include_top=False)\n  pretrained_model.trainable = True\n  model = tf.keras.Sequential([\n    pretrained_model,\n    tf.keras.layers.GlobalAveragePooling2D(),\n    tf.keras.layers.BatchNormalization(),\n    tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n  ])\n  model.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['accuracy']\n  )\n  return model\n\n","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:20.314428Z","iopub.execute_input":"2022-06-03T04:15:20.314724Z","iopub.status.idle":"2022-06-03T04:15:20.320742Z","shell.execute_reply.started":"2022-06-03T04:15:20.314694Z","shell.execute_reply":"2022-06-03T04:15:20.320112Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with tpu_stratergy.scope(): # creating the model in the TPUStrategy scope means we will train the model on the TPU\n  model = create_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:20.321772Z","iopub.execute_input":"2022-06-03T04:15:20.322595Z","iopub.status.idle":"2022-06-03T04:15:33.811483Z","shell.execute_reply.started":"2022-06-03T04:15:20.322553Z","shell.execute_reply":"2022-06-03T04:15:33.810451Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"EPOCHS = 30\n\nstart_lr = 0.00001\nmin_lr = 0.00001\nmax_lr = 0.00005 * tpu_stratergy.num_replicas_in_sync\nrampup_epochs = 5\nsustain_epochs = 0\nexp_decay = .8\n\ndef lrfn(epoch):\n  if epoch < rampup_epochs:\n    return (max_lr - start_lr)/rampup_epochs * epoch + start_lr\n  elif epoch < rampup_epochs + sustain_epochs:\n    return max_lr\n  else:\n    return (max_lr - min_lr) * exp_decay**(epoch-rampup_epochs-sustain_epochs) + min_lr\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(lambda epoch: lrfn(epoch), verbose=True)\nearly_stop = tf.keras.callbacks.EarlyStopping(monitor = 'val_accuracy' , patience = 5 , restore_best_weights=True )\n\nrang = np.arange(EPOCHS)\ny = [lrfn(x) for x in rang]\nplt.plot(rang, y)\nprint('Learning rate per epoch:')","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:33.813013Z","iopub.execute_input":"2022-06-03T04:15:33.813325Z","iopub.status.idle":"2022-06-03T04:15:34.025293Z","shell.execute_reply.started":"2022-06-03T04:15:33.813285Z","shell.execute_reply":"2022-06-03T04:15:34.024039Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nn_train = count_data_items(TRAINING_FILENAMES)\nn_valid = count_data_items(VALIDATION_FILENAMES)\ntrain_steps = count_data_items(TRAINING_FILENAMES) // BATCH_SIZE\nprint(\"TRAINING IMAGES: \", n_train, \", STEPS PER EPOCH: \", train_steps)\nprint(\"VALIDATION IMAGES: \", n_valid)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:34.026732Z","iopub.execute_input":"2022-06-03T04:15:34.026963Z","iopub.status.idle":"2022-06-03T04:15:34.035282Z","shell.execute_reply.started":"2022-06-03T04:15:34.026936Z","shell.execute_reply":"2022-06-03T04:15:34.034321Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(training_dataset, validation_data=validation_dataset,\n                    steps_per_epoch=train_steps, epochs=EPOCHS, callbacks=[lr_callback , early_stop])\n\nfinal_accuracy = history.history[\"val_accuracy\"][-5:]\nprint(\"FINAL ACCURACY MEAN-5: \", np.mean(final_accuracy))","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:15:34.036641Z","iopub.execute_input":"2022-06-03T04:15:34.036861Z","iopub.status.idle":"2022-06-03T04:27:59.56338Z","shell.execute_reply.started":"2022-06-03T04:15:34.036835Z","shell.execute_reply":"2022-06-03T04:27:59.562369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def display_training_curves(training, validation, title, subplot):\n    ax = plt.subplot(subplot)\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(['training', 'validation']) \n\nplt.subplots(figsize=(10,10))\nplt.tight_layout()\ndisplay_training_curves(history.history['accuracy'], history.history['val_accuracy'], 'accuracy', 211)\ndisplay_training_curves(history.history['loss'], history.history['val_loss'], 'loss', 212)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:27:59.564833Z","iopub.execute_input":"2022-06-03T04:27:59.565083Z","iopub.status.idle":"2022-06-03T04:28:00.053595Z","shell.execute_reply.started":"2022-06-03T04:27:59.565052Z","shell.execute_reply":"2022-06-03T04:28:00.05268Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def flower_title(label, prediction):\n    prediction_idx = np.argmax(prediction, axis=-1)\n    if label == prediction_idx:\n        return f'{CLASSES[prediction_idx]} [correct]', 'black'\n    else:\n        return f'{CLASSES[prediction_idx]} [incorrect, should be {CLASSES[label]}]', 'red'\n\ndef get_titles(images, labels, model):\n    predictions = model.predict(images)\n    titles, colors = [], []\n    for label, prediction in zip(classes, predictions):\n        title, color = flower_title(label, prediction)\n        titles.append(title)\n        colors.append(color)\n    return titles, colors\n\nvalidation_viz_iterator = get_dataset_iterator(validation_dataset, 9)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:28:00.054809Z","iopub.execute_input":"2022-06-03T04:28:00.055054Z","iopub.status.idle":"2022-06-03T04:28:00.199928Z","shell.execute_reply.started":"2022-06-03T04:28:00.055024Z","shell.execute_reply":"2022-06-03T04:28:00.199083Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Re-run this cell to show a new batch of images\nimages, classes = next(validation_viz_iterator)\ntitles, colors = get_titles(images, classes, model)\ndisplay_nine_flowers(images, titles, colors)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:28:00.200993Z","iopub.execute_input":"2022-06-03T04:28:00.201218Z","iopub.status.idle":"2022-06-03T04:28:12.329199Z","shell.execute_reply.started":"2022-06-03T04:28:00.201193Z","shell.execute_reply":"2022-06-03T04:28:12.327867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Computing predictions...')\ntest_images_ds = test_dataset.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:28:12.330685Z","iopub.execute_input":"2022-06-03T04:28:12.331203Z","iopub.status.idle":"2022-06-03T04:28:30.069985Z","shell.execute_reply.started":"2022-06-03T04:28:12.331131Z","shell.execute_reply":"2022-06-03T04:28:30.069416Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Generating submission.csv file...')\n\n# Get image ids from test set and convert to unicode\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\n","metadata":{"execution":{"iopub.status.busy":"2022-06-03T04:28:30.070899Z","iopub.execute_input":"2022-06-03T04:28:30.07149Z","iopub.status.idle":"2022-06-03T04:28:32.977391Z","shell.execute_reply.started":"2022-06-03T04:28:30.071456Z","shell.execute_reply":"2022-06-03T04:28:32.976657Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# 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":{"execution":{"iopub.status.busy":"2022-06-03T04:28:32.978456Z","iopub.execute_input":"2022-06-03T04:28:32.978768Z","iopub.status.idle":"2022-06-03T04:28:33.828454Z","shell.execute_reply.started":"2022-06-03T04:28:32.978735Z","shell.execute_reply":"2022-06-03T04:28:33.827575Z"},"trusted":true},"execution_count":null,"outputs":[]}]}