{"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":"!pip install -q efficientnet","metadata":{},"execution_count":null,"outputs":[]},{"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\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\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":"2023-08-14T04:48:13.693293Z","iopub.execute_input":"2023-08-14T04:48:13.694098Z","iopub.status.idle":"2023-08-14T04:48:14.125803Z","shell.execute_reply.started":"2023-08-14T04:48:13.694063Z","shell.execute_reply":"2023-08-14T04:48:14.124894Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras import applications as tf_app\nfrom tensorflow.keras.callbacks import ModelCheckpoint, LambdaCallback, EarlyStopping\n\nimport math, re, os\nimport random\nimport efficientnet.tfkeras as efn","metadata":{"execution":{"iopub.status.busy":"2023-08-14T04:48:14.127419Z","iopub.execute_input":"2023-08-14T04:48:14.127805Z","iopub.status.idle":"2023-08-14T04:48:43.359702Z","shell.execute_reply.started":"2023-08-14T04:48:14.127764Z","shell.execute_reply":"2023-08-14T04:48:43.358676Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() \n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2023-08-14T04:48:43.360966Z","iopub.execute_input":"2023-08-14T04:48:43.361481Z","iopub.status.idle":"2023-08-14T04:48:51.914110Z","shell.execute_reply.started":"2023-08-14T04:48:43.361449Z","shell.execute_reply":"2023-08-14T04:48:51.913102Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\n# from kaggle_datasets import kaggleDatasets \n\n# GCS_DS_PATH = kaggleDatasets().get_gcs_path()\n# Variable definitions\n\n# /kaggle/input/tpu-getting-started/tfrecords-jpeg-512x512\n\ntfrec_dataset = \"/kaggle/input/tpu-getting-started/tfrecords-jpeg-512x512\"\ntf_flower_dataset = \"/kaggle/input/tf-flower-photo-tfrec\"\nIMAGE_SIZE = [512, 512]\nAUTO = tf.data.experimental.AUTOTUNE\nEPOCHS = 30\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\nSEED = 9\n\n\nIMAGENET_FILES = tf.io.gfile.glob(tf_flower_dataset + '/imagenet/tfrecords-jpeg-512x512/*.tfrec')\nINATURELIST_FILES = tf.io.gfile.glob(tf_flower_dataset + '/inaturalist/tfrecords-jpeg-512x512/*.tfrec')\nOPENIMAGE_FILES = tf.io.gfile.glob(tf_flower_dataset + '/openimage/tfrecords-jpeg-512x512/*.tfrec')\nOXFORD_FILES = tf.io.gfile.glob(tf_flower_dataset + '/oxford_102/tfrecords-jpeg-512x512/*.tfrec')\nTENSORFLOW_FILES = tf.io.gfile.glob(tf_flower_dataset + '/tf_flowers/tfrecords-jpeg-512x512/*.tfrec')\n\nADDITIONAL_TRAINING_FILENAMES = IMAGENET_FILES + INATURELIST_FILES + OPENIMAGE_FILES + OXFORD_FILES + TENSORFLOW_FILES  \n\ntraining_filenames = tf.io.gfile.glob(tfrec_dataset + '/train/*.tfrec') + ADDITIONAL_TRAINING_FILENAMES\nvalidation_filenames = tf.io.gfile.glob(tfrec_dataset + '/val/*.tfrec')\ntest_filenames = tf.io.gfile.glob(tfrec_dataset + '/test/*.tfrec')\n\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']","metadata":{"execution":{"iopub.status.busy":"2023-08-14T04:48:51.916198Z","iopub.execute_input":"2023-08-14T04:48:51.916507Z","iopub.status.idle":"2023-08-14T04:48:52.375737Z","shell.execute_reply.started":"2023-08-14T04:48:51.916480Z","shell.execute_reply":"2023-08-14T04:48:52.374611Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Count how many images we have to work with.\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\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nVALIDATION_STEPS = -(-NUM_VALIDATION_IMAGES // BATCH_SIZE)\n\nprint('Dataset: {} training images, {} validation images, {} unlabeled test images'\n      .format(NUM_TRAINING_IMAGES, NUM_VALIDATION_IMAGES, NUM_TEST_IMAGES))\n\n\n","metadata":{"execution":{"iopub.status.busy":"2023-08-14T04:48:52.377011Z","iopub.execute_input":"2023-08-14T04:48:52.377417Z","iopub.status.idle":"2023-08-14T04:48:52.381954Z","shell.execute_reply.started":"2023-08-14T04:48:52.377387Z","shell.execute_reply":"2023-08-14T04:48:52.381006Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Define a funtion to handle our random seeds\ndef seed_everything(seed=SEED):\n    random.seed(seed)\n    os.environ['PYTHONHASHSEED'] = str(seed)\n    np.random.seed(seed)\n    tf.random.set_seed(seed)\n    \nseed_everything(SEED)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Begin loading in the data\ndef decode_image(image_data):\n    image = tf.image.decode_jpeg(image_data, channels=3)\n    # Normalize the images. That is, make them assume a value between 1 and 0.\n    image = tf.cast(image, tf.float32) / 255.0\n    # Reshape image \n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image\n    \n\ndef read_labelled_tfrecord(example):\n    labelled_features = {\n        'image': tf.io.FixedLenFeature([], tf.string),\n        'class': tf.io.FixedLenFeature([], tf.int64),\n    }\n    parsed = tf.io.parse_single_example(example, labelled_features)\n    image = decode_image(parsed['image'])\n    label = tf.cast(parsed['class'], tf.int32)\n    \n    return image, label\n\n\ndef read_unlabelled_tfrecord(example):\n    unlabelled_features = {\n        'image': tf.io.FixedLenFeature([], tf.string),\n        'id': tf.io.FixedLenFeature([], tf.string)\n    }\n    parsed = tf.io.parse_single_example(example, unlabelled_features)\n    image = decode_image(parsed['image'])\n    idnum = parsed['id']\n    \n    return image, idnum\n\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        \n    dataset = tf.data.TFRecordDataset(filenames, num_parallel_reads=AUTO) # automatically interleaves reads from multiple files\n#     print(dataset)\n    \n#     if dataset.element_spec is None:\n#         print(\"The dataset is empty\")\n#     else:\n#         print(\"The dataset is not empty\")\n        \n#     for item in dataset.take(1):\n#         print(item)\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_labelled_tfrecord if labeled else read_unlabelled_tfrecord, num_parallel_calls=AUTO)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    \n    return dataset","metadata":{"execution":{"iopub.status.busy":"2023-08-15T21:50:07.122560Z","iopub.execute_input":"2023-08-15T21:50:07.123300Z","iopub.status.idle":"2023-08-15T21:50:07.150771Z","shell.execute_reply.started":"2023-08-15T21:50:07.123264Z","shell.execute_reply":"2023-08-15T21:50:07.149552Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Augment/transform data\ndef data_augment(image, label):\n    # Thanks to the dataset.prefetch(AUTO)\n    # statement in the next function (below), this happens essentially\n    # for free on TPU. Data pipeline code is executed on the \"CPU\"\n    # part of the TPU while the TPU itself is computing gradients.\n    image = tf.image.random_flip_left_right(image)\n    #image = tf.image.random_saturation(image, 0, 2)\n    return image, label   \n\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() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTO) # prefetch next batch while training (autotune prefetch buffer size)\n    return dataset\n\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\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":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # Define the batch size. This will be 16 with TPU off and 128 (=16*8) with TPU on\n# BATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\n# Now get our data.\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":{"execution":{"iopub.status.busy":"2023-08-14T04:48:52.413657Z","iopub.execute_input":"2023-08-14T04:48:52.414008Z","iopub.status.idle":"2023-08-14T04:48:54.767914Z","shell.execute_reply.started":"2023-08-14T04:48:52.413982Z","shell.execute_reply":"2023-08-14T04:48:54.766308Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"np.set_printoptions(threshold=15, linewidth=80)\n\n# Display shape of training images\nprint(\"Training data shapes:\")\nfor image, label in ds_train.take(3):\n    print(image.numpy().shape, label.numpy().shape)\n    \n    # Display label\n    print(\"Training data label examples:\", label.numpy())","metadata":{"execution":{"iopub.status.busy":"2023-08-14T04:48:54.768700Z","iopub.status.idle":"2023-08-14T04:48:54.769078Z","shell.execute_reply.started":"2023-08-14T04:48:54.768897Z","shell.execute_reply":"2023-08-14T04:48:54.768915Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def visualize_images(dataset, num_images=5):\n    plt.figure(figsize=(15, 10))\n    for i, (batch_images, batch_labels) in enumerate(dataset.take(1)):  # Take 1 batch\n        for j in range(num_images):\n            plt.subplot(1, num_images, j + 1)\n            plt.imshow(batch_images[j].numpy())\n            plt.title(CLASSES[batch_labels[j].numpy()])\n            plt.axis('off')\n    plt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"visualize_images(ds_train)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Now we define a learning rate function to help the model learn better.\nMAX_LR = 0.00005 * strategy.num_replicas_in_sync\n\ndef calculate_learning_rate(epoch,\n                            start_lr=0.00001, min_lr=0.00001, max_lr=MAX_LR,\n                            rampup_epochs=5, sustain_epochs=0,\n                            exp_decay=0.8):\n    \n\n    def compute_lr(epoch, start_lr, min_lr, max_lr, rampup_epochs, sustain_epochs, exp_decay):\n        if epoch < rampup_epochs:\n            lr = ((max_lr - start_lr) /\n                  rampup_epochs * epoch + start_lr)\n        elif epoch < rampup_epochs + sustain_epochs:\n            lr = max_lr\n        else:\n            lr = ((max_lr - min_lr) *\n                  exp_decay**(epoch - rampup_epochs - sustain_epochs) +\n                  min_lr)\n        return lr\n    \n    \n\n    return compute_lr(epoch,\n                      start_lr,\n                      min_lr,\n                      max_lr,\n                      rampup_epochs,\n                      sustain_epochs,\n                      exp_decay)\n\nlearning_rate_callback = tf.keras.callbacks.LearningRateScheduler(calculate_learning_rate, verbose=True)\n\n# You can use the code below to visualize the learning rate schedule\n# epoch_range = [i for i in range(EPOCHS)]\n# lr_values = [calculate_learning_rate(x) for x in epoch_range]\n# plt.plot(epoch_range, lr_values)\n# print(\"Learning rate schedule: {:.3g} to {:.3g} to {:.3g}\".format(lr_values[0], max(lr_values), lr_values[-1]))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Now we define a train model function.\n# Thanks to inspiration from @kalakagat. I will be making use of an essemble solution.\n\n\ndef train_model(net, used_model, best_model, seed, weights):\n    # Prepare the model within a special environment for better performance\n    with strategy.scope():\n        # Create the base model using a specific architecture\n        base_model = getattr(net, used_model)(\n                        weights=weights,\n                        include_top=False,\n                        input_shape=(*IMAGE_SIZE, 3))\n        \n        # Build the complete model by adding new layers on top\n        model = tf.keras.Sequential([\n            base_model,\n            # ... add new layers to classify the images\n            tf.keras.layers.GlobalAveragePooling2D(),\n            tf.keras.layers.Dense(len(CLASSES), activation='softmax')\n        ])\n        \n        # Configure how the model will learn\n        model.compile(\n            optimizer='nadam',\n            loss='sparse_categorical_crossentropy',\n            metrics=['sparse_categorical_accuracy']\n        )\n        \n        \n    \n    # Display the model's architecture\n    model.summary()\n    \n    # Load the best model weights saved during training\n#     model.load_weights(f'/kaggle/input/models/{best_model}_best.h5')\n    \n    # Return the trained model and training history\n    return model\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Thanks to inspiration from @kalakagat. I will be making use of an essemble solution.\n\nSEED = 1\nseed_everything(SEED)\nmodel1 = train_model(tf_app, 'Xception', 'Xception(seed1)', SEED, 'imagenet')\nSEED = 2\nseed_everything(SEED)\nmodel2 = train_model(tf_app, 'Xception', 'Xception(seed2 flip)', SEED, 'imagenet')\nSEED = 3\nseed_everything(SEED)\nmodel3 = train_model(tf_app, 'DenseNet201', 'DenseNet201(seed3)', SEED, 'imagenet')\nSEED = 4\nseed_everything(SEED)\nmodel4 = train_model(tf_app, 'DenseNet201', 'DenseNet201(seed4 flip)', SEED, 'imagenet')\nSEED = 5\nseed_everything(SEED)\nmodel5 = train_model(tf_app, 'DenseNet201', 'DenseNet201(seed6 flip)', SEED, 'imagenet')\nSEED = 6\nseed_everything(SEED)\nmodel6 = train_model(tf_app, 'DenseNet201', 'DenseNet201(seed8 p0.7)', SEED, 'imagenet')\nSEED = 7\nseed_everything(SEED)\nmodel7 = train_model(efn, 'EfficientNetB7', 'EfficientNetB7(seed5 flip)', SEED, 'noisy-student')","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Thanks to inspiration from @kalakagat. I will be making use of an essemble solution.\n\nmodel11 = tf.keras.Sequential() # Create new empty sequential model\nfor layer in model1.layers[:-2]: # Fetch all layers of model(model1) except the last two\n    model11.add(layer) # Add each layer to newly created model11\nfor layer in model11.layers: # Fetch all layers in model11\n    layer.trainable = False # Freeze trainable weights of each layer. Effectively preventing it \n    # from learning any new features from our data. We want make use of it as is.\n    \nmodel22 = tf.keras.Sequential()\nfor layer in model2.layers[:-2]:\n    model22.add(layer)\nfor layer in model22.layers:\n    layer.trainable = False\n\nmodel33 = tf.keras.Sequential()\nfor layer in model3.layers[:-2]:\n    model33.add(layer)\nfor layer in model33.layers:\n    layer.trainable = False\n\nmodel44 = tf.keras.Sequential()\nfor layer in model4.layers[:-2]:\n    model44.add(layer)\nfor layer in model44.layers:\n    layer.trainable = False\n    \nmodel55 = tf.keras.Sequential()\nfor layer in model5.layers[:-2]:\n    model55.add(layer)\nfor layer in model55.layers:\n    layer.trainable = False\n    \nmodel66 = tf.keras.Sequential()\nfor layer in model6.layers[:-2]:\n    model66.add(layer)\nfor layer in model66.layers:\n    layer.trainable = False\n    \nmodel77 = tf.keras.Sequential()\nfor layer in model7.layers[:-2]:\n    model77.add(layer)\nfor layer in model77.layers:\n    layer.trainable = False","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Thanks to inspiration from @kalakagat. I will be making use of an essemble solution.\n\n\n# Use the strategy for distributed training\nwith strategy.scope():\n    # Define the input shape for the images\n    input_shape = (*IMAGE_SIZE, 3)\n    \n    # Create an input layer for the model\n    x = tf.keras.Input(shape=input_shape)\n    \n    # Process the input through multiple pre-trained models\n    x1 = model11(x)\n    x2 = model22(x)\n    x3 = model33(x)\n    x4 = model44(x)\n    x5 = model55(x)\n    x6 = model55(x)\n    x7 = model55(x)\n    \n    # Concatenate the outputs from different models\n    x8 = tf.keras.layers.concatenate([x1, x2, x3, x4, x5, x6, x7], axis=3)\n    \n    # Reduce spatial dimensions using global average pooling\n    x8 = tf.keras.layers.GlobalAveragePooling2D()(x8)\n    \n    # Apply dropout for regularization\n    x8 = tf.keras.layers.Dropout(6/7)(x8)\n    \n    # Add a dense layer for final classification\n    x8 = tf.keras.layers.Dense(len(CLASSES), activation='softmax')(x8)\n    \n    # Create the final model that takes input and gives output\n    out = tf.keras.Model(inputs=x, outputs=x8)\n    \n    # Compile the model with optimizer, loss, and metrics\n    out.compile(\n        optimizer='nadam',\n        loss='sparse_categorical_crossentropy',\n        metrics=['sparse_categorical_accuracy']\n    )\n\n# Display the model summary\nout.summary()\n","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Thanks to inspiration from @kalakagat. I will be making use of an essemble solution.\n\nos.makedirs('checkpoints', exist_ok=True)\n\ncheckpoint_callback = ModelCheckpoint(f'checkpoints/essembled_best.h5',\n                       save_weights_only=True,\n                       monitor='val_sparse_categorical_accuracy',\n                       mode='max',\n                       save_best_only=True,\n                       verbose=1)\n\nbest_epoch_callback = LambdaCallback(on_train_end=lambda logs: \n                             print(f\"Best val_sparse_categorical_accuracy: {checkpoint_callback.best:.4f}\"))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Thanks to inspiration from @kalakagat. I will be making use of an essemble solution.\n\nhistory = out.fit(\n    get_training_dataset(), \n    steps_per_epoch=STEPS_PER_EPOCH,\n    epochs=EPOCHS,\n    callbacks=[learning_rate_callback, checkpoint_callback, best_epoch_callback],\n    validation_data=get_validation_dataset(),\n    validation_steps=VALIDATION_STEPS,\n    shuffle = True,\n    verbose=1\n)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Make predictions with our model based on our test data.\ntest_ds = get_test_dataset(ordered=True)\n\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = out.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions)","metadata":{},"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_ds.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_count":null,"outputs":[]}]}