{"cells":[{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages tos load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n        print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Cassava Plant Disease Classfication with Tensorflow/Keras, OpenCV etc.\n\nReference: https://www.kaggle.com/homiarafarhana/cassava-2nd#Data-Agumentation-and-Pre-Processing\n\nFeel free to give some comments on how I can improve or mistake made!!\n\nThis notebook is suitable for dummies/beginners as I myself a beginner also!\n\nIn this Notebook, there are few sections, which you can see on the right tab.\n\nBasically, this is a classification task uses:\n* Tensorflow/Keras\n    * Deep Learning stuff(model building etc.)\n    * Data Augmentation with `ImageDataGenerator`\n    * TensorBoard to visualize model's performance.\n* OpenCV\n    * Displaying pictures from dataset\n* Matplotlib \n    * Visualize augmented images\n    * Illustrate model's performance\n\nAt the last code block under **\"Making Predictions/Submission\"** , you may find useful code block on how to commit your notebook with pre-trained model.\n\nDo upvote if you find this helpful! Thanks in advanced!"},{"metadata":{},"cell_type":"markdown","source":"# Packages needed"},{"metadata":{"trusted":true},"cell_type":"code","source":"import glob\nimport shutil\nimport cv2\nimport os\nfrom keras_preprocessing import image\nfrom keras_preprocessing.image import ImageDataGenerator\nimport matplotlib.pyplot as plt\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.callbacks import Callback, ReduceLROnPlateau, ModelCheckpoint, TensorBoard\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, BatchNormalization, Dropout, Activation, GlobalAveragePooling2D, Dense\nfrom tensorflow.keras.losses import CategoricalCrossentropy\nfrom tensorflow.keras.optimizers import Adam\nfrom tensorflow.keras.metrics import Accuracy\nfrom tensorflow.keras.applications import InceptionResNetV2\nfrom tensorflow.keras import Input\n\n%matplotlib inline\nplt.rcParams[\"figure.figsize\"] = (17, 6) # (w, h)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"markdown","source":"### Directories\n\nOriginal Dataset"},{"metadata":{"trusted":true},"cell_type":"code","source":"TRAINING_DIR = \"../input/cassava-leaf-disease-classification/train_images/\"\nTRAINING_CSV = \"../input/cassava-leaf-disease-classification/train.csv\"\nJSON_LABELS = \"../input/cassava-leaf-disease-classification/label_num_to_disease_map.json\"\nPRETRAINED_MODEL = \"../input/resnet50/resnet50_weights_tf_dim_ordering_tf_kernels_notop.h5\"","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"os.listdir(\"../input\")\nprint(os.listdir(\"../input\"))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df = pd.read_csv(TRAINING_CSV)\ntrain_df[\"label\"] = train_df[\"label\"].astype(\"string\") # for Keras flow_from_dataframe","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_df.head()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"total_images_count = len(train_df.index)\ntotal_train_img_count = int(len(train_df.index) * 0.8)\ntotal_val_img_count = total_images_count - total_train_img_count\nprint(\"Expected images coutns:\")\nprint(\"\\nTotal Images from original directory: {}\".format(total_images_count))\nprint(\"Training Images: {}\".format(total_train_img_count))\nprint(\"Validation Images: {}\".format(total_val_img_count))\n","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"label_df = pd.read_json(JSON_LABELS, orient = 'index')\nlabel_df = label_df.values.flatten().tolist()\nlabel_df","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"train_label_0 = train_df[train_df[\"label\"]== \"0\"]\ntrain_label_1 = train_df[train_df[\"label\"]== \"1\"]\ntrain_label_2 = train_df[train_df[\"label\"]== \"2\"]\ntrain_label_3 = train_df[train_df[\"label\"]== \"3\"]\ntrain_label_4 = train_df[train_df[\"label\"]== \"4\"]\nlen(train_label_4)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"len_by_labels = [\n    len(train_label_0),\n    len(train_label_1),\n    len(train_label_2),\n    len(train_label_3),\n    len(train_label_4),\n]\n\nplt.bar(label_df, len_by_labels)\n\nplt.xlabel('Labels')  \nplt.ylabel('Image Count')\n\nplt.show()  ","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Displaying some images"},{"metadata":{"trusted":true},"cell_type":"code","source":"training_images_dir = TRAINING_DIR + \"/*.jpg\"\nprint(training_images_dir)\ntraining_images = glob.glob(training_images_dir)\nplt.figure(figsize=(12, 12))    \nfor i in range(1, 10):\n    training_image = np.random.choice(training_images)\n    training_image_RGB = cv2.imread(training_image)[...,::-1]\n    print(training_image_RGB.shape)\n    plt.subplot(3, 3, i)\n    plt.imshow(training_image_RGB)\n    plt.axis('off')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Data Pre-processing\n\n- Data augmentation etc."},{"metadata":{"trusted":true},"cell_type":"code","source":"training_datagen = ImageDataGenerator(\n    rescale = 1/255,\n    rotation_range = 100,\n    width_shift_range = 0.2,\n    height_shift_range = 0.2,\n    shear_range = 0.2,\n    zoom_range = 0.3,\n    brightness_range = [0.7, 1.4],\n    horizontal_flip = True,\n    vertical_flip=True,\n    fill_mode = \"nearest\",\n    validation_split=0.2\n)\n\nvalidation_datagen = ImageDataGenerator(\n    rescale = 1/255,\n    validation_split=0.2\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"BATCH_SIZE = 24\nIMG_WIDTH = 300\nIMG_HEIGHT = 300\nCHANNEL = 3\n\nprint(\"\\nTraining Dataset\")\ntrain_ds = training_datagen.flow_from_dataframe(\n    train_df,\n    TRAINING_DIR,\n    target_size = (IMG_WIDTH, IMG_HEIGHT),\n    class_mode = \"categorical\",\n    batch_size = BATCH_SIZE,\n    x_col = \"image_id\",\n    y_col = \"label\",\n    shuffle = True,\n    subset = \"training\"\n\n)\nprint(\"\\nValidation Dataset\")\nvalidation_ds = validation_datagen.flow_from_dataframe(\n    train_df,\n    TRAINING_DIR,\n    target_size = (IMG_WIDTH, IMG_HEIGHT),\n    class_mode = \"categorical\",\n    batch_size = BATCH_SIZE,\n    x_col = \"image_id\",\n    y_col = \"label\",\n    shuffle = False,\n    subset = \"validation\"\n)\nprint(\"\\nClass Indices:\")\nprint(train_ds.class_indices)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Display Augmented Data"},{"metadata":{"trusted":true},"cell_type":"code","source":"plt.figure(\n    figsize = (12, 12)\n)\n\nfor i in range (1, 10):\n    img, label = train_ds.next()\n    plt.subplot(3, 3, i)\n    plt.imshow(img[0])\n    plt.axis(\"Off\")","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Callbacks"},{"metadata":{"trusted":true},"cell_type":"code","source":"class theCallBacks(Callback):\n    def on_epoch_end(self, epoch, logs={}):\n        if((logs.get(\"val_accuracy\")>0.92) and (logs.get(\"accuracy\")>0.92)): \n            print(\"\\Training Accuracy> 0.92 & Validation Accuracy> 0.92\\nCancelling training!\")\n            self.model.stop_training = True\n\n            \ncallback_on_metrics = theCallBacks() #Instantiate theCallBacks\n\nreduce_lr = ReduceLROnPlateau(\n                    monitor='val_loss', \n                    factor=0.5,\n                    patience= 2, \n                    verbose = 1,\n                    cooldown = 1,\n                    min_lr=0.0001)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Defining Loss Function, Optimizer, Desired Metrics"},{"metadata":{"trusted":true},"cell_type":"code","source":"loss_func = CategoricalCrossentropy()\noptimizer = Adam(learning_rate=0.001)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Model Checkpoint"},{"metadata":{"trusted":true},"cell_type":"code","source":"model_checkpoint_path=\"./cassava_Model.h5\"\ncheckpoint = ModelCheckpoint(model_checkpoint_path, monitor='val_accuracy', verbose=1, save_best_only=True,mode='max')","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# TensorBoard\nEnable this if you wanna use TensorBoard"},{"metadata":{"trusted":true},"cell_type":"code","source":"# class LearningRateLogger(Callback):\n#     def __init__(self):\n#         super().__init__()\n#         self._supports_tf_logs = True\n\n#     def on_epoch_end(self, epoch, logs=None):\n#         if logs is None or \"learning_rate\" in logs:\n#             return\n#         logs[\"learning_rate\"] = self.model.optimizer.lr\n        \n#log_dir = \"logs/fit/\" + datetime.datetime.now().strftime(\"%Y%m%d-%H%M%S\")\n# tensorboard_callback = TensorBoard(log_dir=log_dir, histogram_freq=1)     \n\n# source: https://stackoverflow.com/questions/49127214/keras-how-to-output-learning-rate-onto-tensorboard","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Load TensorBoard with below line!"},{"metadata":{"trusted":true},"cell_type":"code","source":"# %load_ext tensorboard\n# %tensorboard --logdir logs","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Model building\n\nTransfer Learning model with ResNet50."},{"metadata":{"trusted":true},"cell_type":"code","source":"new_input = Input(shape=(IMG_WIDTH, IMG_HEIGHT, CHANNEL))","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"base_model = InceptionResNetV2(\n    include_top=False,\n    weights=\"imagenet\",\n    input_tensor=new_input,\n)\nbase_model.trainable = True","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Unfreeze certain layers/block(s)\n\n\nBelow Code block freeze all except the last block of InceptionResNetV2"},{"metadata":{"trusted":true},"cell_type":"code","source":"# for layer in base_model.layers[:143]:\n#     layer.trainable = False\n#    \n\n# for i, layer in enumerate(base_model.layers):\n#     print(i,layer.name , \"-->\", layer.trainable)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Model Building"},{"metadata":{"trusted":true},"cell_type":"code","source":"def create_model():\n\n    model = Sequential()\n    model.add(base_model)\n    model.add(BatchNormalization())\n    model.add(GlobalAveragePooling2D())\n    model.add(Dropout(0.5))\n    \n    model.add(Dense(256,activation = \"relu\"))\n\n    model.add(Dense(5, activation = \"softmax\"))\n\n    return model","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model = create_model()\n\nmodel.compile(\n    optimizer=optimizer,\n    loss = loss_func,\n    metrics = [\"accuracy\"]\n)\n\nmodel.summary()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"### Train the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"num_epochs = 10\nsteps_per_epoch = total_train_img_count // BATCH_SIZE","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"history = model.fit(\n    train_ds,\n    epochs = num_epochs,\n    validation_data = validation_ds,\n    verbose = 1,\n    steps_per_epoch = steps_per_epoch,\n    callbacks = [\n        reduce_lr,\n        callback_on_metrics,\n        #LearningRateLogger(),\n        #tensorboard_callback, # Enable these two if using TensorBoard\n        checkpoint\n                ]\n)","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"cell_type":"code","source":"model.save(\"./cassava_Model.h5\")\n","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Illustrates Model Performance"},{"metadata":{"trusted":true},"cell_type":"code","source":"acc = history.history[\"accuracy\"]\nval_acc = history.history[\"val_accuracy\"]\nloss = history.history[\"loss\"]\nval_loss = history.history[\"val_loss\"]\n\nepochs = range(len(acc))\n\nplt.plot(epochs, acc, \"r\", label=\"Training Accuracy\")\nplt.plot(epochs, val_acc, \"b\", label=\"Validation Accuracy\")\nplt.title(\"Training and Validation Accuracy\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Accuracy\")\nplt.legend()\nplt.figure()\n\nplt.plot(epochs, loss, \"r\", label=\"Training Loss\")\nplt.plot(epochs, val_loss, \"b\", label=\"Validation Loss\")\nplt.title(\"Training and Validation Loss\")\nplt.xlabel(\"Epochs\")\nplt.ylabel(\"Loss\")\nplt.legend()\nplt.figure()\n\nplt.show()","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"# Making Predictions/Submission\n\nIf you have trained model that you trained locally or somewhere else, you can use below code block for submission purposes. However, you have to upload your model first and change the Path accordingly at this line of code:\n> model = tf.keras.models.load_model(\"./cassava_Model.h5\")"},{"metadata":{"trusted":true},"cell_type":"code","source":"import tensorflow as tf\n\nmodel = tf.keras.models.load_model(\"./cassava_Model.h5\")\npredicted = []\nsample_submission = pd.read_csv('../input/cassava-leaf-disease-classification/sample_submission.csv')\n\nfor image in sample_submission.image_id:\n    img = tf.keras.preprocessing.image.load_img('../input/cassava-leaf-disease-classification/test_images/' + image)\n    img = tf.keras.preprocessing.image.img_to_array(img)\n    img = tf.keras.preprocessing.image.smart_resize(img, (IMG_WIDTH, IMG_HEIGHT))\n    img = tf.reshape(img, (-1, IMG_WIDTH, IMG_HEIGHT, CHANNEL))\n    prediction = model.predict(img/255)  \n    predicted.append(np.argmax(prediction))\n\nsubmission = pd.DataFrame({'image_id': sample_submission.image_id, 'label': predicted})\nsubmission.to_csv('submission.csv', index=False) ","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}