{"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 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\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2021-11-18T18:53:41.196761Z","iopub.execute_input":"2021-11-18T18:53:41.197096Z","iopub.status.idle":"2021-11-18T18:53:47.268262Z","shell.execute_reply.started":"2021-11-18T18:53:41.197016Z","shell.execute_reply":"2021-11-18T18:53:47.267542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Set up TPU","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-11-18T18:53:47.269833Z","iopub.execute_input":"2021-11-18T18:53:47.270273Z","iopub.status.idle":"2021-11-18T18:53:53.387683Z","shell.execute_reply.started":"2021-11-18T18:53:47.270242Z","shell.execute_reply":"2021-11-18T18:53:53.386864Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Get the data. Image resolution: 512 x 512","metadata":{}},{"cell_type":"code","source":"GCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"","metadata":{"execution":{"iopub.status.busy":"2021-11-18T18:53:53.388756Z","iopub.execute_input":"2021-11-18T18:53:53.388998Z","iopub.status.idle":"2021-11-18T18:53:53.795692Z","shell.execute_reply.started":"2021-11-18T18:53:53.388971Z","shell.execute_reply":"2021-11-18T18:53:53.794743Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [512, 512] # 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\n\nAUTO = tf.data.experimental.AUTOTUNE","metadata":{"execution":{"iopub.status.busy":"2021-11-18T18:53:53.797826Z","iopub.execute_input":"2021-11-18T18:53:53.798096Z","iopub.status.idle":"2021-11-18T18:53:53.803780Z","shell.execute_reply.started":"2021-11-18T18:53:53.798066Z","shell.execute_reply":"2021-11-18T18:53:53.802813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"GCS_IMAGE_SIZE_PATHS = {\n    192: '/tfrecords-jpeg-192x192',\n    224: '/tfrecords-jpeg-224x224',\n    331: '/tfrecords-jpeg-331x331',\n    512: '/tfrecords-jpeg-512x512'    \n}\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + GCS_IMAGE_SIZE_PATHS[IMAGE_SIZE[0]] + '/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + GCS_IMAGE_SIZE_PATHS[IMAGE_SIZE[0]] + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_DS_PATH + GCS_IMAGE_SIZE_PATHS[IMAGE_SIZE[0]] + '/test/*.tfrec') \n\ndef 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)\nNUM_TEST_IMAGES = count_data_items(TEST_FILENAMES)\n\nprint('Dataset: {} training images, {} validation images, {} test images'.format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))","metadata":{"execution":{"iopub.status.busy":"2021-11-18T18:53:53.805274Z","iopub.execute_input":"2021-11-18T18:53:53.805724Z","iopub.status.idle":"2021-11-18T18:53:54.032511Z","shell.execute_reply.started":"2021-11-18T18:53:53.805693Z","shell.execute_reply":"2021-11-18T18:53:54.031537Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def data_augmentation(image, label):\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    image = tf.image.resize_with_crop_or_pad(image, 520, 520)\n    image = tf.image.random_crop(image, (IMAGE_SIZE[0],IMAGE_SIZE[1],3))\n    return image, label  \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\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(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.map(data_augmentation, 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(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","metadata":{"execution":{"iopub.status.busy":"2021-11-18T18:53:54.035162Z","iopub.execute_input":"2021-11-18T18:53:54.035440Z","iopub.status.idle":"2021-11-18T18:53:54.055862Z","shell.execute_reply.started":"2021-11-18T18:53:54.035411Z","shell.execute_reply":"2021-11-18T18:53:54.054833Z"},"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'] # 100 - 103\nprint(len(CLASSES))","metadata":{"execution":{"iopub.status.busy":"2021-11-18T18:53:54.057674Z","iopub.execute_input":"2021-11-18T18:53:54.058006Z","iopub.status.idle":"2021-11-18T18:53:54.077592Z","shell.execute_reply.started":"2021-11-18T18:53:54.057968Z","shell.execute_reply":"2021-11-18T18:53:54.076399Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"training_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"execution":{"iopub.status.busy":"2021-11-18T18:53:54.079207Z","iopub.execute_input":"2021-11-18T18:53:54.079837Z","iopub.status.idle":"2021-11-18T18:53:54.408029Z","shell.execute_reply.started":"2021-11-18T18:53:54.079793Z","shell.execute_reply":"2021-11-18T18:53:54.406776Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Set hyperparameters","metadata":{}},{"cell_type":"code","source":"early_stop = tf.keras.callbacks.EarlyStopping(patience=10,restore_best_weights=True)","metadata":{"execution":{"iopub.status.busy":"2021-11-18T18:53:54.409437Z","iopub.execute_input":"2021-11-18T18:53:54.409880Z","iopub.status.idle":"2021-11-18T18:53:54.415295Z","shell.execute_reply.started":"2021-11-18T18:53:54.409807Z","shell.execute_reply":"2021-11-18T18:53:54.414271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpoint_path = \"EfficientNet_V2_XL_DenseNet.h5\"\ncheckpoint = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, save_best_only=True)","metadata":{"execution":{"iopub.status.busy":"2021-11-18T18:53:54.419298Z","iopub.execute_input":"2021-11-18T18:53:54.419763Z","iopub.status.idle":"2021-11-18T18:53:54.426908Z","shell.execute_reply.started":"2021-11-18T18:53:54.419710Z","shell.execute_reply":"2021-11-18T18:53:54.426291Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Learning Rate Scheduler\n\nLR_START = 0.00001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001\nLR_RAMPUP_EPOCHS = 5\nLR_SUSTAIN_EPOCHS = 5\nLR_EXP_DECAY = .8\n\ndef learning_rate_scheduler(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr = (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS * epoch + 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\n    \nlr_callback = tf.keras.callbacks.LearningRateScheduler(learning_rate_scheduler, verbose=1)","metadata":{"execution":{"iopub.status.busy":"2021-11-18T18:53:54.428331Z","iopub.execute_input":"2021-11-18T18:53:54.429003Z","iopub.status.idle":"2021-11-18T18:53:54.445282Z","shell.execute_reply.started":"2021-11-18T18:53:54.428960Z","shell.execute_reply":"2021-11-18T18:53:54.444288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callbacks = [early_stop, lr_callback, checkpoint]","metadata":{"execution":{"iopub.status.busy":"2021-11-18T18:53:54.446599Z","iopub.execute_input":"2021-11-18T18:53:54.446962Z","iopub.status.idle":"2021-11-18T18:53:54.458678Z","shell.execute_reply.started":"2021-11-18T18:53:54.446931Z","shell.execute_reply":"2021-11-18T18:53:54.457608Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Get EfficientNet model","metadata":{}},{"cell_type":"code","source":"# EfficientNet models\n\ndef get_hub_url_and_isize(model_name, ckpt_type, hub_type):\n    if ckpt_type == '1k':\n        ckpt_type = ''  # json doesn't support empty string\n    else:\n        ckpt_type = '-' + ckpt_type  # add '-' as prefix\n  \n    hub_url_map = {\n    'efficientnetv2-b0': f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-b0/{hub_type}',\n    'efficientnetv2-b1': f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-b1/{hub_type}',\n    'efficientnetv2-b2': f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-b2/{hub_type}',\n    'efficientnetv2-b3': f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-b3/{hub_type}',\n    'efficientnetv2-s':  f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-s/{hub_type}',\n    'efficientnetv2-m':  f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-m/{hub_type}',\n    'efficientnetv2-l':  f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-l/{hub_type}',\n\n    'efficientnetv2-b0-21k': f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-b0-21k/{hub_type}',\n    'efficientnetv2-b1-21k': f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-b1-21k/{hub_type}',\n    'efficientnetv2-b2-21k': f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-b2-21k/{hub_type}',\n    'efficientnetv2-b3-21k': f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-b3-21k/{hub_type}',\n    'efficientnetv2-s-21k':  f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-s-21k/{hub_type}',\n    'efficientnetv2-m-21k':  f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-m-21k/{hub_type}',\n    'efficientnetv2-l-21k':  f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-l-21k/{hub_type}',\n    'efficientnetv2-xl-21k':  f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-xl-21k/{hub_type}',\n\n    'efficientnetv2-b0-21k-ft1k': f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-b0-21k-ft1k/{hub_type}',\n    'efficientnetv2-b1-21k-ft1k': f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-b1-21k-ft1k/{hub_type}',\n    'efficientnetv2-b2-21k-ft1k': f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-b2-21k-ft1k/{hub_type}',\n    'efficientnetv2-b3-21k-ft1k': f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-b3-21k-ft1k/{hub_type}',\n    'efficientnetv2-s-21k-ft1k':  f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-s-21k-ft1k/{hub_type}',\n    'efficientnetv2-m-21k-ft1k':  f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-m-21k-ft1k/{hub_type}',\n    'efficientnetv2-l-21k-ft1k':  f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-l-21k-ft1k/{hub_type}',\n    'efficientnetv2-xl-21k-ft1k':  f'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-xl-21k-ft1k/{hub_type}',\n      \n    # efficientnetv1\n    'efficientnet_b0': f'https://tfhub.dev/tensorflow/efficientnet/b0/{hub_type}/1',\n    'efficientnet_b1': f'https://tfhub.dev/tensorflow/efficientnet/b1/{hub_type}/1',\n    'efficientnet_b2': f'https://tfhub.dev/tensorflow/efficientnet/b2/{hub_type}/1',\n    'efficientnet_b3': f'https://tfhub.dev/tensorflow/efficientnet/b3/{hub_type}/1',\n    'efficientnet_b4': f'https://tfhub.dev/tensorflow/efficientnet/b4/{hub_type}/1',\n    'efficientnet_b5': f'https://tfhub.dev/tensorflow/efficientnet/b5/{hub_type}/1',\n    'efficientnet_b6': f'https://tfhub.dev/tensorflow/efficientnet/b6/{hub_type}/1',\n    'efficientnet_b7': f'https://tfhub.dev/tensorflow/efficientnet/b7/{hub_type}/1',\n    }\n    \n    image_size_map = {\n    'efficientnetv2-b0': 224,\n    'efficientnetv2-b1': 240,\n    'efficientnetv2-b2': 260,\n    'efficientnetv2-b3': 300,\n    'efficientnetv2-s':  384,\n    'efficientnetv2-m':  480,\n    'efficientnetv2-l':  480,\n    'efficientnetv2-xl':  512,\n  \n    'efficientnet_b0': 224,\n    'efficientnet_b1': 240,\n    'efficientnet_b2': 260,\n    'efficientnet_b3': 300,\n    'efficientnet_b4': 380,\n    'efficientnet_b5': 456,\n    'efficientnet_b6': 528,\n    'efficientnet_b7': 600,\n    }\n    \n    hub_url = hub_url_map.get(model_name + ckpt_type)\n    image_size = image_size_map.get(model_name, 224)\n    return hub_url, image_size\n","metadata":{"execution":{"iopub.status.busy":"2021-11-18T18:53:54.459985Z","iopub.execute_input":"2021-11-18T18:53:54.460270Z","iopub.status.idle":"2021-11-18T18:53:54.475066Z","shell.execute_reply.started":"2021-11-18T18:53:54.460241Z","shell.execute_reply":"2021-11-18T18:53:54.474419Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Train the model","metadata":{}},{"cell_type":"code","source":"import tensorflow_hub as hub\n\nwith strategy.scope():  \n    input_shape = [*IMAGE_SIZE, 3]  \n    hub_url,_ = get_hub_url_and_isize('efficientnetv2-xl', '21k', 'classification') # 'gs://cloud-tpu-checkpoints/efficientnet/v2/hub/efficientnetv2-xl-21k/classification'\n    model = tf.keras.Sequential([\n        tf.keras.layers.InputLayer(input_shape=input_shape),\n        hub.KerasLayer(hub_url, trainable=True),\n        tf.keras.layers.Dropout(rate=0.2),\n        tf.keras.layers.Dense(104, activation='softmax'),\n    ])\n    print(model.summary())\n    model.compile(\n        optimizer='adam',\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                       )","metadata":{"execution":{"iopub.status.busy":"2021-11-18T18:54:09.508005Z","iopub.execute_input":"2021-11-18T18:54:09.508544Z","iopub.status.idle":"2021-11-18T19:00:59.346382Z","shell.execute_reply.started":"2021-11-18T18:54:09.508493Z","shell.execute_reply":"2021-11-18T19:00:59.344812Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pd.DataFrame(history.history).plot()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-11-18T19:00:59.347223Z","iopub.status.idle":"2021-11-18T19:00:59.347569Z","shell.execute_reply.started":"2021-11-18T19:00:59.347402Z","shell.execute_reply":"2021-11-18T19:00:59.347418Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Confusion matrix","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.'])\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\nscore = 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-11-18T19:01:11.485550Z","iopub.execute_input":"2021-11-18T19:01:11.485900Z","iopub.status.idle":"2021-11-18T19:02:12.156130Z","shell.execute_reply.started":"2021-11-18T19:01:11.485864Z","shell.execute_reply":"2021-11-18T19:02:12.155074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submit predictions","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.\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\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-11-18T19:00:59.351511Z","iopub.status.idle":"2021-11-18T19:00:59.351847Z","shell.execute_reply.started":"2021-11-18T19:00:59.351669Z","shell.execute_reply":"2021-11-18T19:00:59.351690Z"},"trusted":true},"execution_count":null,"outputs":[]}]}