{"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":"## **Importing Libraries.**","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nsns.set_style(\"darkgrid\")\n\nimport tensorflow as tf\nfrom functools import partial\nfrom tensorflow import keras\nimport keras.layers as L\n\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, CSVLogger, LearningRateScheduler\n\nfrom kaggle_datasets import KaggleDatasets\n\nimport re","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:18:44.288040Z","iopub.execute_input":"2021-08-09T06:18:44.288491Z","iopub.status.idle":"2021-08-09T06:18:50.951816Z","shell.execute_reply.started":"2021-08-09T06:18:44.288404Z","shell.execute_reply":"2021-08-09T06:18:50.950517Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## **Device**","metadata":{}},{"cell_type":"code","source":"try:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()\n    print(\"Device:\", tpu.master())\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nexcept:\n    strategy = tf.distribute.get_strategy()\nprint(\"Number of replicas:\", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:18:50.953608Z","iopub.execute_input":"2021-08-09T06:18:50.953916Z","iopub.status.idle":"2021-08-09T06:18:56.698124Z","shell.execute_reply.started":"2021-08-09T06:18:50.953887Z","shell.execute_reply":"2021-08-09T06:18:56.696893Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## **Data Configuration**","metadata":{}},{"cell_type":"code","source":"AUTOTUNE = tf.data.experimental.AUTOTUNE\n\nGCS_DS_Path = KaggleDatasets().get_gcs_path('tpu-getting-started')\nprint(GCS_DS_Path)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:18:56.700594Z","iopub.execute_input":"2021-08-09T06:18:56.701085Z","iopub.status.idle":"2021-08-09T06:18:57.127995Z","shell.execute_reply.started":"2021-08-09T06:18:56.701037Z","shell.execute_reply":"2021-08-09T06:18:57.126687Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = [512,512]\nEPOCHS = 22\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nGCS_PATH = GCS_DS_Path + \"/tfrecords-jpeg-512x512\"","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:18:57.129726Z","iopub.execute_input":"2021-08-09T06:18:57.130120Z","iopub.status.idle":"2021-08-09T06:18:57.135511Z","shell.execute_reply.started":"2021-08-09T06:18:57.130078Z","shell.execute_reply":"2021-08-09T06:18:57.134397Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_files = tf.io.gfile.glob(GCS_PATH + \"/train/*.tfrec\")\nval_files = tf.io.gfile.glob(GCS_PATH + \"/val/*.tfrec\")\ntest_files = tf.io.gfile.glob(GCS_PATH + \"/test/*.tfrec\")","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:18:57.137009Z","iopub.execute_input":"2021-08-09T06:18:57.137442Z","iopub.status.idle":"2021-08-09T06:18:57.378734Z","shell.execute_reply.started":"2021-08-09T06:18:57.137402Z","shell.execute_reply":"2021-08-09T06:18:57.377605Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Train TFRecord Files:\", len(train_files))\nprint(\"Validation TFRecord Files:\", len(val_files))\nprint(\"Test TFRecord Files:\", len(test_files))","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:18:57.379993Z","iopub.execute_input":"2021-08-09T06:18:57.380353Z","iopub.status.idle":"2021-08-09T06:18:57.388200Z","shell.execute_reply.started":"2021-08-09T06:18:57.380282Z","shell.execute_reply":"2021-08-09T06:18:57.386813Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## **Decoding the Data**","metadata":{}},{"cell_type":"code","source":"def decode_image(image):\n    image = tf.image.decode_jpeg(image, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0\n    image = tf.reshape(image, [*IMAGE_SIZE, 3])\n    return image","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:19:15.144762Z","iopub.execute_input":"2021-08-09T06:19:15.145137Z","iopub.status.idle":"2021-08-09T06:19:15.150512Z","shell.execute_reply.started":"2021-08-09T06:19:15.145102Z","shell.execute_reply":"2021-08-09T06:19:15.149498Z"},"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), # 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)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:19:16.275133Z","iopub.execute_input":"2021-08-09T06:19:16.275712Z","iopub.status.idle":"2021-08-09T06:19:16.283182Z","shell.execute_reply.started":"2021-08-09T06:19:16.275663Z","shell.execute_reply":"2021-08-09T06:19:16.282150Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## **Defining Loading Models**","metadata":{}},{"cell_type":"code","source":"def load_dataset(filenames, labeled = True, ordered = False):\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disables order , increases speed\n        \n    dataset = tf.data.TFRecordDataset(\n        filenames,\n        num_parallel_reads=AUTOTUNE\n    ) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(\n        ignore_order   \n    )  # 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=AUTOTUNE\n                         ) # returns a dataset of (image, label) pairs if labeled=True or just images if labeled=False\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:19:23.775779Z","iopub.execute_input":"2021-08-09T06:19:23.776155Z","iopub.status.idle":"2021-08-09T06:19:23.781658Z","shell.execute_reply.started":"2021-08-09T06:19:23.776118Z","shell.execute_reply":"2021-08-09T06:19:23.780877Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def data_augment(image, label):\n    image = tf.image.random_flip_left_right(image)\n    #image = tf.image.random_flip_up_down(image)\n    #image = tf.image.random_saturation(image, lower=0, upper=2)\n    #image = tf.image.rot90(image)\n    return image, label\n\ndef count_data_items(filenames):\n    n = [int(re.compile(r\"-([0-9]*)\\.\").search(filename).group(1)) for filename in filenames]\n    return np.sum(n)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:20:03.437040Z","iopub.execute_input":"2021-08-09T06:20:03.437574Z","iopub.status.idle":"2021-08-09T06:20:03.442952Z","shell.execute_reply.started":"2021-08-09T06:20:03.437543Z","shell.execute_reply":"2021-08-09T06:20:03.441869Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"NUM_TRAIN_IMAGES = count_data_items(train_files)\nNUM_VAL_IMAGES = count_data_items(val_files)\nNUM_TEST_IMAGES = count_data_items(test_files)\nprint(f\"train : {NUM_TRAIN_IMAGES}, test : {NUM_TEST_IMAGES}, val : {NUM_VAL_IMAGES}\")","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:20:05.634365Z","iopub.execute_input":"2021-08-09T06:20:05.634706Z","iopub.status.idle":"2021-08-09T06:20:05.642317Z","shell.execute_reply.started":"2021-08-09T06:20:05.634677Z","shell.execute_reply":"2021-08-09T06:20:05.641226Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def get_train_dataset(filenames, labeled = True, shuffle = True):\n    dataset = load_dataset(filenames, labeled = labeled)\n    dataset = dataset.map(data_augment, num_parallel_calls = AUTOTUNE)\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(AUTOTUNE)\n    return dataset\n\ndef get_val_dataset(filenames, labeled = True, ordered = False):\n    dataset = load_dataset(filenames, labeled=labeled,ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset\n    \ndef get_test_dataset(filenames, labeled = False, ordered = False):\n    dataset = load_dataset(filenames, labeled=labeled, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.prefetch(AUTOTUNE)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:20:07.446996Z","iopub.execute_input":"2021-08-09T06:20:07.447416Z","iopub.status.idle":"2021-08-09T06:20:07.455887Z","shell.execute_reply.started":"2021-08-09T06:20:07.447373Z","shell.execute_reply":"2021-08-09T06:20:07.454879Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dataset = get_train_dataset(filenames=train_files)\nval_dataset = get_val_dataset(filenames=val_files)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:20:07.822108Z","iopub.execute_input":"2021-08-09T06:20:07.822499Z","iopub.status.idle":"2021-08-09T06:20:08.065766Z","shell.execute_reply.started":"2021-08-09T06:20:07.822463Z","shell.execute_reply":"2021-08-09T06:20:08.064645Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**LABELS**","metadata":{}},{"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']","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:20:10.403684Z","iopub.execute_input":"2021-08-09T06:20:10.404056Z","iopub.status.idle":"2021-08-09T06:20:10.413089Z","shell.execute_reply.started":"2021-08-09T06:20:10.404028Z","shell.execute_reply":"2021-08-09T06:20:10.411897Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## **Visualize some Images**","metadata":{}},{"cell_type":"code","source":"image_batch, label_batch = next(iter(val_dataset))\n\ndef show_batch(image_batch, label_batch):\n    plt.figure(figsize = [20,12])\n    for i in range(25):\n        plt.subplot(5,5,i+1)\n        plt.imshow(image_batch[i])\n        plt.title(CLASSES[label_batch[i].numpy()])\n        plt.axis('off')\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:20:12.032245Z","iopub.execute_input":"2021-08-09T06:20:12.032646Z","iopub.status.idle":"2021-08-09T06:20:13.306075Z","shell.execute_reply.started":"2021-08-09T06:20:12.032613Z","shell.execute_reply":"2021-08-09T06:20:13.305042Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"show_batch(image_batch, label_batch)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:20:13.713085Z","iopub.execute_input":"2021-08-09T06:20:13.713635Z","iopub.status.idle":"2021-08-09T06:20:17.760754Z","shell.execute_reply.started":"2021-08-09T06:20:13.713592Z","shell.execute_reply":"2021-08-09T06:20:17.759947Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## **MODEL**","metadata":{}},{"cell_type":"markdown","source":"### **Define Callbacks**","metadata":{}},{"cell_type":"code","source":"init_lr = 1e-4\nlr_schedule = tf.keras.optimizers.schedules.ExponentialDecay(\n    init_lr, decay_steps=10_000, decay_rate=0.96, staircase=True\n)\n\n\nmy_callbacks = [ModelCheckpoint(\"flowers&flowers.h5\", save_best_only=True),\n               EarlyStopping(monitor=\"val_loss\", patience=4),\n               CSVLogger(\"train.log\")]","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:39:09.236965Z","iopub.execute_input":"2021-08-09T06:39:09.237497Z","iopub.status.idle":"2021-08-09T06:39:09.244487Z","shell.execute_reply.started":"2021-08-09T06:39:09.237457Z","shell.execute_reply":"2021-08-09T06:39:09.243432Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### **Build the model.**","metadata":{}},{"cell_type":"code","source":"def make_model():\n    base_model = tf.keras.applications.DenseNet121(\n        input_shape = [*IMAGE_SIZE, 3], include_top = False, \n        weights = \"imagenet\", pooling=\"avg\"\n    )\n    \n    base_model.trainable = True\n    \n    for layer in base_model.layers[:54]:\n        layer.trainable = False\n    \n    inputs = L.Input([*IMAGE_SIZE, 3])\n    #x = tf.keras.applications.densenet.preprocess_input(inputs)\n    x = base_model(inputs)\n    #x = L.Dense(256, activation = \"relu\")(x)\n    #x = L.Dropout(0.4)(x)\n    outputs = L.Dense(104, activation = \"softmax\")(x)\n    \n    model = tf.keras.models.Model(inputs, outputs)\n    \n    model.compile(\n        optimizer = tf.keras.optimizers.Adam(learning_rate=lr_schedule),\n        loss = \"sparse_categorical_crossentropy\",\n        metrics = [\"sparse_categorical_accuracy\"]\n    )\n    \n    print(model.summary())\n    return model","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:39:10.827723Z","iopub.execute_input":"2021-08-09T06:39:10.828088Z","iopub.status.idle":"2021-08-09T06:39:10.836128Z","shell.execute_reply.started":"2021-08-09T06:39:10.828055Z","shell.execute_reply":"2021-08-09T06:39:10.835181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with strategy.scope():\n    model = make_model()","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:39:14.384634Z","iopub.execute_input":"2021-08-09T06:39:14.385191Z","iopub.status.idle":"2021-08-09T06:39:34.795706Z","shell.execute_reply.started":"2021-08-09T06:39:14.385139Z","shell.execute_reply":"2021-08-09T06:39:34.794707Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### **Training**","metadata":{}},{"cell_type":"code","source":"STEPS_PER_EPOCH = NUM_TRAIN_IMAGES // BATCH_SIZE","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:39:34.797107Z","iopub.execute_input":"2021-08-09T06:39:34.797397Z","iopub.status.idle":"2021-08-09T06:39:34.801682Z","shell.execute_reply.started":"2021-08-09T06:39:34.797369Z","shell.execute_reply":"2021-08-09T06:39:34.800708Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_dataset,\n                    epochs = EPOCHS,\n                    steps_per_epoch = STEPS_PER_EPOCH,\n                    validation_data = val_dataset,\n                    callbacks = my_callbacks)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:39:34.803182Z","iopub.execute_input":"2021-08-09T06:39:34.803500Z","iopub.status.idle":"2021-08-09T06:51:37.135696Z","shell.execute_reply.started":"2021-08-09T06:39:34.803470Z","shell.execute_reply":"2021-08-09T06:51:37.134684Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Accuracy / loss**","metadata":{}},{"cell_type":"code","source":"plt.figure(figsize=(15,6))\n\nplt.subplot(1,2,1)\nplt.plot(history.epoch,history.history['sparse_categorical_accuracy'],label = 'Training')\nplt.plot(history.epoch,history.history['val_sparse_categorical_accuracy'],label = 'validation')\n\nplt.title(\"Accuracy\")\nplt.legend()\n\nplt.subplot(1,2,2)\nplt.plot(history.epoch,history.history['loss'],label = 'Training')\nplt.plot(history.epoch,history.history['val_loss'],label = 'validation')\n\nplt.title(\"Loss\")\nplt.legend()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:52:04.818285Z","iopub.execute_input":"2021-08-09T06:52:04.818674Z","iopub.status.idle":"2021-08-09T06:52:05.262106Z","shell.execute_reply.started":"2021-08-09T06:52:04.818643Z","shell.execute_reply":"2021-08-09T06:52:05.260933Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## **Test and Predictions.**","metadata":{}},{"cell_type":"code","source":"model = tf.keras.models.load_model(\"./flowers&flowers.h5\")","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:52:09.296873Z","iopub.execute_input":"2021-08-09T06:52:09.297234Z","iopub.status.idle":"2021-08-09T06:52:16.530040Z","shell.execute_reply.started":"2021-08-09T06:52:09.297198Z","shell.execute_reply":"2021-08-09T06:52:16.528917Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.evaluate(val_dataset)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:52:20.293206Z","iopub.execute_input":"2021-08-09T06:52:20.293739Z","iopub.status.idle":"2021-08-09T06:54:57.788047Z","shell.execute_reply.started":"2021-08-09T06:52:20.293706Z","shell.execute_reply":"2021-08-09T06:54:57.786838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_dataset = get_test_dataset(test_files, ordered = True)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:55:12.014256Z","iopub.execute_input":"2021-08-09T06:55:12.014632Z","iopub.status.idle":"2021-08-09T06:55:12.043827Z","shell.execute_reply.started":"2021-08-09T06:55:12.014601Z","shell.execute_reply":"2021-08-09T06:55:12.042844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def show_batch_predictions(image_batch):\n    plt.figure(figsize=(20, 12))\n    for n in range(25):\n        ax = plt.subplot(5, 5, n + 1)\n        plt.imshow(image_batch[0][n])\n        img_array = tf.expand_dims(image_batch[0][n], axis=0)\n        plt.title(CLASSES[np.argmax(model.predict(img_array)[0])])\n        plt.axis(\"off\")\n\n\nimage_batch = next(iter(test_dataset))\n\nshow_batch_predictions(image_batch)","metadata":{"execution":{"iopub.status.busy":"2021-08-09T06:55:12.209576Z","iopub.execute_input":"2021-08-09T06:55:12.209969Z","iopub.status.idle":"2021-08-09T06:55:23.922772Z","shell.execute_reply.started":"2021-08-09T06:55:12.209934Z","shell.execute_reply":"2021-08-09T06:55:23.921781Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### **Submission.**","metadata":{}},{"cell_type":"code","source":"sample = pd.read_csv(\"../input/tpu-getting-started/sample_submission.csv\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Making Predictions....\")\n\ntest_images_ds = test_dataset.map(lambda image, idnum : image)\nprob = model.predict(test_images_ds)\npred = np.argmax(prob, axis = -1)\nprint(pred)\n\nprint(\"Generating CSV file....\")\n\ntest_ids_ds = test_dataset.map(lambda image, idnum : idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(7382))).numpy().astype(\"U\")\n\nprint(\"Saving CSV....\")\n\nnp.savetxt(\n    \"submission.csv\",\n    np.rec.fromarrays([test_ids, pred]),\n    fmt = ['%s', '%d'],\n    delimiter = \",\",\n    header = \"id,label\",\n    comments=\"\",\n)\nprint(\"Completed!\")","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}