{"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 on TPU\n## Table of Contents\n- Import Packages\n- Distribution Strategy\n- Common Parameters\n- Common Functions\n- Import datasets\n- Understand the data\n- Model Development\n- Submission","metadata":{}},{"cell_type":"markdown","source":"# Import Packages","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nimport pandas as pd\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras import applications\nimport re","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2021-10-29T09:02:00.461663Z","iopub.execute_input":"2021-10-29T09:02:00.462143Z","iopub.status.idle":"2021-10-29T09:02:05.990994Z","shell.execute_reply.started":"2021-10-29T09:02:00.462026Z","shell.execute_reply":"2021-10-29T09:02:05.989839Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Distribution Strategy","metadata":{}},{"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:02:05.992816Z","iopub.execute_input":"2021-10-29T09:02:05.993076Z","iopub.status.idle":"2021-10-29T09:02:11.412267Z","shell.execute_reply.started":"2021-10-29T09:02:05.993046Z","shell.execute_reply":"2021-10-29T09:02:11.411462Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Common Parameters","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [192, 192] # at this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 100\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\nGCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"\nprint(GCS_DS_PATH)","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:02:42.153943Z","iopub.execute_input":"2021-10-29T09:02:42.154922Z","iopub.status.idle":"2021-10-29T09:02:42.554470Z","shell.execute_reply.started":"2021-10-29T09:02:42.154871Z","shell.execute_reply":"2021-10-29T09:02:42.553487Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Common Functions and data pipelines","metadata":{}},{"cell_type":"markdown","source":" **Load datasets**","metadata":{}},{"cell_type":"code","source":"GCS_PATH_2 = GCS_DS_PATH + '/tfrecords-jpeg-192x192'\nAUTO = tf.data.experimental.AUTOTUNE\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH_2 + '/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH_2 + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH_2 + '/test/*.tfrec') \n\nCLASSES = ['pink primrose',    'hard-leaved pocket orchid', 'canterbury bells', 'sweet pea',     'wild geranium',     'tiger lily',           'moon orchid',              'bird of paradise', 'monkshood',        'globe thistle',         # 00 - 09\n           'snapdragon',       \"colt's foot\",               'king protea',      'spear thistle', 'yellow iris',       'globe-flower',         'purple coneflower',        'peruvian lily',    'balloon flower',   'giant white arum lily', # 10 - 19\n           'fire lily',        'pincushion flower',         'fritillary',       'red ginger',    'grape hyacinth',    'corn poppy',           'prince of wales feathers', 'stemless gentian', 'artichoke',        'sweet william',         # 20 - 29\n           'carnation',        'garden phlox',              'love in the mist', 'cosmos',        'alpine sea holly',  'ruby-lipped cattleya', 'cape flower',              'great masterwort', 'siam tulip',       'lenten rose',           # 30 - 39\n           'barberton daisy',  'daffodil',                  'sword lily',       'poinsettia',    'bolero deep blue',  'wallflower',           'marigold',                 'buttercup',        'daisy',            'common dandelion',      # 40 - 49\n           'petunia',          'wild pansy',                'primula',          'sunflower',     'lilac hibiscus',    'bishop of llandaff',   'gaura',                    'geranium',         'orange dahlia',    'pink-yellow dahlia',    # 50 - 59\n           'cautleya spicata', 'japanese anemone',          'black-eyed susan', 'silverbush',    'californian poppy', 'osteospermum',         'spring crocus',            'iris',             'windflower',       'tree poppy',            # 60 - 69\n           'gazania',          'azalea',                    'water lily',       'rose',          'thorn apple',       'morning glory',        'passion flower',           'lotus',            'toad lily',        'anthurium',             # 70 - 79\n           'frangipani',       'clematis',                  'hibiscus',         'columbine',     'desert-rose',       'tree mallow',          'magnolia',                 'cyclamen ',        'watercress',       'canna lily',            # 80 - 89\n           'hippeastrum ',     'bee balm',                  'pink quill',       'foxglove',      'bougainvillea',     'camellia',             'mallow',                   'mexican petunia',  'bromelia',         'blanket flower',        # 90 - 99\n           'trumpet creeper',  'blackberry lily',           'common tulip',     'wild rose']                                                                                                                                               # 100 - 102\n","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:02:44.070539Z","iopub.execute_input":"2021-10-29T09:02:44.070838Z","iopub.status.idle":"2021-10-29T09:02:44.285410Z","shell.execute_reply.started":"2021-10-29T09:02:44.070809Z","shell.execute_reply":"2021-10-29T09:02:44.284583Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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 data_augment(image, label):\n    image = tf.image.random_flip_left_right(image)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label  \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) # 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)\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-192x192/train/*.tfrec'), 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)\n    return dataset\n\ndef get_validation_dataset(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec'), 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","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:03:02.578577Z","iopub.execute_input":"2021-10-29T09:03:02.579056Z","iopub.status.idle":"2021-10-29T09:03:02.597122Z","shell.execute_reply.started":"2021-10-29T09:03:02.579010Z","shell.execute_reply":"2021-10-29T09:03:02.596357Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def count_data_items(filenames):\n    # the number of data items is written in the name of the .tfrec\n    # files, i.e. flowers00-230.tfrec = 230 data items\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)\n\nNUM_TRAINING_IMAGES = count_data_items(TRAINING_FILENAMES)\nNUM_VALIDATION_IMAGES = count_data_items(VALIDATION_FILENAMES)\n\nprint('Dataset: {} training images, {} validation images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES))","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:03:03.360707Z","iopub.execute_input":"2021-10-29T09:03:03.361171Z","iopub.status.idle":"2021-10-29T09:03:03.371205Z","shell.execute_reply.started":"2021-10-29T09:03:03.361136Z","shell.execute_reply":"2021-10-29T09:03:03.370316Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Sample Images**","metadata":{}},{"cell_type":"code","source":"def sample_images(images, row_count, column_count):\n    fig, axs = plt.subplots(row_count, column_count, figsize=(10,10))\n    for i in range(row_count):\n        for j in range(column_count):\n            axs[i,j].imshow(images[i * column_count + j])\n            axs[i,j].axis('off')\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:03:05.293538Z","iopub.execute_input":"2021-10-29T09:03:05.294440Z","iopub.status.idle":"2021-10-29T09:03:05.301186Z","shell.execute_reply.started":"2021-10-29T09:03:05.294386Z","shell.execute_reply":"2021-10-29T09:03:05.300331Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def find_mean_img(full_mat, title, size = (192, 192, 3)):\n    # calculate the average\n    mean_img = np.mean(full_mat, axis = 0)\n    # reshape it back to a matrix\n    mean_img = mean_img.reshape(size)\n    plt.imshow(mean_img, vmin=0, vmax=255)\n    plt.title(f'Average {title}')\n    plt.axis('off')\n    plt.show()\n    return mean_img","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:03:05.965313Z","iopub.execute_input":"2021-10-29T09:03:05.965619Z","iopub.status.idle":"2021-10-29T09:03:05.971607Z","shell.execute_reply.started":"2021-10-29T09:03:05.965587Z","shell.execute_reply":"2021-10-29T09:03:05.970596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Import datasets\n\nThis data is loaded from Kaggle and automatically sharded to maximize parallelization.","metadata":{}},{"cell_type":"code","source":"training_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:03:06.777856Z","iopub.execute_input":"2021-10-29T09:03:06.778195Z","iopub.status.idle":"2021-10-29T09:03:07.153530Z","shell.execute_reply.started":"2021-10-29T09:03:06.778162Z","shell.execute_reply":"2021-10-29T09:03:07.152600Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Understand the data","metadata":{}},{"cell_type":"markdown","source":"Let's see what the dataset looks like.","metadata":{}},{"cell_type":"code","source":"for item in training_dataset:\n    images = item[0].numpy()\n    labels = item[1].numpy()\n    break\nimages.shape, labels.shape","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:03:26.761977Z","iopub.execute_input":"2021-10-29T09:03:26.762277Z","iopub.status.idle":"2021-10-29T09:03:30.977010Z","shell.execute_reply.started":"2021-10-29T09:03:26.762245Z","shell.execute_reply":"2021-10-29T09:03:30.976029Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.unique(labels, return_counts = True)","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:03:44.605125Z","iopub.execute_input":"2021-10-29T09:03:44.605836Z","iopub.status.idle":"2021-10-29T09:03:44.612709Z","shell.execute_reply.started":"2021-10-29T09:03:44.605803Z","shell.execute_reply":"2021-10-29T09:03:44.611937Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_images(images, 4, 4)","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:03:50.735507Z","iopub.execute_input":"2021-10-29T09:03:50.735771Z","iopub.status.idle":"2021-10-29T09:03:51.855033Z","shell.execute_reply.started":"2021-10-29T09:03:50.735744Z","shell.execute_reply":"2021-10-29T09:03:51.853695Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(labels) \n\nfull_mat_F1 = images [labels == 4, :,:,:]\nfull_mat_F2 = images [labels == 67,:,:,:]\nfull_mat_F3 = images [labels == 73,:,:,:]","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:04:07.177751Z","iopub.execute_input":"2021-10-29T09:04:07.178733Z","iopub.status.idle":"2021-10-29T09:04:07.191051Z","shell.execute_reply.started":"2021-10-29T09:04:07.178690Z","shell.execute_reply":"2021-10-29T09:04:07.190162Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"F1_mean = find_mean_img(full_mat_F1, 'F1')\nF2_mean = find_mean_img(full_mat_F2, 'F2')\nF3_mean = find_mean_img(full_mat_F3, 'F3')","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:04:08.389118Z","iopub.execute_input":"2021-10-29T09:04:08.389415Z","iopub.status.idle":"2021-10-29T09:04:08.912657Z","shell.execute_reply.started":"2021-10-29T09:04:08.389384Z","shell.execute_reply":"2021-10-29T09:04:08.911855Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Development","metadata":{}},{"cell_type":"markdown","source":"### Model Checkpoint","metadata":{}},{"cell_type":"code","source":"checkpoint_path = \"model.h5\"\ncheckpoint = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, save_best_only=True)","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:04:17.874207Z","iopub.execute_input":"2021-10-29T09:04:17.875020Z","iopub.status.idle":"2021-10-29T09:04:17.879316Z","shell.execute_reply.started":"2021-10-29T09:04:17.874982Z","shell.execute_reply":"2021-10-29T09:04:17.878476Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Learning Rate Scheduler","metadata":{"execution":{"iopub.status.busy":"2021-09-01T14:26:34.527526Z","iopub.execute_input":"2021-09-01T14:26:34.527875Z","iopub.status.idle":"2021-09-01T14:26:34.530985Z","shell.execute_reply.started":"2021-09-01T14:26:34.527846Z","shell.execute_reply":"2021-09-01T14:26:34.530219Z"}}},{"cell_type":"code","source":"LR_START = 0.00005\nLR_MAX =   0.00005 * strategy.num_replicas_in_sync\nLR_MIN =   0.0000025\nLR_RAMPUP_EPOCHS = 3\nLR_SUSTAIN_EPOCHS = 6\nLR_EXP_DECAY = .8\ndef scheduler_callback(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr =  np.random.random_sample() * LR_START\n    elif epoch < LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS:\n        lr = LR_MAX\n    else:\n        lr = (LR_MAX - LR_MIN) * LR_EXP_DECAY**(epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS) + LR_MIN\n    return lr\nscheduler = tf.keras.callbacks.LearningRateScheduler(scheduler_callback, verbose=True)","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:04:19.778593Z","iopub.execute_input":"2021-10-29T09:04:19.778873Z","iopub.status.idle":"2021-10-29T09:04:19.786541Z","shell.execute_reply.started":"2021-10-29T09:04:19.778846Z","shell.execute_reply":"2021-10-29T09:04:19.785623Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Early Stopping","metadata":{}},{"cell_type":"code","source":"early_stop = tf.keras.callbacks.EarlyStopping(patience=10)","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:04:22.362622Z","iopub.execute_input":"2021-10-29T09:04:22.363420Z","iopub.status.idle":"2021-10-29T09:04:22.367690Z","shell.execute_reply.started":"2021-10-29T09:04:22.363383Z","shell.execute_reply":"2021-10-29T09:04:22.366765Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callbacks = [early_stop, checkpoint, scheduler]","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:04:22.796988Z","iopub.execute_input":"2021-10-29T09:04:22.797273Z","iopub.status.idle":"2021-10-29T09:04:22.802117Z","shell.execute_reply.started":"2021-10-29T09:04:22.797246Z","shell.execute_reply":"2021-10-29T09:04:22.801190Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Optimizer","metadata":{}},{"cell_type":"code","source":"optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, \n                                                 beta_1=0.9, \n                                                 beta_2=0.999, \n                                                 epsilon=1e-07, \n                                                 amsgrad=False)","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:04:24.610394Z","iopub.execute_input":"2021-10-29T09:04:24.610836Z","iopub.status.idle":"2021-10-29T09:04:24.615681Z","shell.execute_reply.started":"2021-10-29T09:04:24.610806Z","shell.execute_reply":"2021-10-29T09:04:24.614610Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Get Pretrain Model\nI will build the Model based on kears pretrained Models. There are many pretrained Models such as InceptionV3, EfficientNet 0 - 7 and so on. You can choose the pretrained Model you like to train the Model.","metadata":{}},{"cell_type":"code","source":"model_types = [\n    \"dense_net\", \n    \"xception\", \n    \"inception\", \n    \"inceptionResNet\",\n]\n\nmodel_type = model_types[1]\n\ndef get_pretraind_model(model_type, input_shape):\n    if model_type == \"dense_net\":\n        return applications.densenet.DenseNet121(\n                include_top=False,\n                input_shape=input_shape               \n            )\n    if model_type == \"xception\":\n        return applications.Xception(\n            include_top=False,\n            input_shape=input_shape                        \n        )\n    if model_type == \"inception\":\n        return applications.InceptionV3(\n            include_top=False,\n            input_shape=input_shape                          \n        )\n    if model_type == \"inceptionResNet\":\n        return applications.InceptionResNetV2(\n            include_top=False,\n                input_shape=input_shape                         \n        )\n   ","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:04:29.598200Z","iopub.execute_input":"2021-10-29T09:04:29.598617Z","iopub.status.idle":"2021-10-29T09:04:29.605368Z","shell.execute_reply.started":"2021-10-29T09:04:29.598586Z","shell.execute_reply":"2021-10-29T09:04:29.604440Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train the Model","metadata":{}},{"cell_type":"code","source":"def train(\n    model_type, epochs, optimizer, callbacks, \n    strategy, layers):\n    tf.keras.backend.clear_session()\n    with strategy.scope():  \n        input_shape = [*IMAGE_SIZE, 3]   \n        pretrained_model = get_pretraind_model(model_type, input_shape)\n        print(pretrained_model.summary())\n        pretrained_model.trainable = True \n        all_layers = [pretrained_model] + layers + [tf.keras.layers.Dense(104, activation='softmax')]\n        model = tf.keras.Sequential(all_layers)\n        model.compile(\n            optimizer=optimizer,\n            loss = 'sparse_categorical_crossentropy',\n            metrics=['sparse_categorical_accuracy']\n        )\n        history = model.fit(training_dataset, \n                            steps_per_epoch=STEPS_PER_EPOCH, \n                            epochs=epochs, \n                            validation_data=validation_dataset, \n                            callbacks=callbacks\n                           )\n        pd.DataFrame(history.history).plot()\n        plt.show()\n        return model","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:04:35.600090Z","iopub.execute_input":"2021-10-29T09:04:35.600772Z","iopub.status.idle":"2021-10-29T09:04:35.609943Z","shell.execute_reply.started":"2021-10-29T09:04:35.600731Z","shell.execute_reply":"2021-10-29T09:04:35.609317Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = train(\n    model_type, EPOCHS, optimizer, callbacks, strategy, \n    layers=[\n        tf.keras.layers.Dropout(0.5), \n        tf.keras.layers.GlobalAveragePooling2D(), \n        tf.keras.layers.Dropout(0.5)\n    ]\n)","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:04:37.781962Z","iopub.execute_input":"2021-10-29T09:04:37.782391Z","iopub.status.idle":"2021-10-29T09:13:02.763332Z","shell.execute_reply.started":"2021-10-29T09:04:37.782356Z","shell.execute_reply":"2021-10-29T09:13:02.762427Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Confusion matrix","metadata":{}},{"cell_type":"markdown","source":"We'll look at two common ways of validation: plotting the confusion matrix and visual validation.","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom 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":"2021-10-29T09:14:19.631681Z","iopub.execute_input":"2021-10-29T09:14:19.632186Z","iopub.status.idle":"2021-10-29T09:14:20.307087Z","shell.execute_reply.started":"2021-10-29T09:14:19.632152Z","shell.execute_reply":"2021-10-29T09:14:20.306203Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"cmdataset = 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":"2021-10-29T09:14:22.188871Z","iopub.execute_input":"2021-10-29T09:14:22.189411Z","iopub.status.idle":"2021-10-29T09:14:27.203828Z","shell.execute_reply.started":"2021-10-29T09:14:22.189377Z","shell.execute_reply":"2021-10-29T09:14:27.202865Z"},"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-10-29T09:14:54.565546Z","iopub.execute_input":"2021-10-29T09:14:54.565842Z","iopub.status.idle":"2021-10-29T09:14:59.580103Z","shell.execute_reply.started":"2021-10-29T09:14:54.565813Z","shell.execute_reply":"2021-10-29T09:14:59.579245Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visual validation","metadata":{}},{"cell_type":"code","source":"dataset = get_validation_dataset()\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:15:48.641657Z","iopub.execute_input":"2021-10-29T09:15:48.641956Z","iopub.status.idle":"2021-10-29T09:15:49.236144Z","shell.execute_reply.started":"2021-10-29T09:15:48.641927Z","shell.execute_reply":"2021-10-29T09:15:49.235411Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import pyplot as plt\nimport math\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)\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\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-10-29T09:21:52.695110Z","iopub.execute_input":"2021-10-29T09:21:52.695415Z","iopub.status.idle":"2021-10-29T09:21:52.717673Z","shell.execute_reply.started":"2021-10-29T09:21:52.695384Z","shell.execute_reply":"2021-10-29T09:21:52.716656Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images, labels = next(batch)\nprobabilities = model.predict(images)\npredictions = np.argmax(probabilities, axis=-1)\ndisplay_batch_of_images((images, labels), predictions)\n","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:21:53.903654Z","iopub.execute_input":"2021-10-29T09:21:53.904373Z","iopub.status.idle":"2021-10-29T09:21:56.037487Z","shell.execute_reply.started":"2021-10-29T09:21:53.904334Z","shell.execute_reply":"2021-10-29T09:21:56.035950Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Make test predictions (unlabelled data)","metadata":{}},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True)\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)","metadata":{"execution":{"iopub.status.busy":"2021-10-29T09:22:06.020271Z","iopub.execute_input":"2021-10-29T09:22:06.020578Z","iopub.status.idle":"2021-10-29T09:22:30.255459Z","shell.execute_reply.started":"2021-10-29T09:22:06.020546Z","shell.execute_reply":"2021-10-29T09:22:30.254596Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission","metadata":{}},{"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.\nmodel.load_weights(checkpoint_path)\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\nprint('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":"2021-10-29T09:13:14.822769Z","iopub.status.idle":"2021-10-29T09:13:14.823250Z","shell.execute_reply.started":"2021-10-29T09:13:14.822987Z","shell.execute_reply":"2021-10-29T09:13:14.823011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}