{"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":"%matplotlib inline\nimport math, re, os\n\nimport numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\n\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\n#GCS_DS_PATH = KaggleDatasets().get_gcs_path()\n# Configuration\nNUM_CLASSES=10\nEPOCHS = 10\nBATCH_SIZE = 8 #* strategy.num_replicas_in_sync\nIMG_SIZE = 600","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_dir=\"../input/c/plant-pathology-2021-fgvc8/train_images/\"\ntest_dir=\"../input/c/plant-pathology-2021-fgvc8/test_images/\"\ndf_train=pd.read_csv('../input/c/plant-pathology-2021-fgvc8/train.csv')\ndf_sub = pd.read_csv('../input/c/plant-pathology-2021-fgvc8/sample_submission.csv')\n","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 train_dir+fname","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_paths = df_train.image.apply(format_train_path)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels = df_train['labels'].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":"# labels_dict = dict(zip(list(labels.value_counts().index), np.arange(labels.value_counts().shape[0])))\n# target_labels = labels.map(labels_dict)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"# labels = df_train['labels'].apply(pd.Series, 1).stack()\n# labels.index = labels.index.droplevel(-1)\n# target_labels = pd.get_dummies(labels).groupby(level=0).sum()\n# target_labels.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"labels.value_counts().plot.bar(figsize=(15,5))\nplt.show()","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":"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.5),\n  layers.experimental.preprocessing.RandomFlip(\"vertical\"),\n  layers.experimental.preprocessing.RandomZoom(.2, .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":{"trusted":true},"cell_type":"code","source":"def scheduler(epoch, lr):\n    if epoch < 10:\n        return lr\n    else:\n        return lr * tf.math.exp(-0.1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from keras import backend as K\n\ndef recall(y_true, y_pred):\n    num = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n    den = K.sum(K.round(K.clip(y_true, 0, 1))) + K.epsilon()\n    recall = num / den\n    return recall\n\ndef precision(y_true, y_pred):\n    num = K.sum(K.round(K.clip(y_true * y_pred, 0, 1)))\n    den = K.sum(K.round(K.clip(y_pred, 0, 1))) + K.epsilon()\n    precision = num / den\n    return precision\n\ndef f1(y_true, y_pred):\n    p = precision(y_true, y_pred)\n    r = recall(y_true, y_pred)\n    return 2*((p*r)/(p+r+K.epsilon()))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"lr_schedule = tf.keras.callbacks.LearningRateScheduler(scheduler, 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":"catcross_loss = tf.keras.losses.CategoricalCrossentropy(from_logits=True, \n                                               label_smoothing=0.1, \n                                               name='categorical_crossentropy' )\nNUM_CLASSES = len(labels_dict)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow.keras.models import Sequential\nfrom tensorflow.keras.applications import EfficientNetB7\nfrom tensorflow.keras.applications import ResNet50\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 = ResNet50(include_top=False, input_shape=input_shape ,weights=\"imagenet\", pooling='max')\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(base_model)\n    # Rebuild top\n#     model.add(layers.GlobalAveragePooling2D(name=\"avg_pool\"))\n#     model.add(layers.BatchNormalization())\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 = \"softmax\"))\n    opt = Adam(lr=0.001)\n    model.compile(optimizer='Adam', loss=catcross_loss, metrics=['acc'])\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=6,validation_data=valid_dataset,callbacks=[lr_schedule,EarlyStopping],verbose=1)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"import matplotlib\n\nplt.figure(figsize=(10,8))\nplt.plot(history.history['loss'])\nplt.plot(history.history['val_loss'])\nplt.title(\"Model Loss\")\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend(['Train', 'Test'])\nplt.ylim(ymax = 2, ymin = 0)\nplt.grid()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(10,8))\nplt.plot(history.history['acc'])\nplt.plot(history.history['val_acc'])\nplt.title(\"Model Accuracy\")\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend(['Train', 'Test'])\nplt.ylim(ymax = 1, ymin = 0)\nplt.grid()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(figsize=(10,8))\nplt.plot(history.history['f1'])\nplt.plot(history.history['val_f1'])\nplt.title(\"Model F1-Score\")\nplt.xlabel('Epochs')\nplt.ylabel('f1')\nplt.legend(['Train', 'Test'])\nplt.ylim(ymax = 1, ymin = 0)\nplt.grid()\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save(\"resnetplant.h5\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Make predictions"},{"metadata":{"trusted":true},"cell_type":"code","source":"from tensorflow import keras\nmodel = keras.models.load_model('../input/resnet/resnetplant.h5')","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"test_dataset = (\n    tf.data.Dataset\n    .list_files('../input/c/plant-pathology-2021-fgvc8/test_images/'+\"*\")\n    .map(decode_image)\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":"pred_labels","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}