{"cells":[{"metadata":{},"cell_type":"markdown","source":"# Load the libraries"},{"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\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.optimizers import Adam\nfrom sklearn import metrics\nfrom sklearn.model_selection import train_test_split\nfrom keras.callbacks import ModelCheckpoint","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Enable the TPU"},{"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":{},"cell_type":"markdown","source":"# Load data"},{"metadata":{"trusted":true},"cell_type":"code","source":"# Data access\nGCS_DS_PATH = KaggleDatasets().get_gcs_path()\n# Configuration\nNUM_CLASSES=7\nEPOCHS = 10\nBATCH_SIZE = 8 * strategy.num_replicas_in_sync\nIMG_SIZE = 600","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"GCS_DS_PATH","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"!gsutil ls $GCS_DS_PATH","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')\n","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_train.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"def format_train_path(fname):\n    return GCS_DS_PATH+'/train_images/'+fname","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_paths = df_train.image.apply(format_train_path)\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Make the label encodig"},{"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.1, random_state=42)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"'''\ndef decode_image(filename, label=None, image_size=(IMG_SIZE, IMG_SIZE)):\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    print(image)\n    image = tf.keras.preprocessing.image.array_to_img(image)\n    image = tf.keras.preprocessing.image.random_shift(image, 0.3, 0.3),\n    image = tf.keras.preprocessing.image.random_rotation(image, rg=180)\n    image = tf.keras.preprocessing.image.random_brightness(image, [0.5,0.1,0.15,0.2,0.25])\n    image = tf.keras.preprocessing.image.random_zoom(image,[0.5,0.1,0.15,0.2,0.25])\n    image = tf.keras.preprocessing.image.random_shear(image, intensity=10)\n    \n    if label is None:\n        return image\n    else:\n        return image, label\n'''","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"STEPS_PER_EPOCH = train_paths.shape[0] // BATCH_SIZE","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Image Pre-processing"},{"metadata":{"trusted":true},"cell_type":"code","source":"data_augmentation = tf.keras.Sequential([\n  layers.experimental.preprocessing.RandomFlip(\"horizontal\"),\n  layers.experimental.preprocessing.RandomRotation(0.2),\n])\ndef decode_image(filename, label=None, image_size=(IMG_SIZE, IMG_SIZE)):\n    bits = tf.io.read_file(filename)\n    image = tf.image.decode_jpeg(bits, channels=3)\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, seed=42):\n    image = tf.expand_dims(image, 0)\n    image = data_augmentation(image)[0]\n    seed = tf.random.experimental.stateless_split([seed,IMG_SIZE], num=1)[0, :]\n    image = tf.image.stateless_random_brightness(image, max_delta=0.2, seed=seed)\n    #image = tf.image.stateless_random_contrast(image,0.01,0.1, seed=seed)\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","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Create function for varying learning rate"},{"metadata":{"trusted":true},"cell_type":"code","source":"def build_lrfn(lr_start=0.00001, lr_max=0.00005,lr_min=0.0000105, lr_rampup_epochs=5,lr_sustain_epochs=0, lr_exp_decay=.5):    \n    lr_max = lr_max * strategy.num_replicas_in_sync\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) *\\\n                 lr_exp_decay**(epoch - lr_rampup_epochs- lr_sustain_epochs) + lr_min\n        return lr\n    return lrfn","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"Metrics"},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import backend as K\n\ndef f1(y_true, y_pred):\n    def recall(y_true, y_pred):\n        \"\"\"Recall metric.\n\n        Only computes a batch-wise average of recall.\n\n        Computes the recall, a metric for multi-label classification of\n        how many relevant items are selected.\n        \"\"\"\n        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n        possible_positives = K.sum(K.round(K.clip(y_true, 0, 1)))\n        recall = true_positives / (possible_positives + K.epsilon())\n        return recall\n\n    def precision(y_true, y_pred):\n        \"\"\"Precision metric.\n\n        Only computes a batch-wise average of precision.\n\n        Computes the precision, a metric for multi-label classification of\n        how many selected items are relevant.\n        \"\"\"\n        true_positives = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n        predicted_positives = K.sum(K.round(K.clip(y_pred, 0, 1)))\n        precision = true_positives / (predicted_positives + K.epsilon())\n        return precision\n    precision = precision(y_true, y_pred)\n    recall = recall(y_true, y_pred)\n    return 2*((precision*recall)/(precision+recall+K.epsilon()))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lrfn = build_lrfn()\nlr_schedule = tf.keras.callbacks.LearningRateScheduler(lrfn, verbose=1)\nEarlyStopping=tf.keras.callbacks.EarlyStopping(monitor=\"val_loss\",patience=10,verbose=True, mode=\"min\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Build the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.applications import EfficientNetB7","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.applications import EfficientNetB7\ninput_shape = [IMG_SIZE, IMG_SIZE, 3]\n# instantiating the model in the strategy scope creates the model on the TPU\ndef build_model():\n    base_model = EfficientNetB7(include_top=False, input_shape=input_shape ,weights=\"imagenet\", drop_connect_rate=0.4)\n    # Freeze the pretrained weights\n    for layer in base_model.layers:\n            if not isinstance(layer, layers.BatchNormalization):\n                layer.trainable = True\n    model = Sequential()\n    model.add(layers.BatchNormalization(input_shape=input_shape))\n    model.add(base_model)\n    # Rebuild top\n    model.add(layers.GlobalAveragePooling2D(name=\"avg_pool\"))\n    model.add(layers.BatchNormalization())\n    model.add(layers.Dropout(0.2, name=\"top_dropout1\"))\n    model.add(layers.Dense(512,activation='relu'))\n    model.add(layers.Dense(128,activation='relu'))\n    model.add(layers.Dense(32,activation='relu'))\n    model.add(layers.Dense(NUM_CLASSES, activation=\"sigmoid\", name=\"pred\"))\n    opt = Adam(lr=0.001)\n    metrics=[f1]\n    model.compile(optimizer='Adam', loss='binary_crossentropy', metrics=metrics )\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"with strategy.scope():\n    model = build_model()\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Train the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"history=model.fit(train_dataset,steps_per_epoch=STEPS_PER_EPOCH,epochs=30,validation_data=valid_dataset,callbacks=[lr_schedule,EarlyStopping],verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save(\"v4.h5\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Make predictions"},{"metadata":{"trusted":true},"cell_type":"code","source":"test_dataset = (\n    tf.data.Dataset\n    .list_files(GCS_DS_PATH+'/test_images/'+\"*\")\n    .map(decode_image, num_parallel_calls=AUTO)\n    .batch(BATCH_SIZE)\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred = model.predict(test_dataset)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"pred.round()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"process the predictions"},{"metadata":{"trusted":true},"cell_type":"code","source":"label_names = target_labels.columns\ndef get_labels_from_pred(preds):\n    preds = preds.round()\n    lab = []\n    for row in preds:\n        l = []\n        for i,v in enumerate(row):\n            if v == 1:\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(pred)","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(\"submission.csv\", index=False, encoding='utf-8')","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}