{"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":"### Turn on TPU on top right before running this notebook","metadata":{"execution":{"iopub.status.busy":"2022-04-10T10:29:55.453708Z","iopub.execute_input":"2022-04-10T10:29:55.454386Z","iopub.status.idle":"2022-04-10T10:29:55.474002Z","shell.execute_reply.started":"2022-04-10T10:29:55.454258Z","shell.execute_reply":"2022-04-10T10:29:55.472582Z"}}},{"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\nimport time\nfrom tqdm import tqdm, trange\nfrom scipy import stats","metadata":{"execution":{"iopub.status.busy":"2022-04-10T17:06:18.112542Z","iopub.execute_input":"2022-04-10T17:06:18.114253Z","iopub.status.idle":"2022-04-10T17:06:18.127078Z","shell.execute_reply.started":"2022-04-10T17:06:18.114077Z","shell.execute_reply":"2022-04-10T17:06:18.124287Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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":"2022-04-10T17:04:23.330198Z","iopub.execute_input":"2022-04-10T17:04:23.331070Z","iopub.status.idle":"2022-04-10T17:04:28.873944Z","shell.execute_reply.started":"2022-04-10T17:04:23.331031Z","shell.execute_reply":"2022-04-10T17:04:28.873242Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## load data","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(GCS_DS_PATH):\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(GCS_DS_PATH):\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(GCS_DS_PATH, 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\n\ndef sample_images(images, row_count, column_count):\n    fig, axs = plt.subplots(row_count, column_count, figsize=(10,10))\n    for i in range(0, row_count):\n        for j in range(0, 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":"2022-04-10T17:04:28.875722Z","iopub.execute_input":"2022-04-10T17:04:28.876309Z","iopub.status.idle":"2022-04-10T17:04:28.897013Z","shell.execute_reply.started":"2022-04-10T17:04:28.876262Z","shell.execute_reply":"2022-04-10T17:04:28.895873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Import data","metadata":{}},{"cell_type":"code","source":"### Parameters\nIMAGE_SIZE = [192, 192] # at this size, a GPU will run out of memory. Use the TPU\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\n\n\nGCS_DS_PATH = KaggleDatasets().get_gcs_path() # you can list the bucket with \"!gsutil ls $GCS_DS_PATH\"\nprint(GCS_DS_PATH)\n\ntraining_dataset = get_training_dataset(GCS_DS_PATH)\nvalidation_dataset = get_validation_dataset(GCS_DS_PATH)\n\nprint(training_dataset, '\\n', validation_dataset)","metadata":{"execution":{"iopub.status.busy":"2022-04-10T17:04:28.899937Z","iopub.execute_input":"2022-04-10T17:04:28.900379Z","iopub.status.idle":"2022-04-10T17:04:29.681572Z","shell.execute_reply.started":"2022-04-10T17:04:28.900333Z","shell.execute_reply":"2022-04-10T17:04:29.680650Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"for item in training_dataset:\n    images = item[0].numpy()\n    labels = item[1].numpy()\n    break\n\nprint(images.shape, labels.shape, sample_images(images, 5, 5))","metadata":{"execution":{"iopub.status.busy":"2022-04-10T17:04:29.683144Z","iopub.execute_input":"2022-04-10T17:04:29.684008Z","iopub.status.idle":"2022-04-10T17:04:32.953819Z","shell.execute_reply.started":"2022-04-10T17:04:29.683956Z","shell.execute_reply":"2022-04-10T17:04:32.952692Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model","metadata":{}},{"cell_type":"code","source":"def ModelCheckPoint(i):\n    checkpoint_path = \"model{:d}.h5\".format(i)\n    checkpoint = tf.keras.callbacks.ModelCheckpoint(checkpoint_path, save_best_only=True)\n\n\n    LR_START = 0.00005\n    LR_MAX =   0.00005 * strategy.num_replicas_in_sync\n    LR_MIN =   0.0000025\n    LR_RAMPUP_EPOCHS = 3\n    LR_SUSTAIN_EPOCHS = 6\n    LR_EXP_DECAY = .8\n    def 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\n    scheduler = tf.keras.callbacks.LearningRateScheduler(scheduler_callback, verbose=True)\n\n\n\n    early_stop = tf.keras.callbacks.EarlyStopping(patience=10)\n    callbacks = [early_stop, checkpoint, scheduler]\n\n    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)\n    \n    return checkpoint_path, checkpoint, scheduler, early_stop, callbacks, optimizer","metadata":{"execution":{"iopub.status.busy":"2022-04-10T17:04:32.955014Z","iopub.execute_input":"2022-04-10T17:04:32.955295Z","iopub.status.idle":"2022-04-10T17:04:32.969312Z","shell.execute_reply.started":"2022-04-10T17:04:32.955260Z","shell.execute_reply":"2022-04-10T17:04:32.968366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"checkpoint_path, checkpoint, scheduler, early_stop, callbacks, optimizer = ModelCheckPoint(0)\n\nprint(checkpoint_path, '\\n', checkpoint, scheduler, '\\n', early_stop, '\\n', callbacks, '\\n', optimizer)","metadata":{"execution":{"iopub.status.busy":"2022-04-10T17:04:32.971020Z","iopub.execute_input":"2022-04-10T17:04:32.971299Z","iopub.status.idle":"2022-04-10T17:04:32.985628Z","shell.execute_reply.started":"2022-04-10T17:04:32.971265Z","shell.execute_reply":"2022-04-10T17:04:32.984580Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Pre-trained models","metadata":{"execution":{"iopub.status.busy":"2022-04-10T10:45:41.79714Z","iopub.execute_input":"2022-04-10T10:45:41.797785Z","iopub.status.idle":"2022-04-10T10:45:41.802275Z","shell.execute_reply.started":"2022-04-10T10:45:41.797731Z","shell.execute_reply":"2022-04-10T10:45:41.801405Z"}}},{"cell_type":"code","source":"def 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":"2022-04-10T17:04:32.987654Z","iopub.execute_input":"2022-04-10T17:04:32.988448Z","iopub.status.idle":"2022-04-10T17:04:32.998951Z","shell.execute_reply.started":"2022-04-10T17:04:32.988404Z","shell.execute_reply":"2022-04-10T17:04:32.998292Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# train model","metadata":{}},{"cell_type":"code","source":"def train(model_type, epochs, optimizer, callbacks, 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        \n        return model, history\n    \ndef predict_fun(checkpoint_path, model_i):\n    test_ds = get_test_dataset(GCS_DS_PATH, ordered=True) # since we are splitting the dataset and iterating separately on images and ids, order matters.\n        \n    model_i.load_weights(checkpoint_path)\n\n    test_images_ds = test_ds.map(lambda image, idnum: image)\n    probabilities = model_i.predict(test_images_ds)\n\n    predictions = np.argmax(probabilities, axis=-1)\n        \n    return predictions\n    ","metadata":{"execution":{"iopub.status.busy":"2022-04-10T17:04:33.000610Z","iopub.execute_input":"2022-04-10T17:04:33.001212Z","iopub.status.idle":"2022-04-10T17:04:33.014295Z","shell.execute_reply.started":"2022-04-10T17:04:33.001168Z","shell.execute_reply":"2022-04-10T17:04:33.013405Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_types = [\"dense_net\", \"xception\", \"inception\", \"efficient_0\", \"efficient_1\", \"efficient_2\", \"efficient_3\",\\\n    \"efficient_4\", \"efficient_5\", \"efficient_6\", \"efficient_7\"]\n# model_type = model_types[1]\n\n\nEPOCHS = 15\n\nAll_models=[]; All_history=[]; All_predictions=[]\n\nfor i in trange(5):#len(model_types)):\n    checkpoint_path, checkpoint, scheduler, early_stop, callbacks, optimizer = ModelCheckPoint(i)\n    %time model, history = train( model_types[i], EPOCHS, optimizer, callbacks, strategy,\\\n            layers=[tf.keras.layers.Dropout(0.5),\\\n                    tf.keras.layers.GlobalAveragePooling2D(),\\\n                    tf.keras.layers.Dropout(0.5)])\n\n    All_models.append(model)\n    All_history.append(history)\n    \n    predicts = predict_fun(checkpoint_path, model)\n    All_predictions.append(predicts)","metadata":{"scrolled":true,"execution":{"iopub.status.busy":"2022-04-10T17:06:25.499116Z","iopub.execute_input":"2022-04-10T17:06:25.500438Z","iopub.status.idle":"2022-04-10T17:33:55.484778Z","shell.execute_reply.started":"2022-04-10T17:06:25.500391Z","shell.execute_reply":"2022-04-10T17:33:55.483892Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.rcParams[\"figure.figsize\"] = (10,6)\n\nfor i in range(5):\n    plt.plot(pd.DataFrame(All_history[i].history['val_sparse_categorical_accuracy']), lw=2, label=model_types[i])\n\nplt.legend(fontsize=15, loc='lower right')\nplt.ylabel('Accuracy', fontsize=30)\nplt.xlabel('Epochs', fontsize=30)\nplt.xticks(fontsize=20, rotation=0)\nplt.yticks(fontsize=20, rotation=0)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-10T17:35:12.275488Z","iopub.execute_input":"2022-04-10T17:35:12.275796Z","iopub.status.idle":"2022-04-10T17:35:12.553396Z","shell.execute_reply.started":"2022-04-10T17:35:12.275767Z","shell.execute_reply":"2022-04-10T17:35:12.552304Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"plt.rcParams[\"figure.figsize\"] = (15,6)\n\nfor i in range(5):\n    plt.plot(All_predictions[i], lw=2, ls='--', label=model_types[i])\n\nplt.legend(fontsize=15, loc='lower right')\nplt.ylabel('Predicted Categories', fontsize=30)\nplt.xlabel('flowers', fontsize=30)\nplt.xticks(fontsize=20, rotation=0)\nplt.yticks(fontsize=20, rotation=0)\n\nplt.xlim(0, 50)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-04-10T17:35:22.041623Z","iopub.execute_input":"2022-04-10T17:35:22.042512Z","iopub.status.idle":"2022-04-10T17:35:22.336759Z","shell.execute_reply.started":"2022-04-10T17:35:22.042464Z","shell.execute_reply":"2022-04-10T17:35:22.336089Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Taking mode of Predictions from different models","metadata":{}},{"cell_type":"code","source":"All_predictions = np.asarray(All_predictions)\nAll_predictions_mode = stats.mode(All_predictions, axis=0)[0][0]\n\nAll_predictions_mode[:15]","metadata":{"execution":{"iopub.status.busy":"2022-04-10T17:33:56.116993Z","iopub.execute_input":"2022-04-10T17:33:56.117237Z","iopub.status.idle":"2022-04-10T17:33:56.374884Z","shell.execute_reply.started":"2022-04-10T17:33:56.117210Z","shell.execute_reply":"2022-04-10T17:33:56.373930Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"test_ds = get_test_dataset(GCS_DS_PATH, ordered=True)\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\n\n\nprint(test_ids, All_predictions_mode)","metadata":{"execution":{"iopub.status.busy":"2022-04-10T17:33:56.376284Z","iopub.execute_input":"2022-04-10T17:33:56.376521Z","iopub.status.idle":"2022-04-10T17:34:04.686399Z","shell.execute_reply.started":"2022-04-10T17:33:56.376495Z","shell.execute_reply":"2022-04-10T17:34:04.685436Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Submission file","metadata":{}},{"cell_type":"code","source":"\nprint('Generating submission.csv file...')\n\nnp.savetxt('submission.csv', np.rec.fromarrays([test_ids, All_predictions_mode]), fmt=['%s', '%d'], delimiter=',', header='id,label', comments='')\n\nprint('Done')","metadata":{"execution":{"iopub.status.busy":"2022-04-10T17:34:04.688087Z","iopub.execute_input":"2022-04-10T17:34:04.688353Z","iopub.status.idle":"2022-04-10T17:34:04.753079Z","shell.execute_reply.started":"2022-04-10T17:34:04.688320Z","shell.execute_reply":"2022-04-10T17:34:04.752097Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}