{"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":"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 to 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","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport numpy as np\nimport pandas as pd \nimport matplotlib.pyplot as plt\n\nimport tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import (EarlyStopping, ModelCheckpoint, \n                                        ReduceLROnPlateau)\nnp.random.seed(452)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"main_dir = '../input/cassava-leaf-disease-classification'\ntrain_df = pd.read_csv(main_dir + '/train.csv')\ntrain_df['label'] = train_df['label'].astype('str')\ntrain_df.head()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# check the shape of the images\ntrain_image_paths = main_dir + '/train_images'\n\nfor file in train_df.image_id[:5]:\n    print(plt.imread(os.path.join(train_image_paths, file)).shape)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = (224, 224)\nBATCH_SIZE = 16 \n#STEPS_PER_EPOCH = len(train_df) * 0.8 // BATCH_SIZE\n#VALIDATION_STEPS = len(train_df) * 0.2 // BATCH_SIZE\nEPOCHS = 10","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# create train and validation augmentations\ntrain_aug = ImageDataGenerator(rotation_range = 40,\n                               width_shift_range = 0.2, \n                               height_shift_range = 0.2, \n                               zoom_range = 0.2,\n                               shear_range = 0.2, \n                               brightness_range = [0.2, 1.0], \n                               horizontal_flip = True, \n                               vertical_flip = True, \n                               validation_split = 0.2, \n                               fill_mode = 'nearest')\n\n\nval_aug = ImageDataGenerator(validation_split = 0.2)\n\n\ntrain_gen = train_aug.flow_from_dataframe(train_df, \n                                          directory = train_image_paths, \n                                          subset = 'training', \n                                          x_col = 'image_id',\n                                          y_col = 'label', \n                                          target_size = IMAGE_SIZE, \n                                          batch_size = BATCH_SIZE, \n                                          class_mode = 'sparse', \n                                          seed = 42, \n                                          shuffle = True)\n\n\nval_gen = val_aug.flow_from_dataframe(train_df, \n                                      directory = train_image_paths, \n                                      subset = 'validation', \n                                      x_col = 'image_id',\n                                      y_col = 'label', \n                                      target_size = IMAGE_SIZE, \n                                      batch_size = BATCH_SIZE, \n                                      class_mode = 'sparse', \n                                      seed = 42, \n                                      shuffle = False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":" from tensorflow.keras.models import Sequential\nfrom keras.layers.core import Activation, Flatten, Dropout, Dense\nfrom keras import backend as K\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.convolutional import Conv2D\nfrom keras.layers.convolutional import MaxPooling2D\nfrom keras.optimizers import Adam\nmodel = Sequential()\ninputShape = (224, 224,3)\nchanDim = -1\nif K.image_data_format() == \"channels_first\":\n    inputShape = (3, 224, 224)\n    chanDim = 1\nmodel.add(Conv2D(32, (3, 3), padding=\"same\",input_shape=inputShape))\nmodel.add(Activation(\"relu\"))\nmodel.add(BatchNormalization(axis=chanDim))\nmodel.add(MaxPooling2D(pool_size=(3, 3)))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(64, (3, 3), padding=\"same\"))\nmodel.add(Activation(\"relu\"))\nmodel.add(BatchNormalization(axis=chanDim))\nmodel.add(Conv2D(64, (3, 3), padding=\"same\"))\nmodel.add(Activation(\"relu\"))\nmodel.add(BatchNormalization(axis=chanDim))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(128, (3, 3), padding=\"same\"))\nmodel.add(Activation(\"relu\"))\nmodel.add(BatchNormalization(axis=chanDim))\nmodel.add(Conv2D(128, (3, 3), padding=\"same\"))\nmodel.add(Activation(\"relu\"))\nmodel.add(BatchNormalization(axis=chanDim))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\nmodel.add(Flatten())\nmodel.add(Dense(1024))\nmodel.add(Activation(\"relu\"))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.5))\nmodel.add(Dense(5))\nmodel.add(Activation(\"softmax\"))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.summary()","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from tensorflow import keras\nfrom tensorflow.keras import layers\n\nopt = keras.optimizers.Adam(learning_rate=0.01)\nmodel.compile(loss='categorical_crossentropy', optimizer=opt)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_path = ModelCheckpoint('best_weights.h5', \n                             save_best_only = True, \n                             monitor = 'val_loss', \n                             mode = 'min', \n                             verbose = 1)\n\n# learning rate scheduler\nreduce_lr = ReduceLROnPlateau(monitor = 'val_loss', \n                              factor = 0.3, \n                              patience = 2, \n                              min_lr = 1e-6, \n                              mode = 'min', \n                              verbose = 1)\n\n# early stopping\nearly_stopping = EarlyStopping(monitor = 'val_loss', \n                               patience = 3, \n                               mode = 'min', \n                               verbose = 1, \n                               restore_best_weights = True)","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# compile the model\nmodel.compile(optimizer = tf.keras.optimizers.Adam(1e-3), \n              loss = 'sparse_categorical_crossentropy', \n              metrics = ['accuracy'])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"history = model.fit(train_gen, \n                    steps_per_epoch = STEPS_PER_EPOCH, \n                    epochs = EPOCHS, \n                    validation_data = val_gen, \n                    validation_steps = VALIDATION_STEPS, \n                    callbacks = [model_path, early_stopping, reduce_lr])","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# plot the loss and accuracy of the model\nhistory_df = pd.DataFrame(history.history)\nhistory_df.loc[:, ['loss', 'val_loss']].plot()\nhistory_df.loc[:, ['accuracy', 'val_accuracy']].plot();","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# # predict the values from the test set (a part of training set)\ny_pred = model.predict(val_gen)\nprint(y_pred)\n# # Convert predictions classes to one hot vectors \ny_pred_classes = np.argmax(y_pred, axis=1) \n\n# # converting validation labels from str to int\nval_labels = [int(i) for i in train_df.label]\n\n# # compute the confusion matrix\nconfusion_mtx = confusion_matrix(val_labels, y_pred_classes) \n\n# # plot the confusion matrix\ndisplay_confusion_matrix(confusion_mtx, CLASSES, True) ","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix, plot_confusion_matrix\nconfusion_matrix(y_true=val_gen, y_pred=y_pred)\nconfusion_matrix(val_gen,  y_pred, labels=(0,1,2,3))\ntp, fn, fp, tn = confusion_matrix(val_gen, y_pred, labels=(1,0)).ravel()\nprecision = tp/(tp+fp)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}