{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"import math, re, os\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom kaggle_datasets import KaggleDatasets\nimport tensorflow as tf\nimport tensorflow.keras.layers as L\nfrom tensorflow.keras.applications import EfficientNetB7, EfficientNetB5\nfrom keras.applications.densenet import DenseNet201\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nfrom keras.callbacks import ModelCheckpoint\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"AUTO = tf.data.experimental.AUTOTUNE\n# 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)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# Data access\nGCS_DS_PATH = KaggleDatasets().get_gcs_path(\"plant-pathology-2021-fgvc8\")\n\n# Configuration\nEPOCHS = 20\nBATCH_SIZE = 8 * strategy.num_replicas_in_sync\nIM_Z = 768","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def format_train_path(fname):\n    return GCS_DS_PATH+'/train_images/'+fname\n\ndef format_test_path(fname):\n    return GCS_DS_PATH+'/test_images/'+fname","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dir=\"../input/plant-pathology-2021-fgvc8/train_images/\"\ntest_dir=\"../input/plant-pathology-2021-fgvc8/test_images/\"\ndf_train=pd.read_csv('../input/plant-pathology-2021-fgvc8/train.csv')\ndf_sub = pd.read_csv('../input/plant-pathology-2021-fgvc8/sample_submission.csv')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_paths = df_train.image.apply(format_train_path)\ntest_paths = df_sub.image.apply(format_test_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = df_train['labels'].str.split(\" \").apply(pd.Series, 1).stack()\nlabels.index = labels.index.droplevel(-1)\ntarget_labels = pd.get_dummies(labels).groupby(level=0).sum()\ntarget_labels.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_paths, valid_paths, train_labels, valid_labels = train_test_split(\n    train_paths, target_labels, test_size=0.2)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def decode_image(filename, label=None, image_size=(IM_Z, IM_Z)):\n    bits = tf.io.read_file(filename)\n    image = tf.image.decode_jpeg(bits, channels=3)\n    image = tf.cast(image, tf.float32) / 255.0\n    image = tf.image.resize(image, image_size)\n    \n    if label is None:\n        return image\n    else:\n        return image, label\n\ndef data_augment(image, label=None):\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n#     image = tf.image.adjust_brightness(image, delta=0.2)\n#     image = tf.image.adjust_contrast(image,2)\n    \n    if label is None:\n        return image\n    else:\n        return image, label","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((train_paths, train_labels))\n    .map(decode_image, num_parallel_calls=AUTO)\n    .cache()\n    .map(data_augment, num_parallel_calls=AUTO)\n    .repeat()\n    .shuffle(512)\n    .batch(BATCH_SIZE)\n    .prefetch(AUTO)\n)\n\nvalid_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices((valid_paths, valid_labels))\n    .map(decode_image, num_parallel_calls=AUTO)\n    .batch(BATCH_SIZE)\n    .cache()\n    .prefetch(AUTO)\n)\n\ntest_dataset = (\n    tf.data.Dataset\n    .from_tensor_slices(test_paths)\n    .map(decode_image, num_parallel_calls=AUTO)\n    .batch(BATCH_SIZE)\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_lrfn(lr_start=0.00001, lr_max=0.000075, \n               lr_min=0.000001, lr_rampup_epochs=20, \n               lr_sustain_epochs=0, lr_exp_decay=.8):\n    lr_max = lr_max * strategy.num_replicas_in_sync\n\n    def lrfn(epoch):\n        if epoch < lr_rampup_epochs:\n            lr = (lr_max - lr_start) / lr_rampup_epochs * epoch + 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    \n    return lrfn\n\nch_p = ModelCheckpoint(filepath=\"model_ef.h5\", monitor='val_loss', save_weights_only=True,\n                                                 verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model = tf.keras.Sequential([\n        EfficientNetB7(\n            input_shape=(IM_Z, IM_Z, 3),\n            weights=None,\n            include_top=False\n        ),\n        L.GlobalAveragePooling2D(),\n        L.Dense(train_labels.shape[1], activation='softmax')\n    ])\n        \n    model.compile(\n        optimizer='adam',\n        loss = 'categorical_crossentropy',\n        metrics=['categorical_accuracy']\n    )\n#     model.summary()\n\nmodel.load_weights('../input/plant-2021-densenet201-efficientnetb7-tpu/model_ef.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lrfn = build_lrfn()\nlr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)\nSTEPS_PER_EPOCH = train_labels.shape[0] // BATCH_SIZE ","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(\n    train_dataset, \n    epochs=EPOCHS, \n    callbacks=[lr_schedule, ch_p],\n    steps_per_epoch=STEPS_PER_EPOCH,\n    validation_data=valid_dataset\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model1 = tf.keras.Sequential([\n        tf.keras.applications.DenseNet201(\n            input_shape=(IM_Z, IM_Z, 3),\n            weights=None,\n            include_top=False\n        ),\n        L.GlobalAveragePooling2D(),\n        L.Dense(train_labels.shape[1], activation='softmax')\n    ])\n        \n             \n    model1.compile(\n        optimizer='adam',\n        loss = 'categorical_crossentropy',\n        metrics=['categorical_accuracy']\n    )\n#     model.summary()\n\nmodel1.load_weights('../input/plant-2021-densenet201-efficientnetb7-tpu/model_den.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"ch_p_den = ModelCheckpoint(filepath=\"model_den.h5\", monitor='val_loss', save_weights_only=True,\n                                                 verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history1 = model1.fit(\n    train_dataset, \n    epochs=EPOCHS, \n    callbacks=[lr_schedule, ch_p_den],\n    steps_per_epoch=STEPS_PER_EPOCH,\n    validation_data=valid_dataset\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"probs = (model1.predict(test_dataset)+model.predict(test_dataset))/2","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_names = target_labels.columns\ndef get_labels_from_pred(preds):\n    lab = []\n    for row in preds:\n        l = []\n        for i,v in enumerate(row):\n            if v >= 0.4:\n                l.append(i)\n        lab.append(\" \".join(label_names[l]))\n    return lab","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred_labels = get_labels_from_pred(probs)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_sub[\"labels\"] = pred_labels","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_sub.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"df_sub.to_csv(\"submission1.csv\", index=False)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]}],"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":4,"nbformat_minor":4}