{"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":"# Flower Classification on TPU\n## Table of Contents\n- [1. Import Packages](#1.)\n- [2. Distribution Strategy](#2.)\n- [3. Common Parameters](#3.)\n- [4. Common Functions](#4.)\n- [5. Import datasets](#5.)\n- [6. Understand the data](#6.)\n- [7. Model Development](#7.)\n- [8. Submission](#8.)","metadata":{}},{"cell_type":"markdown","source":"<a href=\"1.\"></a>\n## 1. Import Packages","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nimport pandas as pd\nfrom kaggle_datasets import KaggleDatasets\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras import applications","metadata":{"_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","execution":{"iopub.status.busy":"2021-09-01T15:20:55.787536Z","iopub.execute_input":"2021-09-01T15:20:55.788109Z","iopub.status.idle":"2021-09-01T15:21:02.132616Z","shell.execute_reply.started":"2021-09-01T15:20:55.788025Z","shell.execute_reply":"2021-09-01T15:21:02.131593Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a href=\"2.\"></a>\n## 2. Distribution Strategy","metadata":{}},{"cell_type":"code","source":"# Detect hardware, return appropriate distribution strategy\ntry:\n    tpu = tf.distribute.cluster_resolver.TPUClusterResolver()  # TPU detection. No parameters necessary if TPU_NAME environment variable is set. On Kaggle this is always the case.\n    print('Running on TPU ', tpu.master())\nexcept ValueError:\n    tpu = None\n\nif tpu:\n    tf.config.experimental_connect_to_cluster(tpu)\n    tf.tpu.experimental.initialize_tpu_system(tpu)\n    strategy = tf.distribute.experimental.TPUStrategy(tpu)\nelse:\n    strategy = tf.distribute.get_strategy() # default distribution strategy in Tensorflow. Works on CPU and single GPU.\n\nprint(\"REPLICAS: \", strategy.num_replicas_in_sync)","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:21:06.125261Z","iopub.execute_input":"2021-09-01T15:21:06.125652Z","iopub.status.idle":"2021-09-01T15:21:11.821767Z","shell.execute_reply.started":"2021-09-01T15:21:06.125608Z","shell.execute_reply":"2021-09-01T15:21:11.820836Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a href=\"3.\"></a>\n## 3. Common Parameters","metadata":{}},{"cell_type":"code","source":"IMAGE_SIZE = [192, 192] # with this size, a GPU will run out of memory. Use the TPU\nEPOCHS = 100\nBATCH_SIZE = 16 * strategy.num_replicas_in_sync\n\nNUM_TRAINING_IMAGES = 12753\nNUM_TEST_IMAGES = 7382\nSTEPS_PER_EPOCH = NUM_TRAINING_IMAGES // BATCH_SIZE\nGCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"\nprint(GCS_DS_PATH)","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:21:43.075942Z","iopub.execute_input":"2021-09-01T15:21:43.076583Z","iopub.status.idle":"2021-09-01T15:21:43.489052Z","shell.execute_reply.started":"2021-09-01T15:21:43.076529Z","shell.execute_reply":"2021-09-01T15:21:43.488063Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a href=\"4.\"></a>\n## 4. Common Functions","metadata":{}},{"cell_type":"markdown","source":" **Load datasets**","metadata":{}},{"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, [*IMAGE_SIZE, 3]) # explicit size needed for TPU\n    return image\n\ndef read_labeled_tfrecord(example):\n    LABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"class\": tf.io.FixedLenFeature([], tf.int64),  # shape [] means single element\n    }\n    example = tf.io.parse_single_example(example, LABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    label = tf.cast(example['class'], tf.int32)\n    return image, label # returns a dataset of (image, label) pairs\n\ndef read_unlabeled_tfrecord(example):\n    UNLABELED_TFREC_FORMAT = {\n        \"image\": tf.io.FixedLenFeature([], tf.string), # tf.string means bytestring\n        \"id\": tf.io.FixedLenFeature([], tf.string),  # shape [] means single element\n        # class is missing, this competitions's challenge is to predict flower classes for the test dataset\n    }\n    example = tf.io.parse_single_example(example, UNLABELED_TFREC_FORMAT)\n    image = decode_image(example['image'])\n    idnum = example['id']\n    return image, idnum # returns a dataset of image(s)\n\ndef load_dataset(filenames, labeled=True, ordered=False):\n    # Read from TFRecords. For optimal performance, reading from multiple files at once and\n    # disregarding data order. Order does not matter since we will be shuffling the data anyway.\n\n    ignore_order = tf.data.Options()\n    if not ordered:\n        ignore_order.experimental_deterministic = False # disable order, increase speed\n\n    dataset = tf.data.TFRecordDataset(filenames) # automatically interleaves reads from multiple files\n    dataset = dataset.with_options(ignore_order) # uses data as soon as it streams in, rather than in its original order\n    dataset = dataset.map(read_labeled_tfrecord if labeled else read_unlabeled_tfrecord)\n    # returns a dataset of (image, label) pairs if labeled=True or (image, id) pairs if labeled=False\n    return dataset\n\ndef get_training_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/train/*.tfrec'), labeled=True)\n    dataset = dataset.repeat() # the training dataset must repeat for several epochs\n    dataset = dataset.shuffle(2048)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset\n\ndef get_validation_dataset():\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/val/*.tfrec'), labeled=True, ordered=False)\n    dataset = dataset.batch(BATCH_SIZE)\n    dataset = dataset.cache()\n    return dataset\n\ndef get_test_dataset(ordered=False):\n    dataset = load_dataset(tf.io.gfile.glob(GCS_DS_PATH + '/tfrecords-jpeg-192x192/test/*.tfrec'), labeled=False, ordered=ordered)\n    dataset = dataset.batch(BATCH_SIZE)\n    return dataset","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:21:47.879896Z","iopub.execute_input":"2021-09-01T15:21:47.880292Z","iopub.status.idle":"2021-09-01T15:21:47.895204Z","shell.execute_reply.started":"2021-09-01T15:21:47.88026Z","shell.execute_reply":"2021-09-01T15:21:47.894155Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"**Sample Images**","metadata":{}},{"cell_type":"code","source":"def sample_images(images, row_count, column_count):\n    fig, axs = plt.subplots(row_count, column_count, figsize=(10,10))\n    for i in range(row_count):\n        for j in range(column_count):\n            axs[i,j].imshow(images[i * column_count + j])\n            axs[i,j].axis('off')\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:21:51.721585Z","iopub.execute_input":"2021-09-01T15:21:51.721963Z","iopub.status.idle":"2021-09-01T15:21:51.729442Z","shell.execute_reply.started":"2021-09-01T15:21:51.721921Z","shell.execute_reply":"2021-09-01T15:21:51.728009Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a href=\"5.\"></a>\n## 5. Import datasets\n\nThis data is loaded from Kaggle and automatically sharded to maximize parallelization.","metadata":{}},{"cell_type":"code","source":"training_dataset = get_training_dataset()\nvalidation_dataset = get_validation_dataset()","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:21:54.823382Z","iopub.execute_input":"2021-09-01T15:21:54.823862Z","iopub.status.idle":"2021-09-01T15:21:55.209798Z","shell.execute_reply.started":"2021-09-01T15:21:54.82383Z","shell.execute_reply":"2021-09-01T15:21:55.208954Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a href=\"6.\"></a>\n## 6. Understand the data","metadata":{}},{"cell_type":"markdown","source":"Let's see what the dataset looks like.","metadata":{}},{"cell_type":"code","source":"for item in training_dataset:\n    images = item[0].numpy()\n    labels = item[1].numpy()\n    break\nimages.shape, labels.shape","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:22:17.892772Z","iopub.execute_input":"2021-09-01T15:22:17.893133Z","iopub.status.idle":"2021-09-01T15:22:19.903201Z","shell.execute_reply.started":"2021-09-01T15:22:17.893105Z","shell.execute_reply":"2021-09-01T15:22:19.902181Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample_images(images, 4, 4)","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:22:22.087768Z","iopub.execute_input":"2021-09-01T15:22:22.088152Z","iopub.status.idle":"2021-09-01T15:22:23.18694Z","shell.execute_reply.started":"2021-09-01T15:22:22.088121Z","shell.execute_reply":"2021-09-01T15:22:23.186193Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a href=\"7.\"></a>\n## 7. Model Development","metadata":{}},{"cell_type":"markdown","source":"### Model Checkpoint","metadata":{}},{"cell_type":"code","source":"checkpoint_path = \"model.h5\"\ncheckpoint = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, save_best_only=True)","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:22:37.346554Z","iopub.execute_input":"2021-09-01T15:22:37.347249Z","iopub.status.idle":"2021-09-01T15:22:37.351494Z","shell.execute_reply.started":"2021-09-01T15:22:37.34721Z","shell.execute_reply":"2021-09-01T15:22:37.350431Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Learning Rate Scheduler","metadata":{"execution":{"iopub.status.busy":"2021-09-01T14:26:34.527526Z","iopub.execute_input":"2021-09-01T14:26:34.527875Z","iopub.status.idle":"2021-09-01T14:26:34.530985Z","shell.execute_reply.started":"2021-09-01T14:26:34.527846Z","shell.execute_reply":"2021-09-01T14:26:34.530219Z"}}},{"cell_type":"code","source":"LR_START = 0.00005\nLR_MAX =   0.00005 * strategy.num_replicas_in_sync\nLR_MIN =   0.0000025\nLR_RAMPUP_EPOCHS = 3\nLR_SUSTAIN_EPOCHS = 6\nLR_EXP_DECAY = .8\ndef scheduler_callback(epoch):\n    if epoch < LR_RAMPUP_EPOCHS:\n        lr =  np.random.random_sample() * 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\nscheduler = tf.keras.callbacks.LearningRateScheduler(scheduler_callback, verbose=True)","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:22:45.457201Z","iopub.execute_input":"2021-09-01T15:22:45.45756Z","iopub.status.idle":"2021-09-01T15:22:45.464497Z","shell.execute_reply.started":"2021-09-01T15:22:45.457528Z","shell.execute_reply":"2021-09-01T15:22:45.463466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Early Stopping","metadata":{}},{"cell_type":"code","source":"early_stop = tf.keras.callbacks.EarlyStopping(patience=10)","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:22:49.138729Z","iopub.execute_input":"2021-09-01T15:22:49.139091Z","iopub.status.idle":"2021-09-01T15:22:49.14377Z","shell.execute_reply.started":"2021-09-01T15:22:49.139059Z","shell.execute_reply":"2021-09-01T15:22:49.14259Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"callbacks = [early_stop, checkpoint, scheduler]","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:22:50.945648Z","iopub.execute_input":"2021-09-01T15:22:50.946022Z","iopub.status.idle":"2021-09-01T15:22:50.951261Z","shell.execute_reply.started":"2021-09-01T15:22:50.945992Z","shell.execute_reply":"2021-09-01T15:22:50.950389Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Optimizer","metadata":{}},{"cell_type":"code","source":"optimizer = tf.keras.optimizers.Adam(learning_rate=0.001, \n                                                 beta_1=0.9, \n                                                 beta_2=0.999, \n                                                 epsilon=1e-07, \n                                                 amsgrad=False)","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:22:53.397848Z","iopub.execute_input":"2021-09-01T15:22:53.398334Z","iopub.status.idle":"2021-09-01T15:22:53.402697Z","shell.execute_reply.started":"2021-09-01T15:22:53.398305Z","shell.execute_reply":"2021-09-01T15:22:53.401928Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Get Pretrain Model\nI will build the Model based on kears pretrained Models. There are many pretrained Models such as InceptionV3, EfficientNet 0 - 7 and so on. You can choose the pretrained Model you like to train the Model.","metadata":{}},{"cell_type":"code","source":"model_types = [\n    \"dense_net\", \n    \"xception\", \n    \"inception\", \n    \"efficient_0\", \n    \"efficient_1\", \n    \"efficient_2\", \n    \"efficient_3\",\n    \"efficient_4\",\n    \"efficient_5\",\n    \"efficient_6\",\n    \"efficient_7\"\n]\nmodel_type = model_types[0]\ndef get_pretraind_model(model_type, input_shape):\n    if model_type == \"dense_net\":\n        return applications.densenet.DenseNet121(\n                include_top=False,\n                input_shape=input_shape               \n            )\n    if model_type == \"xception\":\n        return applications.Xception(\n            include_top=False,\n            input_shape=input_shape                        \n        )\n    if model_type == \"inception\":\n        return applications.InceptionV3(\n            include_top=False,\n            input_shape=input_shape                          \n        )\n    if model_type == \"efficient_0\":\n        return applications.EfficientNetB0(\n            include_top=False,\n                input_shape=input_shape                         \n        )\n    if model_type == \"efficient_1\":\n        return applications.EfficientNetB1(\n            include_top=False,\n            input_shape=input_shape                         \n        )\n    if model_type == \"efficient_2\":\n        return applications.EfficientNetB2(\n            include_top=False,\n            input_shape=input_shape                        \n        )\n    if model_type == \"efficient_3\":\n        return applications.EfficientNetB3(\n            include_top=False,\n            input_shape=input_shape                       \n        )\n    if model_type == \"efficient_4\":\n        return applications.EfficientNetB4(\n            include_top=False,\n            input_shape=input_shape                       \n        )\n    if model_type == \"efficient_5\":\n        return applications.EfficientNetB5(\n            include_top=False,\n            input_shape=input_shape                       \n        )\n    if model_type == \"efficient_6\":\n        return applications.EfficientNetB6(\n            include_top=False,\n            input_shape=input_shape                       \n        )\n    if model_type == \"efficient_7\":\n        return applications.EfficientNetB7(\n            include_top=False,\n            input_shape=input_shape                       \n        )","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:23:31.889234Z","iopub.execute_input":"2021-09-01T15:23:31.889616Z","iopub.status.idle":"2021-09-01T15:23:31.900159Z","shell.execute_reply.started":"2021-09-01T15:23:31.889585Z","shell.execute_reply":"2021-09-01T15:23:31.899436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Train the Model","metadata":{}},{"cell_type":"code","source":"def train(\n    model_type, epochs, optimizer, callbacks, \n    strategy, layers):\n    tf.keras.backend.clear_session()\n    with strategy.scope():  \n        input_shape = [*IMAGE_SIZE, 3]   \n        pretrained_model = get_pretraind_model(model_type, input_shape)\n        print(pretrained_model.summary())\n        pretrained_model.trainable = True \n        all_layers = [pretrained_model] + layers + [tf.keras.layers.Dense(104, activation='softmax')]\n        model = tf.keras.Sequential(all_layers)\n        model.compile(\n            optimizer=optimizer,\n            loss = 'sparse_categorical_crossentropy',\n            metrics=['sparse_categorical_accuracy']\n        )\n        history = model.fit(training_dataset, \n                            steps_per_epoch=STEPS_PER_EPOCH, \n                            epochs=epochs, \n                            validation_data=validation_dataset, \n                            callbacks=callbacks\n                           )\n        pd.DataFrame(history.history).plot()\n        plt.show()\n        return model","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:23:35.864399Z","iopub.execute_input":"2021-09-01T15:23:35.864938Z","iopub.status.idle":"2021-09-01T15:23:35.873018Z","shell.execute_reply.started":"2021-09-01T15:23:35.864891Z","shell.execute_reply":"2021-09-01T15:23:35.872011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = train(\n    model_type, EPOCHS, optimizer, callbacks, strategy, \n    layers=[\n        tf.keras.layers.GlobalAveragePooling2D(), \n        tf.keras.layers.Dropout(0.5)\n    ]\n)","metadata":{"execution":{"iopub.status.busy":"2021-09-01T15:23:38.490732Z","iopub.execute_input":"2021-09-01T15:23:38.491235Z","iopub.status.idle":"2021-09-01T15:26:05.824699Z","shell.execute_reply.started":"2021-09-01T15:23:38.491195Z","shell.execute_reply":"2021-09-01T15:26:05.823644Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a href=\"8.\"></a>\n## 8. Submission","metadata":{}},{"cell_type":"code","source":"test_ds = get_test_dataset(ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\nmodel.load_weights(checkpoint_path)\nprint('Computing predictions...')\ntest_images_ds = test_ds.map(lambda image, idnum: image)\nprobabilities = model.predict(test_images_ds)\npredictions = np.argmax(probabilities, axis=-1)\nprint(predictions[:10])\n\nprint('Generating submission.csv file...')\ntest_ids_ds = test_ds.map(lambda image, idnum: idnum).unbatch()\ntest_ids = next(iter(test_ids_ds.batch(NUM_TEST_IMAGES))).numpy().astype('U') # all in one batch\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, predictions]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')","metadata":{"execution":{"iopub.status.busy":"2021-09-01T14:56:23.848104Z","iopub.execute_input":"2021-09-01T14:56:23.848602Z","iopub.status.idle":"2021-09-01T14:56:54.765046Z","shell.execute_reply.started":"2021-09-01T14:56:23.848557Z","shell.execute_reply":"2021-09-01T14:56:54.763947Z"},"trusted":true},"execution_count":null,"outputs":[]}]}