{"cells":[{"metadata":{},"cell_type":"markdown","source":"## Import Section"},{"metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Read image data "},{"metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","trusted":true},"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()","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Set up some global variables"},{"metadata":{"trusted":true},"cell_type":"code","source":"IMAGE_SIZE = (224, 224)\nBATCH_SIZE = 16 \nSTEPS_PER_EPOCH = len(train_df) * 0.8 // BATCH_SIZE\nVALIDATION_STEPS = len(train_df) * 0.2 // BATCH_SIZE\nEPOCHS = 10","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Data Augmentation"},{"metadata":{"trusted":true},"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\n# create train and validation generators\n# If class_mode = 'sparse', y_col = 'label' column values must be strings\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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Load pretrained EfficientNetB7 Model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# base model\nbase_model = tf.keras.applications.EfficientNetB0(weights = 'imagenet', \n                                                  include_top = False, \n                                                  input_shape = IMAGE_SIZE + (3, ))\n\nx = layers.GlobalAveragePooling2D()(base_model.output)\nx = layers.Dropout(0.5)(x)\noutput = layers.Dense(5, activation = 'softmax')(x)\nmodel = tf.keras.Model(base_model.input, output)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Callbacks"},{"metadata":{"trusted":true},"cell_type":"code","source":"# save model weights\nmodel_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)","execution_count":null,"outputs":[]},{"metadata":{},"cell_type":"markdown","source":"## Compile and fit the model"},{"metadata":{"trusted":true},"cell_type":"code","source":"# compile the model\nmodel.compile(optimizer = tf.keras.optimizers.Adam(1e-3), \n              loss = 'sparse_categorical_crossentropy', \n              metrics = ['accuracy'])\n\n# fit the model\nhistory = 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])","execution_count":null,"outputs":[]},{"metadata":{"trusted":true},"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();","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}