{"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":"# A Simple TF 2.1 notebook\n\nThis is based entirely off of Martin Gorner's excellent starter notebook, and is intended solely as a simple, shorter introduction to the operations being performed there.","metadata":{"_uuid":"a1c0e91b-82e0-4038-b999-f69d51230b34","_cell_guid":"0ab7baae-f97d-4871-af10-b7c550a5b0b7","trusted":true}},{"cell_type":"code","source":"import tensorflow as tf\nimport numpy as np\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_uuid":"c68fda87-0dad-447f-9f6a-ed6fa365b64e","_cell_guid":"ac894bd1-2ecc-49c2-9164-957bcc3b27bb","execution":{"iopub.status.busy":"2023-04-03T03:35:29.344237Z","iopub.execute_input":"2023-04-03T03:35:29.345060Z","iopub.status.idle":"2023-04-03T03:35:29.352085Z","shell.execute_reply.started":"2023-04-03T03:35:29.345014Z","shell.execute_reply":"2023-04-03T03:35:29.350432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Detect my accelerator","metadata":{"_uuid":"3b5d615a-3182-4f81-a8f3-cb6e54264e63","_cell_guid":"93dde2ac-0d09-4d46-a121-f2ecae88c786","trusted":true}},{"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver() #detect and initiate the TPU\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\nif tpu: #if tpu exists\n    tf.config.experimental_connect_to_cluster(tpu) #locate tpu on the network\n    tf.tpu.experimental.initialize_tpu_system(tpu) #initiatlize the TPU\n    strategy = tf.distribute.experimental.TPUStrategy(tpu) #instatiating the object TPUStrategy\n    # This object contains the necessary distributed training code that will work on TPUs with 8 cores\n    \nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2023-04-03T03:37:41.841425Z","iopub.execute_input":"2023-04-03T03:37:41.842179Z","iopub.status.idle":"2023-04-03T03:37:46.489617Z","shell.execute_reply.started":"2023-04-03T03:37:41.842119Z","shell.execute_reply":"2023-04-03T03:37:46.488420Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# CHANGED FOR TPU 1VM:\n# Detect hardware, return appropriate distribution strategy\n'''\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver.connect(tpu=\"local\") # \"local\" for 1VM TPU\n    strategy = tf.distribute.TPUStrategy(tpu)\n    print(\"on TPU\")\nexcept tf.errors.NotFoundError:\n    print(\"not on TPU\")\n    strategy = tf.distribute.MirroredStrategy()\n    \nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)\n'''","metadata":{"_uuid":"ca83590c-b66b-4a3f-a66c-672f851f6361","_cell_guid":"8cb47b9d-d19a-4a3d-89c4-49010783d95b","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-04-03T03:08:47.085459Z","iopub.execute_input":"2023-04-03T03:08:47.085939Z","iopub.status.idle":"2023-04-03T03:08:47.430436Z","shell.execute_reply.started":"2023-04-03T03:08:47.085894Z","shell.execute_reply":"2023-04-03T03:08:47.429489Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Get my data path","metadata":{"_uuid":"0ac5b0f1-82b4-4f11-9a6a-20c5e9e0c217","_cell_guid":"2eef11e3-52b1-48c6-aced-1b23877d2542","trusted":true}},{"cell_type":"code","source":"from kaggle_datasets import KaggleDatasets\n\n\n# CHANGED FOR TPU 1VM: Direct access to the filesystem, no longer need to get_gcs_path()!\nGCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"\n#GCS_DS_PATH = '/kaggle/input/flower-classification-with-tpus'","metadata":{"_uuid":"1cd5541c-e170-43a3-b2dd-edfbc5e9c1b0","_cell_guid":"501e1373-26a2-4f6c-a106-438be52d9a21","execution":{"iopub.status.busy":"2023-04-03T03:38:48.601617Z","iopub.execute_input":"2023-04-03T03:38:48.602525Z","iopub.status.idle":"2023-04-03T03:38:48.973960Z","shell.execute_reply.started":"2023-04-03T03:38:48.602468Z","shell.execute_reply":"2023-04-03T03:38:48.972826Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Set some parameters","metadata":{"_uuid":"242649f3-dd3c-48d3-8be1-e2cb9bc70583","_cell_guid":"e80238ac-95c4-471c-86b7-bd07d6a6db7e","trusted":true}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [512, 512] # at this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 10\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nAUTO = tf.data.experimental.AUTOTUNE","metadata":{"_uuid":"fd506828-093f-4291-b8e4-bb3512509cf7","_cell_guid":"fff4b014-6d83-4909-a9fd-396584ac486b","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-04-03T03:45:43.718181Z","iopub.execute_input":"2023-04-03T03:45:43.718742Z","iopub.status.idle":"2023-04-03T03:45:43.726417Z","shell.execute_reply.started":"2023-04-03T03:45:43.718693Z","shell.execute_reply":"2023-04-03T03:45:43.724939Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Load my data\n\nThis data is loaded from Kaggle and automatically sharded to maximize parallelization.","metadata":{"_uuid":"0eaf2aba-6dff-4726-933d-f5c3a40d2b44","_cell_guid":"5b03ba57-3f00-404f-939a-cd401bd2c350","trusted":true}},{"cell_type":"code","source":"def decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0  # 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\n\ndef get_training_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/train/*.tfrec'), labeled=True)\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(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/val/*.tfrec'), labeled=True, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-512x512/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\ntraining_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"_uuid":"b8a52a0f-50a0-4dab-a702-955a35600a17","_cell_guid":"71de7242-f9d9-4c29-8dfd-0ae79b8641c7","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-04-03T03:46:15.112613Z","iopub.execute_input":"2023-04-03T03:46:15.113019Z","iopub.status.idle":"2023-04-03T03:46:15.331513Z","shell.execute_reply.started":"2023-04-03T03:46:15.112984Z","shell.execute_reply":"2023-04-03T03:46:15.330412Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Build a model on TPU (or GPU, or CPU...) with Tensorflow 2.1!","metadata":{"_uuid":"d679cfbe-ba20-4c5d-a1a6-b0650058bc75","_cell_guid":"f0938c02-03e8-4603-9b17-38ef39ac3330","trusted":true}},{"cell_type":"code","source":"with strategy.scope():    \n    pretrained_model = tf.keras.applications.VGG16(weights='imagenet', include_top=False ,input_shape=[*IMAGE_SIZE, 3])\n    pretrained_model.trainable = False # tramsfer learning\n    \n    model = tf.keras.Sequential([\n        pretrained_model,\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(104, activation='softmax')\n    ])\n        \nmodel.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy']\n)\n","metadata":{"_uuid":"43c90f57-a8fb-4844-ae42-954e291d10aa","_cell_guid":"4423286c-bbc9-46e5-a20e-49600014692c","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-04-03T03:46:19.009367Z","iopub.execute_input":"2023-04-03T03:46:19.009796Z","iopub.status.idle":"2023-04-03T03:46:21.007719Z","shell.execute_reply.started":"2023-04-03T03:46:19.009756Z","shell.execute_reply":"2023-04-03T03:46:21.006318Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import pyplot as plt\n\n# This learning rate schedule is custom learning scheduler\n# From TF/Keras Learning Rate & Schedulers\n# Copied straight from a notebook of Chris Deotte.\n# Learning Rate Schedule for Fine Tuning #\ndef exponential_lr(epoch,\n                   start_lr = 0.00001, min_lr = 0.00001, max_lr = 0.00005,\n                   rampup_epochs = 2, sustain_epochs = 0,\n                   exp_decay = 0.8):\n\n    def lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay):\n        # linear increase from start to rampup_epochs\n        if epoch < rampup_epochs:\n            lr = ((max_lr - start_lr) /\n                  rampup_epochs * epoch + start_lr)\n        # constant max_lr during sustain_epochs\n        elif epoch < rampup_epochs + sustain_epochs:\n            lr = max_lr\n        # exponential decay towards min_lr\n        else:\n            lr = ((max_lr - min_lr) *\n                  exp_decay**(epoch - rampup_epochs - sustain_epochs) +\n                  min_lr)\n        return lr\n    return lr(epoch,\n              start_lr,\n              min_lr,\n              max_lr,\n              rampup_epochs,\n              sustain_epochs,\n              exp_decay)\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(exponential_lr, verbose=True)\n\nrng = [i for i in range(EPOCHS)]\ny = [exponential_lr(x) for x in rng]\nplt.plot(rng, y)\nprint(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(y[0], max(y), y[-1]))","metadata":{"execution":{"iopub.status.busy":"2023-04-03T03:46:59.811563Z","iopub.execute_input":"2023-04-03T03:46:59.811971Z","iopub.status.idle":"2023-04-03T03:47:00.050839Z","shell.execute_reply.started":"2023-04-03T03:46:59.811934Z","shell.execute_reply":"2023-04-03T03:47:00.049558Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"historical = model.fit(\n        training_dataset, \n        steps_per_epoch=STEPS_PER_EPOCH, \n        epochs=EPOCHS, \n        validation_data=validation_dataset,\n        #callbacks=[lr_callback],\n    )     ","metadata":{"execution":{"iopub.status.busy":"2023-04-03T04:43:23.534285Z","iopub.execute_input":"2023-04-03T04:43:23.534804Z","iopub.status.idle":"2023-04-03T04:47:29.150945Z","shell.execute_reply.started":"2023-04-03T04:43:23.534757Z","shell.execute_reply":"2023-04-03T04:47:29.149707Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"hello\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def 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.'])\n    \ndisplay_training_curves(\n    historical.history['loss'],\n    historical.history['val_loss'],\n    'loss',\n    211,\n)\ndisplay_training_curves(\n    historical.history['sparse_categorical_accuracy'],\n    historical.history['val_sparse_categorical_accuracy'],\n    'accuracy',\n    212,\n)","metadata":{"execution":{"iopub.status.busy":"2023-04-03T04:35:14.784874Z","iopub.execute_input":"2023-04-03T04:35:14.786260Z","iopub.status.idle":"2023-04-03T04:35:15.360766Z","shell.execute_reply.started":"2023-04-03T04:35:14.786194Z","shell.execute_reply":"2023-04-03T04:35:15.359639Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install scikit-learn --upgrade","metadata":{"execution":{"iopub.status.busy":"2023-04-03T04:35:36.178899Z","iopub.execute_input":"2023-04-03T04:35:36.180411Z","iopub.status.idle":"2023-04-03T04:35:48.513531Z","shell.execute_reply.started":"2023-04-03T04:35:36.180318Z","shell.execute_reply":"2023-04-03T04:35:48.511682Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import f1_score, precision_score, recall_score, confusion_matrix\n\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(CLASSES)))\n    ax.set_xticklabels(CLASSES, fontdict={'fontsize': 7})\n    plt.setp(ax.get_xticklabels(), rotation=45, ha=\"left\", rotation_mode=\"anchor\")\n    ax.set_yticks(range(len(CLASSES)))\n    ax.set_yticklabels(CLASSES, 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    \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":"2023-04-03T04:35:48.516827Z","iopub.execute_input":"2023-04-03T04:35:48.517464Z","iopub.status.idle":"2023-04-03T04:35:48.534212Z","shell.execute_reply.started":"2023-04-03T04:35:48.517390Z","shell.execute_reply":"2023-04-03T04:35:48.532840Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"CLASSES = ['pink primrose',    'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',     'wild geranium',     'tiger lily',           'moon orchid',              'bird of paradise', 'monkshood',        'globe thistle',         # 00 - 09\n           'snapdragon',       \"colt's foot\",               'king protea',      'spear thistle', 'yellow iris',       'globe-flower',         'purple coneflower',        'peruvian lily',    'balloon flower',   'giant white arum lily', # 10 - 19\n           'fire lily',        'pincushion flower',         'fritillary',       'red ginger',    'grape hyacinth',    'corn poppy',           'prince of wales feathers', 'stemless gentian', 'artichoke',        'sweet william',         # 20 - 29\n           'carnation',        'garden phlox',              'love in the mist', 'cosmos',        'alpine sea holly',  'ruby-lipped cattleya', 'cape flower',              'great masterwort', 'siam tulip',       'lenten rose',           # 30 - 39\n           'barberton daisy',  'daffodil',                  'sword lily',       'poinsettia',    'bolero deep blue',  'wallflower',           'marigold',                 'buttercup',        'daisy',            'common dandelion',      # 40 - 49\n           'petunia',          'wild pansy',                'primula',          'sunflower',     'lilac hibiscus',    'bishop of llandaff',   'gaura',                    'geranium',         'orange dahlia',    'pink-yellow dahlia',    # 50 - 59\n           'cautleya spicata', 'japanese anemone',          'black-eyed susan', 'silverbush',    'californian poppy', 'osteospermum',         'spring crocus',            'iris',             'windflower',       'tree poppy',            # 60 - 69\n           'gazania',          'azalea',                    'water lily',       'rose',          'thorn apple',       'morning glory',        'passion flower',           'lotus',            'toad lily',        'anthurium',             # 70 - 79\n           'frangipani',       'clematis',                  'hibiscus',         'columbine',     'desert-rose',       'tree mallow',          'magnolia',                 'cyclamen ',        'watercress',       'canna lily',            # 80 - 89\n           'hippeastrum ',     'bee balm',                  'pink quill',       'foxglove',      'bougainvillea',     'camellia',             'mallow',                   'mexican petunia',  'bromelia',         'blanket flower',        # 90 - 99\n           'trumpet creeper',  'blackberry lily',           'common tulip',     'wild rose']   \n\nNUM_VALIDATION_IMAGES=3712 \n\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(NUM_VALIDATION_IMAGES))).numpy()\ncm_probabilities = model.predict(images_ds)\ncm_predictions = np.argmax(cm_probabilities, axis=-1)\n\nlabels = range(len(CLASSES))\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":"2023-04-03T04:35:51.843669Z","iopub.execute_input":"2023-04-03T04:35:51.844094Z","iopub.status.idle":"2023-04-03T04:35:59.582620Z","shell.execute_reply.started":"2023-04-03T04:35:51.844056Z","shell.execute_reply":"2023-04-03T04:35:59.580319Z"},"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":"2023-04-03T04:37:50.191916Z","iopub.execute_input":"2023-04-03T04:37:50.192559Z","iopub.status.idle":"2023-04-03T04:37:55.283970Z","shell.execute_reply.started":"2023-04-03T04:37:50.192506Z","shell.execute_reply":"2023-04-03T04:37:55.282486Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = get_validation_dataset()\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)","metadata":{"execution":{"iopub.status.busy":"2023-04-03T02:07:40.638698Z","iopub.execute_input":"2023-04-03T02:07:40.639529Z","iopub.status.idle":"2023-04-03T02:07:40.712832Z","shell.execute_reply.started":"2023-04-03T02:07:40.639494Z","shell.execute_reply":"2023-04-03T02:07:40.711928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import math\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\n    # 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()\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,\n                                     # 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\n    # 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)","metadata":{"execution":{"iopub.status.busy":"2023-04-02T19:59:35.019559Z","iopub.execute_input":"2023-04-02T19:59:35.020343Z","iopub.status.idle":"2023-04-02T19:59:35.040005Z","shell.execute_reply.started":"2023-04-02T19:59:35.020303Z","shell.execute_reply":"2023-04-02T19:59:35.038823Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\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":"2023-04-02T20:04:24.245902Z","iopub.execute_input":"2023-04-02T20:04:24.246842Z","iopub.status.idle":"2023-04-02T20:04:27.381597Z","shell.execute_reply.started":"2023-04-02T20:04:24.246780Z","shell.execute_reply":"2023-04-02T20:04:27.380560Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Compute your predictions on the test set!\n\nThis will create a file that can be submitted to the competition.","metadata":{"_uuid":"6e881ca4-4aed-4f90-8b32-99991d607929","_cell_guid":"decd9920-8ff4-4a82-babe-033d1249a358","trusted":true}},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)\n\n","metadata":{"_uuid":"aed47871-2d46-4b6f-8647-03368eabdd11","_cell_guid":"5562fa5e-a996-4f4c-baf0-768064ede725","collapsed":false,"jupyter":{"outputs_hidden":false},"execution":{"iopub.status.busy":"2023-04-03T02:08:40.731675Z","iopub.execute_input":"2023-04-03T02:08:40.732398Z","iopub.status.idle":"2023-04-03T02:10:34.444532Z","shell.execute_reply.started":"2023-04-03T02:08:40.732362Z","shell.execute_reply":"2023-04-03T02:10:34.443484Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"execution":{"iopub.status.busy":"2023-04-03T02:12:13.052379Z","iopub.execute_input":"2023-04-03T02:12:13.053425Z","iopub.status.idle":"2023-04-03T02:12:13.468112Z","shell.execute_reply.started":"2023-04-03T02:12:13.053379Z","shell.execute_reply":"2023-04-03T02:12:13.466988Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"","metadata":{"execution":{"iopub.status.busy":"2022-09-16T16:41:55.328687Z","iopub.execute_input":"2022-09-16T16:41:55.329544Z","iopub.status.idle":"2022-09-16T16:42:04.143932Z","shell.execute_reply.started":"2022-09-16T16:41:55.329447Z","shell.execute_reply":"2022-09-16T16:42:04.143031Z"}}},{"cell_type":"markdown","source":"","metadata":{"execution":{"iopub.status.busy":"2022-09-16T16:30:45.095894Z","iopub.execute_input":"2022-09-16T16:30:45.096839Z"}}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"markdown","source":"# Step 9: Make a submission #\n\nIf you haven't already, create your own editable copy of this notebook by clicking on the **Copy and Edit** button in the top right corner. Then, submit to the competition by following these steps:\n\n1. Begin by clicking on the blue **Save Version** button in the top right corner of the window.  This will generate a pop-up window.  \n2. Ensure that the **Save and Run All** option is selected, and then click on the blue **Save** button.\n3. This generates a window in the bottom left corner of the notebook.  After it has finished running, click on the number to the right of the **Save Version** button.  This pulls up a list of versions on the right of the screen.  Click on the ellipsis **(...)** to the right of the most recent version, and select **Open in Viewer**.  This brings you into view mode of the same page. You will need to scroll down to get back to these instructions.\n4. Click on the **Output** tab on the right of the screen.  Then, click on the file you would like to submit, and click on the blue **Submit** button to submit your results to the leaderboard.\n\nYou have now successfully submitted to the competition!\n\nIf you want to keep working to improve your performance, select the blue **Edit** button in the top right of the screen. Then you can change your code and repeat the process. There's a lot of room to improve, and you will climb up the leaderboard as you work.\n","metadata":{}},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}