{"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":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\n\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2022-01-12T18:49:00.222969Z","iopub.execute_input":"2022-01-12T18:49:00.223491Z","iopub.status.idle":"2022-01-12T18:49:00.367529Z","shell.execute_reply.started":"2022-01-12T18:49:00.223458Z","shell.execute_reply":"2022-01-12T18:49:00.366706Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\nfrom kaggle_datasets import KaggleDatasets\n\nGCS_DS_PATH = KaggleDatasets().get_gcs_path(\"tpu-getting-started\")","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:49:00.369098Z","iopub.execute_input":"2022-01-12T18:49:00.369306Z","iopub.status.idle":"2022-01-12T18:49:00.809616Z","shell.execute_reply.started":"2022-01-12T18:49:00.369282Z","shell.execute_reply":"2022-01-12T18:49:00.808837Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Detect TPU, return appropriate distribution strategy\nimport tensorflow as tf\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver() \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() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:49:00.812061Z","iopub.execute_input":"2022-01-12T18:49:00.812367Z","iopub.status.idle":"2022-01-12T18:49:11.969635Z","shell.execute_reply.started":"2022-01-12T18:49:00.812325Z","shell.execute_reply":"2022-01-12T18:49:11.968594Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image_size = 512\nGCS_PATH = GCS_DS_PATH + '/tfrecords-jpeg-512x512'\nAUTO = tf.data.experimental.AUTOTUNE\n\nTRAINING_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(GCS_PATH + '/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","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:49:11.971551Z","iopub.execute_input":"2022-01-12T18:49:11.97179Z","iopub.status.idle":"2022-01-12T18:49:12.21966Z","shell.execute_reply.started":"2022-01-12T18:49:11.971762Z","shell.execute_reply":"2022-01-12T18:49:12.218674Z"},"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, [512,512, 3]) # explicit size needed for TPU\n    return image\n\ndef data_augment(image, label=None,seed = 2020):    \n    image = tf.image.random_flip_left_right(image, seed=seed)\n    image = tf.image.random_flip_up_down(image, seed=seed)\n    if label is None:\n        return image\n    else:\n        return image, label","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:49:12.220855Z","iopub.execute_input":"2022-01-12T18:49:12.2211Z","iopub.status.idle":"2022-01-12T18:49:12.228032Z","shell.execute_reply.started":"2022-01-12T18:49:12.221073Z","shell.execute_reply":"2022-01-12T18:49:12.227139Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string),\n        \"class\": tf.io.FixedLenFeature([], tf.int64),\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\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), \n        \"id\": tf.io.FixedLenFeature([], tf.string),\n    }\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\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False\n\n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO)\n    dataset = dataset.with_options(ignore_order)\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:49:12.22935Z","iopub.execute_input":"2022-01-12T18:49:12.22965Z","iopub.status.idle":"2022-01-12T18:49:12.242948Z","shell.execute_reply.started":"2022-01-12T18:49:12.229613Z","shell.execute_reply":"2022-01-12T18:49:12.242091Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"AUTO = tf.data.AUTOTUNE\nBATCH_SIZE = 64\ntrain_dataset = (load_dataset(TRAINING_FILENAMES, labeled=True)\n    .cache()\n    .map(data_augment, num_parallel_calls=AUTO)\n    .repeat()\n    .shuffle(512)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n    )\n\nvalid_dataset = (load_dataset(VALIDATION_FILENAMES, labeled=True)\n    .batch(BATCH_SIZE)\n    .cache()\n    .prefetch(AUTO)\n    )\ntest_dataset = (load_dataset(TEST_FILENAMES, labeled=False)\n    .map(data_augment, num_parallel_calls=AUTO)\n    .batch(BATCH_SIZE)\n        )","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:49:12.244091Z","iopub.execute_input":"2022-01-12T18:49:12.244413Z","iopub.status.idle":"2022-01-12T18:49:12.656252Z","shell.execute_reply.started":"2022-01-12T18:49:12.244371Z","shell.execute_reply":"2022-01-12T18:49:12.65524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport math, re, os\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)\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-01-12T18:49:12.658038Z","iopub.execute_input":"2022-01-12T18:49:12.658715Z","iopub.status.idle":"2022-01-12T18:49:12.666484Z","shell.execute_reply.started":"2022-01-12T18:49:12.65867Z","shell.execute_reply":"2022-01-12T18:49:12.665399Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Training:\", train_dataset)\nprint (\"Validation:\", valid_dataset)\nprint(\"Test:\", test_dataset)\n\n\n# for image, label in train_dataset.take(3):\n#     print(CLASSES[label.numpy()[0]])\n#     imgplot = plt.imshow(image.numpy()[0])\n#     plt.show()","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:49:12.667551Z","iopub.execute_input":"2022-01-12T18:49:12.667813Z","iopub.status.idle":"2022-01-12T18:49:12.6856Z","shell.execute_reply.started":"2022-01-12T18:49:12.667783Z","shell.execute_reply":"2022-01-12T18:49:12.684782Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow import keras\nfrom kaggle_datasets import KaggleDatasets\nfrom tensorflow.keras.models import Sequential\nimport tensorflow.keras.layers as L\nfrom tensorflow.keras.applications import InceptionResNetV2\nfrom tensorflow.keras.layers import Dense, GlobalAveragePooling2D\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:49:12.689099Z","iopub.execute_input":"2022-01-12T18:49:12.689845Z","iopub.status.idle":"2022-01-12T18:49:12.696477Z","shell.execute_reply.started":"2022-01-12T18:49:12.689798Z","shell.execute_reply":"2022-01-12T18:49:12.695543Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    model = tf.keras.Sequential([\n        InceptionResNetV2(\n            input_shape=(image_size, image_size, 3),\n            include_top=False\n        ),\n        L.GlobalMaxPooling2D(),\n        L.Dense(104, activation='softmax')\n    ])\n        \n    model.compile(\n        optimizer='adam',\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy'],\n    )","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:49:12.697714Z","iopub.execute_input":"2022-01-12T18:49:12.698405Z","iopub.status.idle":"2022-01-12T18:49:50.344538Z","shell.execute_reply.started":"2022-01-12T18:49:12.69837Z","shell.execute_reply":"2022-01-12T18:49:50.34359Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.compile(\n#     optimizer='adam',\n#     loss = 'sparse_categorical_crossentropy',\n#     metrics=['sparse_categorical_accuracy'],\n# )\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:49:50.345771Z","iopub.execute_input":"2022-01-12T18:49:50.346018Z","iopub.status.idle":"2022-01-12T18:49:50.406814Z","shell.execute_reply.started":"2022-01-12T18:49:50.345975Z","shell.execute_reply":"2022-01-12T18:49:50.405786Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"LR_START = 0.0001\nLR_MAX = 0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.0001\nLR_RAMPUP_EPOCHS = 4\nLR_SUSTAIN_EPOCHS = 6\nLR_EXP_DECAY = .8\nEPOCHS = 40\n\ndef lrfn(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(lrfn, verbose=True)\n\nrng = [i for i in range(EPOCHS)]\ny = [lrfn(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":"2022-01-12T18:49:50.408786Z","iopub.execute_input":"2022-01-12T18:49:50.409314Z","iopub.status.idle":"2022-01-12T18:49:50.682775Z","shell.execute_reply.started":"2022-01-12T18:49:50.409244Z","shell.execute_reply":"2022-01-12T18:49:50.681811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_checkpoint_callback = tf.keras.callbacks.ModelCheckpoint(\n    filepath='model_1.h5',\n    save_weights_only=True,\n    monitor='val_categorical_accuracy',\n    mode='max',\n    save_best_only=True)","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:49:50.684386Z","iopub.execute_input":"2022-01-12T18:49:50.684729Z","iopub.status.idle":"2022-01-12T18:49:50.689293Z","shell.execute_reply.started":"2022-01-12T18:49:50.684696Z","shell.execute_reply":"2022-01-12T18:49:50.688456Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\nhistory = model.fit(\n    train_dataset, \n    epochs=10,\n    steps_per_epoch = STEPS_PER_EPOCH,\n    callbacks=[lr_callback],\n    validation_data=valid_dataset\n)","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:56:08.32371Z","iopub.execute_input":"2022-01-12T18:56:08.324182Z","iopub.status.idle":"2022-01-12T19:06:23.810799Z","shell.execute_reply.started":"2022-01-12T18:56:08.324148Z","shell.execute_reply":"2022-01-12T19:06:23.809725Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\n\nfrom tensorflow.keras import datasets, layers, models\nimport matplotlib.pyplot as plt\nwith strategy.scope():\n    model2 = models.Sequential()\n    model2.add(layers.Conv2D(512, (3, 3), activation='relu', input_shape=(512, 512, 3)))\n    model2.add(layers.MaxPooling2D((2, 2)))\n    model2.add(layers.Conv2D(512, (3, 3), activation='relu'))\n    model2.add(layers.MaxPooling2D((2, 2)))\n    model2.add(layers.Conv2D(256, (3, 3), activation='relu'))\n    model2.add(layers.MaxPooling2D((2, 2)))\n    model2.add(layers.Conv2D(128, (3, 3), activation='relu'))\n    model2.add(layers.MaxPooling2D((2, 2)))\n    model2.add(layers.Conv2D(128, (3, 3), activation='relu'))\n    model2.add(layers.MaxPooling2D((2, 2)))\n    model2.add(layers.Conv2D(128, (3, 3), activation='relu'))\n    model2.add(layers.GlobalMaxPooling2D())\n    model2.add(layers.Dense(104,activation='softmax'))\n    model2.summary()\n    \n    model2.compile(\n    optimizer='adam',\n    loss = 'sparse_categorical_crossentropy',\n    metrics=['sparse_categorical_accuracy'],\n    )\n\n","metadata":{"execution":{"iopub.status.busy":"2022-01-12T19:06:25.406342Z","iopub.execute_input":"2022-01-12T19:06:25.407189Z","iopub.status.idle":"2022-01-12T19:06:25.724087Z","shell.execute_reply.started":"2022-01-12T19:06:25.407139Z","shell.execute_reply":"2022-01-12T19:06:25.723046Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // 64\n\nhistory = model2.fit(\n    train_dataset, \n    epochs=10,\n    steps_per_epoch = STEPS_PER_EPOCH,\n    callbacks=[lr_callback],\n    validation_data=valid_dataset\n)","metadata":{"execution":{"iopub.status.busy":"2022-01-12T19:06:25.725718Z","iopub.execute_input":"2022-01-12T19:06:25.726044Z","iopub.status.idle":"2022-01-12T19:20:52.410255Z","shell.execute_reply.started":"2022-01-12T19:06:25.725984Z","shell.execute_reply":"2022-01-12T19:20:52.409443Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // 64\n\n# history = model2.fit(\n#     train_dataset, \n#     epochs=10,\n#     steps_per_epoch = STEPS_PER_EPOCH,\n#     callbacks=[lr_callback],\n#     validation_data=valid_dataset\n# )","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:52:32.97341Z","iopub.status.idle":"2022-01-12T18:52:32.973738Z","shell.execute_reply.started":"2022-01-12T18:52:32.973565Z","shell.execute_reply":"2022-01-12T18:52:32.973588Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // 128\n\n# history = model.fit(\n#     train_dataset, \n#     epochs=10,\n#     steps_per_epoch = STEPS_PER_EPOCH,\n#     callbacks=[lr_callback],\n#     validation_data=valid_dataset\n# )","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:52:32.974965Z","iopub.status.idle":"2022-01-12T18:52:32.975327Z","shell.execute_reply.started":"2022-01-12T18:52:32.975152Z","shell.execute_reply":"2022-01-12T18:52:32.975174Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    model3 = tf.keras.Sequential([\n        InceptionResNetV2(\n            input_shape=(image_size, image_size, 3),\n            weights = 'imagenet',\n            include_top=False\n        ),\n        L.GlobalMaxPooling2D(),\n        L.Dense(104, activation='softmax')\n    ])\n        \n    model3.compile(\n        optimizer='adam',\n        loss = 'sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy'],\n    )","metadata":{"execution":{"iopub.status.busy":"2022-01-12T19:20:52.411945Z","iopub.execute_input":"2022-01-12T19:20:52.41228Z","iopub.status.idle":"2022-01-12T19:21:25.43961Z","shell.execute_reply.started":"2022-01-12T19:20:52.412241Z","shell.execute_reply":"2022-01-12T19:21:25.438693Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAINING_IMAGES // 128\n\nhistory = model3.fit(\n    train_dataset, \n    epochs=10,\n    steps_per_epoch = STEPS_PER_EPOCH,\n    callbacks=[lr_callback],\n    validation_data=valid_dataset\n)","metadata":{"execution":{"iopub.status.busy":"2022-01-12T19:21:25.44099Z","iopub.execute_input":"2022-01-12T19:21:25.441325Z","iopub.status.idle":"2022-01-12T19:29:41.738402Z","shell.execute_reply.started":"2022-01-12T19:21:25.441285Z","shell.execute_reply":"2022-01-12T19:29:41.737562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Computing predictions...')\ntest_images_ds = test_dataset.map(lambda image, idnum: image)\nprobabilities = model3.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:52:32.979438Z","iopub.status.idle":"2022-01-12T18:52:32.980112Z","shell.execute_reply.started":"2022-01-12T18:52:32.979878Z","shell.execute_reply":"2022-01-12T18:52:32.979902Z"},"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# 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-01-12T18:52:32.981809Z","iopub.status.idle":"2022-01-12T18:52:32.982909Z","shell.execute_reply.started":"2022-01-12T18:52:32.982726Z","shell.execute_reply":"2022-01-12T18:52:32.982746Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\n\ncmdataset = valid_dataset\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":"2022-01-12T20:25:21.303628Z","iopub.execute_input":"2022-01-12T20:25:21.304649Z","iopub.status.idle":"2022-01-12T20:25:27.346014Z","shell.execute_reply.started":"2022-01-12T20:25:21.304597Z","shell.execute_reply":"2022-01-12T20:25:27.345069Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sn\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndf_cm = pd.DataFrame(cmat)\nsn.set(font_scale=1.4) # for label size\nsn.heatmap(df_cm, annot=True, annot_kws={\"size\": 1}) # font size\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-01-12T20:25:27.347856Z","iopub.execute_input":"2022-01-12T20:25:27.348178Z","iopub.status.idle":"2022-01-12T20:26:00.824383Z","shell.execute_reply.started":"2022-01-12T20:25:27.348138Z","shell.execute_reply":"2022-01-12T20:26:00.823522Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import f1_score\n\nscore = f1_score(cm_correct_labels, cm_predictions, average='macro')\nprint(score)","metadata":{"execution":{"iopub.status.busy":"2022-01-12T20:14:11.738381Z","iopub.execute_input":"2022-01-12T20:14:11.739245Z","iopub.status.idle":"2022-01-12T20:14:11.749847Z","shell.execute_reply.started":"2022-01-12T20:14:11.739211Z","shell.execute_reply":"2022-01-12T20:14:11.749108Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\n\ncmdataset = valid_dataset\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 = model2.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":"2022-01-12T20:26:00.827103Z","iopub.execute_input":"2022-01-12T20:26:00.827797Z","iopub.status.idle":"2022-01-12T20:26:09.945502Z","shell.execute_reply.started":"2022-01-12T20:26:00.827745Z","shell.execute_reply":"2022-01-12T20:26:09.944551Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sn\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndf_cm = pd.DataFrame(cmat)\nsn.set(font_scale=1.4) # for label size\nsn.heatmap(df_cm, annot=True, annot_kws={\"size\": 1}) # font size\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-01-12T20:26:09.947421Z","iopub.execute_input":"2022-01-12T20:26:09.947677Z","iopub.status.idle":"2022-01-12T20:26:43.725761Z","shell.execute_reply.started":"2022-01-12T20:26:09.947648Z","shell.execute_reply":"2022-01-12T20:26:43.724927Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import f1_score\n\nscore = f1_score(cm_correct_labels, cm_predictions, average='macro')\nprint(score)","metadata":{"execution":{"iopub.status.busy":"2022-01-12T20:14:54.045388Z","iopub.execute_input":"2022-01-12T20:14:54.045599Z","iopub.status.idle":"2022-01-12T20:14:54.056750Z","shell.execute_reply.started":"2022-01-12T20:14:54.045573Z","shell.execute_reply":"2022-01-12T20:14:54.055944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix\n\ncmdataset = valid_dataset\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 = model3.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":"2022-01-12T20:26:43.727918Z","iopub.execute_input":"2022-01-12T20:26:43.728196Z","iopub.status.idle":"2022-01-12T20:26:49.826263Z","shell.execute_reply.started":"2022-01-12T20:26:43.728166Z","shell.execute_reply":"2022-01-12T20:26:49.825209Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sn\nimport pandas as pd\nimport matplotlib.pyplot as plt\n\n\ndf_cm = pd.DataFrame(cmat)\nsn.set(font_scale=1.4) # for label size\nsn.heatmap(df_cm, annot=True, annot_kws={\"size\": 1}) # font size\nplt.show()","metadata":{"_kg_hide-output":false,"execution":{"iopub.status.busy":"2022-01-12T20:26:49.827714Z","iopub.execute_input":"2022-01-12T20:26:49.828068Z","iopub.status.idle":"2022-01-12T20:27:22.608840Z","shell.execute_reply.started":"2022-01-12T20:26:49.828023Z","shell.execute_reply":"2022-01-12T20:27:22.608038Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import f1_score\n\nscore = f1_score(cm_correct_labels, cm_predictions, average='macro')\nprint(score)","metadata":{"execution":{"iopub.status.busy":"2022-01-12T20:15:28.046600Z","iopub.execute_input":"2022-01-12T20:15:28.047063Z","iopub.status.idle":"2022-01-12T20:15:28.057611Z","shell.execute_reply.started":"2022-01-12T20:15:28.047018Z","shell.execute_reply":"2022-01-12T20:15:28.056640Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model3.summary()","metadata":{"execution":{"iopub.status.busy":"2022-01-12T20:28:06.630713Z","iopub.execute_input":"2022-01-12T20:28:06.631582Z","iopub.status.idle":"2022-01-12T20:28:06.699421Z","shell.execute_reply.started":"2022-01-12T20:28:06.631543Z","shell.execute_reply":"2022-01-12T20:28:06.698502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from matplotlib import pyplot as plt\n\ndef batch_to_numpy_images_and_labels(data):\n    images, labels = data\n    numpy_images = images.numpy()\n    numpy_labels = labels.numpy()\n    if numpy_labels.dtype == object: # 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":"2022-01-12T20:47:02.305183Z","iopub.execute_input":"2022-01-12T20:47:02.305901Z","iopub.status.idle":"2022-01-12T20:47:02.327926Z","shell.execute_reply.started":"2022-01-12T20:47:02.305864Z","shell.execute_reply":"2022-01-12T20:47:02.327073Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = valid_dataset\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)\n\nimages, labels = next(batch)\nprobabilities = model.predict(images)\npredictions = np.argmax(probabilities, axis=-1)\ndisplay_batch_of_images((images, labels), predictions)","metadata":{"execution":{"iopub.status.busy":"2022-01-12T20:47:05.115098Z","iopub.execute_input":"2022-01-12T20:47:05.115684Z","iopub.status.idle":"2022-01-12T20:47:09.104323Z","shell.execute_reply.started":"2022-01-12T20:47:05.115640Z","shell.execute_reply":"2022-01-12T20:47:09.103162Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = valid_dataset\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)\n\nimages, labels = next(batch)\nprobabilities = model2.predict(images)\npredictions = np.argmax(probabilities, axis=-1)\ndisplay_batch_of_images((images, labels), predictions)","metadata":{"execution":{"iopub.status.busy":"2022-01-12T20:47:30.147117Z","iopub.execute_input":"2022-01-12T20:47:30.147672Z","iopub.status.idle":"2022-01-12T20:47:41.519675Z","shell.execute_reply.started":"2022-01-12T20:47:30.147621Z","shell.execute_reply":"2022-01-12T20:47:41.518385Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = valid_dataset\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)\n\nimages, labels = next(batch)\nprobabilities = model2.predict(images)\npredictions = np.argmax(probabilities, axis=-1)\ndisplay_batch_of_images((images, labels), predictions)","metadata":{"execution":{"iopub.status.busy":"2022-01-12T20:47:45.438644Z","iopub.execute_input":"2022-01-12T20:47:45.439250Z","iopub.status.idle":"2022-01-12T20:47:49.317857Z","shell.execute_reply.started":"2022-01-12T20:47:45.439203Z","shell.execute_reply":"2022-01-12T20:47:49.317033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# with strategy.scope():\n#     model4 = tf.keras.Sequential([\n#         efn.EfficientNetB7(\n#             weights='imagenet', include_top=False, pooling='avg', input_shape=(image_size, image_size, 3)\n#         ),\n#         L.Dense(4, activation='softmax')\n#     ])\n        \n#     model4.compile(\n#         optimizer = 'adam',\n#         loss = 'categorical_crossentropy',\n#         metrics=['categorical_accuracy']\n#     )\n#     model4.summary()","metadata":{"execution":{"iopub.status.busy":"2022-01-12T18:52:32.987178Z","iopub.status.idle":"2022-01-12T18:52:32.987795Z","shell.execute_reply.started":"2022-01-12T18:52:32.987574Z","shell.execute_reply":"2022-01-12T18:52:32.987603Z"},"trusted":true},"execution_count":null,"outputs":[]}]}