{"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":"# Petals to the Metal - Flower Classification\n\nKaggle competition: [here](https://www.kaggle.com/c/tpu-getting-started)","metadata":{"id":"HrWLNacl94cj"}},{"cell_type":"markdown","source":"# Step 1: Imports #\n\nWe begin by importing several Python packages.","metadata":{"id":"ssgHkMbJ-_B8"}},{"cell_type":"code","source":"import math, re, os\nimport numpy as np\nimport tensorflow as tf\n\nprint(\"Tensorflow version \" + tf.__version__)","metadata":{"id":"ZU9Cwhnk-_B9","outputId":"734a5308-9b0e-462d-8fd0-052237672cb0","execution":{"iopub.status.busy":"2022-09-08T12:28:09.362665Z","iopub.execute_input":"2022-09-08T12:28:09.363498Z","iopub.status.idle":"2022-09-08T12:28:14.148405Z","shell.execute_reply.started":"2022-09-08T12:28:09.363388Z","shell.execute_reply":"2022-09-08T12:28:14.147409Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 2: Distribution Strategy #\n\nDetecting tpu, i managed to try TPU while experimenting. But for final model i fit it on gpu","metadata":{"id":"IqD4mTF7-_CA"}},{"cell_type":"code","source":"# Detect TPU, return appropriate distribution strategy\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.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"id":"K1pwzOnh-_CB","outputId":"83fc9993-9688-41a5-bdaa-226665d5ada1","execution":{"iopub.status.busy":"2022-09-08T12:28:14.153339Z","iopub.execute_input":"2022-09-08T12:28:14.155917Z","iopub.status.idle":"2022-09-08T12:28:14.174338Z","shell.execute_reply.started":"2022-09-08T12:28:14.155877Z","shell.execute_reply":"2022-09-08T12:28:14.173448Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n\n# Step 3: Loading the Competition Data #\n\n## Get GCS Path ##\n\nAviable only in kaggle notebook, for working in colab i manualy take it as a string","metadata":{"id":"nJWDaq5--_CD"}},{"cell_type":"code","source":"# from kaggle_datasets import KaggleDatasets\n\n# GCS_DS_PATH = KaggleDatasets().get_gcs_path('tpu-getting-started')\n# print(GCS_DS_PATH)","metadata":{"id":"f_fsmO5Q-_CE","execution":{"iopub.status.busy":"2022-09-08T12:28:14.175282Z","iopub.execute_input":"2022-09-08T12:28:14.175629Z","iopub.status.idle":"2022-09-08T12:28:14.185575Z","shell.execute_reply.started":"2022-09-08T12:28:14.175595Z","shell.execute_reply":"2022-09-08T12:28:14.184390Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"\n\n## Load Data ##\n\nTook from [this notebook](https://www.kaggle.com/code/ryanholbrook/create-your-first-submission)","metadata":{"id":"fTbBqZ3T-_CF"}},{"cell_type":"code","source":"\nIMAGE_SIZE = [192, 192]\nPATH = 'gs://kds-b3ff303edf58b5b27fca364f366efb224ebf9debd703a256f1250285/tfrecords-jpeg-192x192'\nAUTO = tf.data.experimental.AUTOTUNE\n\nTRAINING_FILENAMES = tf.io.gfile.glob(PATH + '/train/*.tfrec')\nVALIDATION_FILENAMES = tf.io.gfile.glob(PATH + '/val/*.tfrec')\nTEST_FILENAMES = tf.io.gfile.glob(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\n\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, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset","metadata":{"_kg_hide-input":true,"id":"quTKmvvs-_CG","execution":{"iopub.status.busy":"2022-09-08T12:28:14.192041Z","iopub.execute_input":"2022-09-08T12:28:14.192733Z","iopub.status.idle":"2022-09-08T12:28:14.921881Z","shell.execute_reply.started":"2022-09-08T12:28:14.192697Z","shell.execute_reply":"2022-09-08T12:28:14.920852Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Dataset creation helper functions ##\n\n","metadata":{"id":"HqiN31oK-_CI"}},{"cell_type":"code","source":"\ndef data_augment(image, label):\n\n    image = tf.image.random_flip_left_right(image)\n    return image, label   \n\ndef get_training_dataset():\n    dataset = load_dataset(TRAINING_FILENAMES, labeled=True)\n    dataset = dataset.map(data_augment, num_parallel_calls=AUTO)\n    dataset = dataset.repeat() \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\n\ndef count_data_items(filenames):\n\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))\n","metadata":{"_kg_hide-input":true,"id":"T68gf8R2-_CJ","outputId":"c8c869ef-c5d0-4cb8-8912-10be7405b342","execution":{"iopub.status.busy":"2022-09-08T12:28:14.923474Z","iopub.execute_input":"2022-09-08T12:28:14.924598Z","iopub.status.idle":"2022-09-08T12:28:14.938465Z","shell.execute_reply.started":"2022-09-08T12:28:14.924559Z","shell.execute_reply":"2022-09-08T12:28:14.937468Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Creating datasets, and defining batch size","metadata":{"id":"3C6gsWgV-_CK"}},{"cell_type":"code","source":"\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nds_train = get_training_dataset()\nds_valid = get_validation_dataset()\nds_test = get_test_dataset()\n\nprint(\"Training:\", ds_train)\nprint (\"Validation:\", ds_valid)\nprint(\"Test:\", ds_test)","metadata":{"id":"Lu0nej1J-_CL","outputId":"8e53c807-c240-4934-9545-f3d7dd47bb1a","execution":{"iopub.status.busy":"2022-09-08T12:28:14.939982Z","iopub.execute_input":"2022-09-08T12:28:14.941235Z","iopub.status.idle":"2022-09-08T12:28:18.052561Z","shell.execute_reply.started":"2022-09-08T12:28:14.941173Z","shell.execute_reply":"2022-09-08T12:28:18.051467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 4: Explore Data #\n\nLet's take a moment to look at some of the images in the dataset.","metadata":{"id":"VV7L43-H-_CO"}},{"cell_type":"markdown","source":"### Some helper functions.\nTook from [this Notebook](https://www.kaggle.com/code/ryanholbrook/create-your-first-submission)","metadata":{"id":"k09QKkxm7saF"}},{"cell_type":"code","source":"\nfrom 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: \n                                     \n        numpy_labels = [None for _ in enumerate(numpy_images)]\n  \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    \n    images, labels = batch_to_numpy_images_and_labels(databatch)\n    if labels is None:\n        labels = [None for _ in enumerate(images)]\n        \n  \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":{"_kg_hide-input":true,"id":"mv9rfMsm-_CP","execution":{"iopub.status.busy":"2022-09-08T12:28:18.054670Z","iopub.execute_input":"2022-09-08T12:28:18.055172Z","iopub.status.idle":"2022-09-08T12:28:18.072685Z","shell.execute_reply.started":"2022-09-08T12:28:18.055132Z","shell.execute_reply":"2022-09-08T12:28:18.071601Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 5: Define Model #\n\nI tried several models:\n\nCustom cnn models are too simple, but take too much time and memory to train.The limitations of the basic version of google colab prevent me from building a more complex one\n\n\nUsing pre-trained models shows good results, but works better if you retrain the entire architecture. What I can't do as you know\n\nI tried to optimize RAM usage by using 192x192 pictures resolutions instead of 512x512, and removing several visualisation functions of this notebook.\n\n\nSo the best result I have achieved, is by using `Xception model`, pretrained on imagenet dataset. And using 192x192 resolution in fitting.\n\n","metadata":{"id":"xsCCuhqX-_CT"}},{"cell_type":"code","source":"EPOCHS = 12\n\nwith strategy.scope():\n    pretrained_model = tf.keras.applications.xception.Xception(\n        weights='imagenet',\n        include_top=False ,\n        input_shape=[*IMAGE_SIZE, 3],\n        classes=len(CLASSES)\n    )\n    pretrained_model.trainable = False\n    \n    model = tf.keras.Sequential([\n        tf.keras.layers.Input(shape=[*IMAGE_SIZE,3]),\n        ###data augmentation\n        tf.keras.layers.RandomContrast(factor=0.5),\n        tf.keras.layers.RandomFlip(mode='horizontal'),\n        tf.keras.layers.RandomWidth(factor=0.15),\n        tf.keras.layers.RandomRotation(factor=0.10),\n        tf.keras.layers.RandomTranslation(height_factor=0.1, width_factor=0.1),\n        # pretrained base\n        pretrained_model,\n        # head\n        tf.keras.layers.GlobalAveragePooling2D(),\n        tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n    ])","metadata":{"id":"2JHjxb49-_CU","execution":{"iopub.status.busy":"2022-09-08T12:28:18.076020Z","iopub.execute_input":"2022-09-08T12:28:18.076692Z","iopub.status.idle":"2022-09-08T12:28:21.386357Z","shell.execute_reply.started":"2022-09-08T12:28:18.076658Z","shell.execute_reply":"2022-09-08T12:28:21.385408Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Unsuccessful attempt:","metadata":{"id":"1_ragV_u-NNs"}},{"cell_type":"code","source":"# with strategy.scope():\n#   model = tf.keras.Sequential([\n#       tf.keras.layers.Input(shape=[*IMAGE_SIZE, 3],\n#                             batch_size=BATCH_SIZE),\n\n#       tf.keras.layers.Conv2D(32, 3, padding=\"same\", activation=\"relu\"),\n#       tf.keras.layers.MaxPool2D(),\n      \n#       tf.keras.layers.Conv2D(64, 3, padding=\"same\", activation=\"relu\"),\n#       tf.keras.layers.MaxPool2D(),\n\n#       tf.keras.layers.Conv2D(128, 3, padding=\"same\", activation=\"relu\"),\n#       tf.keras.layers.Conv2D(128, 3, padding=\"same\", activation=\"relu\"),\n#       tf.keras.layers.MaxPool2D(),\n\n#       tf.keras.layers.GlobalAveragePooling2D(),\n#       tf.keras.layers.Dense(6, activation='relu'),\n#       tf.keras.layers.Dropout(0.2),\n#       tf.keras.layers.Dense(len(CLASSES), activation='softmax'),\n#   ])","metadata":{"id":"EiVr55UkR9Oc","execution":{"iopub.status.busy":"2022-09-08T12:28:21.391260Z","iopub.execute_input":"2022-09-08T12:28:21.391912Z","iopub.status.idle":"2022-09-08T12:28:21.400029Z","shell.execute_reply.started":"2022-09-08T12:28:21.391873Z","shell.execute_reply":"2022-09-08T12:28:21.399065Z"},"trusted":true},"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":{"id":"e0Q4JJHO-_CV","outputId":"f24af967-2876-41dd-dc07-e94cc26e16fd","execution":{"iopub.status.busy":"2022-09-08T12:28:21.407278Z","iopub.execute_input":"2022-09-08T12:28:21.410229Z","iopub.status.idle":"2022-09-08T12:28:21.447671Z","shell.execute_reply.started":"2022-09-08T12:28:21.410193Z","shell.execute_reply":"2022-09-08T12:28:21.446571Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 6: Training #\n\n## CALLBACKS ##\n\n","metadata":{"id":"YQm3Uiwj-_CV"}},{"cell_type":"markdown","source":"### LR scheduler\nWe'll train this network with a special learning rate schedule.","metadata":{"id":"z8zH1FJI5JwR"}},{"cell_type":"code","source":"LR_START = 0.00005\nLR_MAX = LR_START #0.00005 * strategy.num_replicas_in_sync\nLR_MIN = 0.00001 #LR_START\nLR_RAMPUP_EPOCHS = 0 #5\nLR_SUSTAIN_EPOCHS = 5 # 0\nLR_EXP_DECAY = 0.85\n\ndef lrfn(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:  \n        lr = LR_START + (epoch * (LR_MAX - LR_START) / LR_RAMPUP_EPOCHS)   #   np.random.random_sample() * LR_START\n    elif epoch < (LR_RAMPUP_EPOCHS + LR_SUSTAIN_EPOCHS):  ####5-7lun\n        lr = LR_MAX\n    else:    \n        lr = LR_MIN + (LR_MAX - LR_MIN) * LR_EXP_DECAY ** (epoch - LR_RAMPUP_EPOCHS - LR_SUSTAIN_EPOCHS)\n#    print('For epoch', epoch, 'setting lr to', lr)\n    return lr\n\nlr_callback = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose = True)\n\nrng = [i for i in range(30)]\ny = [lrfn(x) for x in rng]\nplt.plot(rng, y)","metadata":{"_kg_hide-input":true,"id":"sj0T_eb2-_CW","outputId":"053b2728-eccb-499c-f728-8e1ab56e1edc","execution":{"iopub.status.busy":"2022-09-08T12:28:21.452115Z","iopub.execute_input":"2022-09-08T12:28:21.454755Z","iopub.status.idle":"2022-09-08T12:28:21.702335Z","shell.execute_reply.started":"2022-09-08T12:28:21.454708Z","shell.execute_reply":"2022-09-08T12:28:21.701285Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### EarlyStop callback","metadata":{"id":"F3XiZhN95BE_"}},{"cell_type":"code","source":"early_stop = tf.keras.callbacks.EarlyStopping(monitor='val_loss', patience=4, restore_best_weights = True)","metadata":{"id":"XyD1nxL9agIG","execution":{"iopub.status.busy":"2022-09-08T12:28:21.703927Z","iopub.execute_input":"2022-09-08T12:28:21.704551Z","iopub.status.idle":"2022-09-08T12:28:21.710953Z","shell.execute_reply.started":"2022-09-08T12:28:21.704505Z","shell.execute_reply":"2022-09-08T12:28:21.709736Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Fit Model ##\n\nWe're ready to train the model.","metadata":{"id":"8JCIYJKb-_CX"}},{"cell_type":"code","source":"import shutil # for archives with models\n# Define training epochs\nEPOCHS = 30\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\n\n\nloaded_model = False\n# if os.path.exists(\"/content/models/xception_model\") or \\\n#  os.path.exists(\"/content/xception_model.zip\"):\n#   loaded_model = True\nimport os\nif loaded_model:\n  if not os.path.exists(\"/content/models/xception_model\"):\n    shutil.unpack_archive(\"/content/xception_model.zip\", \"/content/models/\")\n  model = tf.keras.models.load_model(\"/content/models/xception_model\")\nelse:\n  history = model.fit(\n      ds_train,\n      validation_data=ds_valid,\n      epochs=EPOCHS,\n      steps_per_epoch=STEPS_PER_EPOCH,\n      callbacks=[early_stop, lr_callback],\n  )","metadata":{"id":"r8iDkGVk-_CX","outputId":"43fa1992-3c6e-4550-cc39-1e3a3e7a3609","execution":{"iopub.status.busy":"2022-09-08T12:28:21.713378Z","iopub.execute_input":"2022-09-08T12:28:21.714375Z","iopub.status.idle":"2022-09-08T12:48:29.977731Z","shell.execute_reply.started":"2022-09-08T12:28:21.714340Z","shell.execute_reply":"2022-09-08T12:48:29.976512Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Saving model for future use","metadata":{"id":"bOw1BB7a4uGw"}},{"cell_type":"code","source":"if not loaded_model:\n  tf.keras.models.save_model(\n      model,\n      \"models/xception_model\",\n      overwrite=True,\n      include_optimizer=True,\n      save_traces=True\n  )","metadata":{"id":"tsyv6tyOqjxP"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# if not loaded_model:\n#   shutil.make_archive(\"xception_model\", \"zip\", \"/content/models/xception_model\")","metadata":{"id":"LwvL83vD1OUp","outputId":"ea7544cf-0ff6-4511-d711-b0a58cc9fd64"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"##Loss and metrics during training graph:\n\n\nFortunately, it converges","metadata":{"id":"7QJKabIm-_CX"}},{"cell_type":"code","source":"if not loaded_model:\n  display_training_curves(\n    history.history['loss'],\n    history.history['val_loss'],\n    'loss',\n    211,\n  )\n  display_training_curves(\n    history.history['sparse_categorical_accuracy'],\n    history.history['val_sparse_categorical_accuracy'],\n    'accuracy',\n    212,\n  )","metadata":{"id":"IS_IarZ8-_CY","outputId":"9a46292d-164b-4cb2-d17e-8ff3d9b8f7e5","execution":{"iopub.status.busy":"2022-09-08T12:48:54.421571Z","iopub.execute_input":"2022-09-08T12:48:54.422167Z","iopub.status.idle":"2022-09-08T12:48:54.865185Z","shell.execute_reply.started":"2022-09-08T12:48:54.422131Z","shell.execute_reply":"2022-09-08T12:48:54.864221Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Visual Validation ##\nLet's visualise what we get with 0.64 accuracy on validation set","metadata":{"id":"Gt8mROK--_Cb"}},{"cell_type":"code","source":"dataset = get_validation_dataset()\ndataset = dataset.unbatch().batch(20)\nbatch = iter(dataset)","metadata":{"id":"tUsLVHyv-_Cc"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"And here is a set of flowers with their predicted species.","metadata":{"id":"seCv-8-V-_Cc"}},{"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)","metadata":{"id":"ypMhrqKk-_Cc","outputId":"0169cb5a-fb83-4063-cba4-7cbd55122945"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Step 8: Make Test Predictions #\nCells above should generate predictions for submit","metadata":{"id":"HnMPj0lU-_Cc"}},{"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)\n# print(predictions)","metadata":{"id":"ngxuVbzy-_Cd","outputId":"e9074149-0182-47e0-ebf5-1f468dd449a7"},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Generating `submissions.csv`","metadata":{"id":"GHZfl_5X-_Cd"}},{"cell_type":"code","source":"print('Generating submission.csv file...')\n\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')\n\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","metadata":{"id":"IFulrbj4-_Cd","outputId":"d7ac2c74-efbf-45bb-d486-faad1e9cc3ce"},"execution_count":null,"outputs":[]}]}