{"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":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport datetime\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\nimport tensorflow as tf\nfrom tensorflow.keras import models, layers\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom tensorflow.keras.optimizers import Adam\n\n# ignoring warnings\nimport warnings\nwarnings.simplefilter(\"ignore\")\n\nimport os, cv2, json\nfrom PIL import Image","metadata":{"_uuid":"d629ff2d2480ee46fbb7e2d37f6b5fab8052498a","_cell_guid":"79c7e3d0-c299-4dcb-8224-4455121ee9b0","_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-09-27T10:16:02.076162Z","iopub.execute_input":"2021-09-27T10:16:02.07665Z","iopub.status.idle":"2021-09-27T10:16:07.377416Z","shell.execute_reply.started":"2021-09-27T10:16:02.076615Z","shell.execute_reply":"2021-09-27T10:16:07.376514Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"class CFG:    \n    # config\n    WORK_DIR = '../input/cassava-leaf-disease-classification'\n    BATCH_SIZE = 8\n    EPOCHS = 5\n    TARGET_SIZE = 512","metadata":{"execution":{"iopub.status.busy":"2021-09-27T10:16:07.379399Z","iopub.execute_input":"2021-09-27T10:16:07.379768Z","iopub.status.idle":"2021-09-27T10:16:07.387452Z","shell.execute_reply.started":"2021-09-27T10:16:07.379739Z","shell.execute_reply":"2021-09-27T10:16:07.385648Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Functions","metadata":{}},{"cell_type":"code","source":"def create_model():\n    conv_base = EfficientNetB0(include_top = False, weights = None,\n                               input_shape = (CFG.TARGET_SIZE, CFG.TARGET_SIZE, 3))\n    model = conv_base.output\n    model = layers.GlobalAveragePooling2D()(model)\n    model = layers.Dense(5, activation = \"softmax\")(model)\n    model = models.Model(conv_base.input, model)\n\n    model.compile(optimizer = Adam(lr = 0.001),\n                  loss = \"sparse_categorical_crossentropy\",\n                  metrics = [\"acc\"])\n    return model","metadata":{"execution":{"iopub.status.busy":"2021-09-27T10:16:07.389258Z","iopub.execute_input":"2021-09-27T10:16:07.38965Z","iopub.status.idle":"2021-09-27T10:16:07.407349Z","shell.execute_reply.started":"2021-09-27T10:16:07.389611Z","shell.execute_reply":"2021-09-27T10:16:07.406196Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def activation_layer_vis(img, activation_layer = 0, layers = 10):\n    layer_outputs = [layer.output for layer in model.layers[:layers]]\n    activation_model = models.Model(inputs = model.input, outputs = layer_outputs)\n    activations = activation_model.predict(img)\n    \n    rows = int(activations[activation_layer].shape[3] / 3)\n    cols = int(activations[activation_layer].shape[3] / rows)\n    fig, axes = plt.subplots(rows, cols, figsize = (15, 15 * cols))\n    axes = axes.flatten()\n    \n    for i, ax in zip(range(activations[activation_layer].shape[3]), axes):\n        ax.matshow(activations[activation_layer][0, :, :, i], cmap = 'viridis')\n        ax.axis('off')\n    plt.tight_layout()\n    plt.show()","metadata":{"execution":{"iopub.status.busy":"2021-09-27T10:16:07.409741Z","iopub.execute_input":"2021-09-27T10:16:07.410747Z","iopub.status.idle":"2021-09-27T10:16:07.424764Z","shell.execute_reply.started":"2021-09-27T10:16:07.410672Z","shell.execute_reply":"2021-09-27T10:16:07.423502Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def all_activations_vis(img, layers = 10):\n    layer_outputs = [layer.output for layer in model.layers[:layers]]\n    activation_model = models.Model(inputs = model.input, outputs = layer_outputs)\n    activations = activation_model.predict(img)\n    \n    layer_names = []\n    for layer in model.layers[:layers]: \n        layer_names.append(layer.name) \n\n    images_per_row = 3\n    for layer_name, layer_activation in zip(layer_names, activations): \n        n_features = layer_activation.shape[-1] \n\n        size = layer_activation.shape[1] \n\n        n_cols = n_features // images_per_row \n        display_grid = np.zeros((size * n_cols, images_per_row * size)) \n\n        for col in range(n_cols): \n            for row in range(images_per_row): \n                channel_image = layer_activation[0, :, :, col * images_per_row + row] \n                channel_image -= channel_image.mean() \n                channel_image /= channel_image.std() \n                channel_image *= 64 \n                channel_image += 128 \n                channel_image = np.clip(channel_image, 0, 255).astype('uint8') \n                display_grid[col * size : (col + 1) * size, \n                             row * size : (row + 1) * size] = channel_image \n        scale = 1. / size \n        plt.figure(figsize=(scale * 5 * display_grid.shape[1], \n                            scale * 5 * display_grid.shape[0])) \n        plt.title(layer_name) \n        plt.grid(False)\n        plt.axis('off')\n        plt.imshow(display_grid, aspect = 'auto', cmap = 'viridis')","metadata":{"execution":{"iopub.status.busy":"2021-09-27T10:16:07.427739Z","iopub.execute_input":"2021-09-27T10:16:07.428374Z","iopub.status.idle":"2021-09-27T10:16:07.450851Z","shell.execute_reply.started":"2021-09-27T10:16:07.428336Z","shell.execute_reply":"2021-09-27T10:16:07.449562Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data","metadata":{}},{"cell_type":"code","source":"train_labels = pd.read_csv(os.path.join(CFG.WORK_DIR, \"train.csv\"))\n\nSTEPS_PER_EPOCH = len(train_labels)*0.8 / CFG.BATCH_SIZE\nVALIDATION_STEPS = len(train_labels)*0.2 / CFG.BATCH_SIZE\n\n    \ntrain_labels.head()","metadata":{"execution":{"iopub.status.busy":"2021-09-27T10:16:07.452577Z","iopub.execute_input":"2021-09-27T10:16:07.453184Z","iopub.status.idle":"2021-09-27T10:16:07.520162Z","shell.execute_reply.started":"2021-09-27T10:16:07.453126Z","shell.execute_reply":"2021-09-27T10:16:07.519466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### ImageDataGenerator","metadata":{}},{"cell_type":"code","source":"train_labels.label = train_labels.label.astype('str')\n\ntrain_datagen = ImageDataGenerator(validation_split = 0.2, preprocessing_function = None,\n                                     rotation_range = 45, zoom_range = 0.2,\n                                     horizontal_flip = True, vertical_flip = True,\n                                     fill_mode = 'nearest', shear_range = 0.1,\n                                     height_shift_range = 0.1, width_shift_range = 0.1)\n\ntrain_generator = train_datagen.flow_from_dataframe(train_labels, directory = os.path.join(CFG.WORK_DIR, \"train_images\"),\n                         subset = \"training\", x_col = \"image_id\",\n                         y_col = \"label\", target_size = (CFG.TARGET_SIZE, CFG.TARGET_SIZE),\n                         batch_size = CFG.BATCH_SIZE, class_mode = \"sparse\")\n\n\nvalidation_datagen = ImageDataGenerator(validation_split = 0.2)\n\nvalidation_generator = validation_datagen.flow_from_dataframe(train_labels,\n                         directory = os.path.join(CFG.WORK_DIR, \"train_images\"),\n                         subset = \"validation\", x_col = \"image_id\",\n                         y_col = \"label\", target_size = (CFG.TARGET_SIZE, CFG.TARGET_SIZE),\n                         batch_size = CFG.BATCH_SIZE, class_mode = \"sparse\")","metadata":{"execution":{"iopub.status.busy":"2021-09-27T10:16:07.521468Z","iopub.execute_input":"2021-09-27T10:16:07.521788Z","iopub.status.idle":"2021-09-27T10:16:52.131335Z","shell.execute_reply.started":"2021-09-27T10:16:07.521754Z","shell.execute_reply":"2021-09-27T10:16:52.130383Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"img_path = os.path.join(CFG.WORK_DIR, \"train_images\", train_labels.image_id[20])\nimg = image.load_img(img_path, target_size = (CFG.TARGET_SIZE, CFG.TARGET_SIZE))\nimg_tensor = image.img_to_array(img)\nimg_tensor = np.expand_dims(img_tensor, axis = 0)\nimg_tensor /= 255.\n\nplt.imshow(img_tensor[0])\nplt.axis('off')\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2021-09-27T10:17:19.924119Z","iopub.execute_input":"2021-09-27T10:17:19.924454Z","iopub.status.idle":"2021-09-27T10:17:20.099569Z","shell.execute_reply.started":"2021-09-27T10:17:19.924425Z","shell.execute_reply":"2021-09-27T10:17:20.098534Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Modeling","metadata":{}},{"cell_type":"code","source":"model = create_model()\nmodel.summary()","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2021-09-27T09:01:53.933028Z","iopub.execute_input":"2021-09-27T09:01:53.933348Z","iopub.status.idle":"2021-09-27T09:01:57.963445Z","shell.execute_reply.started":"2021-09-27T09:01:53.933317Z","shell.execute_reply":"2021-09-27T09:01:57.962538Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Our EfficientNet CNN has %d layers' %len(model.layers))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-09-27T09:01:57.967291Z","iopub.execute_input":"2021-09-27T09:01:57.967542Z","iopub.status.idle":"2021-09-27T09:01:57.974882Z","shell.execute_reply.started":"2021-09-27T09:01:57.967515Z","shell.execute_reply":"2021-09-27T09:01:57.974094Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Loading weights","metadata":{}},{"cell_type":"code","source":"model.load_weights('../input/cassava-leaf-disease-models/basic_EfNetB0_imagenet_512.h5')","metadata":{"execution":{"iopub.status.busy":"2021-09-27T09:12:17.492674Z","iopub.execute_input":"2021-09-27T09:12:17.493017Z","iopub.status.idle":"2021-09-27T09:12:18.370431Z","shell.execute_reply.started":"2021-09-27T09:12:17.492987Z","shell.execute_reply":"2021-09-27T09:12:18.369655Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Training","metadata":{}},{"cell_type":"code","source":"model_save = ModelCheckpoint('./EffNetB0_512_8_best_weights.h5', \n                             save_best_only = True, \n                             save_weights_only = True,\n                             monitor = 'val_loss', \n                             mode = 'min', verbose = 1)\nearly_stop = EarlyStopping(monitor = 'val_loss', min_delta = 0.001, \n                           patience = 5, mode = 'min', verbose = 1,\n                           restore_best_weights = True)\nreduce_lr = ReduceLROnPlateau(monitor = 'val_loss', factor = 0.3, \n                              patience = 2, min_delta = 0.001, \n                              mode = 'min', verbose = 1)\n\n\nhistory = model.fit(\n    train_generator,\n    steps_per_epoch = STEPS_PER_EPOCH,\n    epochs = CFG.EPOCHS,\n    validation_data = validation_generator,\n    validation_steps = VALIDATION_STEPS,\n    callbacks = [model_save, early_stop, reduce_lr]\n)","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2021-09-27T09:14:43.774307Z","iopub.execute_input":"2021-09-27T09:14:43.774704Z","iopub.status.idle":"2021-09-27T09:16:53.047105Z","shell.execute_reply.started":"2021-09-27T09:14:43.774668Z","shell.execute_reply":"2021-09-27T09:16:53.043605Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"acc = history.history['acc']\nval_acc = history.history['val_acc']\nloss = history.history['loss']\nval_loss = history.history['val_loss']\n\nepochs = range(1, len(acc) + 1)\n\nfig, (ax1, ax2) = plt.subplots(1, 2, figsize=(15, 5))\nsns.set_style(\"white\")\nplt.suptitle('Train history', size = 15)\n\nax1.plot(epochs, acc, \"bo\", label = \"Training acc\")\nax1.plot(epochs, val_acc, \"b\", label = \"Validation acc\")\nax1.set_title(\"Training and validation acc\")\nax1.legend()\n\nax2.plot(epochs, loss, \"bo\", label = \"Training loss\", color = 'red')\nax2.plot(epochs, val_loss, \"b\", label = \"Validation loss\", color = 'red')\nax2.set_title(\"Training and validation loss\")\nax2.legend()\n\nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2021-09-27T09:13:43.627789Z","iopub.execute_input":"2021-09-27T09:13:43.628139Z","iopub.status.idle":"2021-09-27T09:13:43.65801Z","shell.execute_reply.started":"2021-09-27T09:13:43.628106Z","shell.execute_reply":"2021-09-27T09:13:43.656642Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save('./EffNetB0_512_8.h5')","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Visualization of CNN intermediate activations","metadata":{}},{"cell_type":"markdown","source":"### Visualization of the first layer","metadata":{}},{"cell_type":"code","source":"activation_layer_vis(img_tensor, 0)","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Visualization of the first 5 layers","metadata":{}},{"cell_type":"code","source":"all_activations_vis(img_tensor, 5)","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"Visualization of intermediate activations gives a rough step-by-step understanding of how CNN works.","metadata":{}},{"cell_type":"markdown","source":"# Prediction","metadata":{}},{"cell_type":"code","source":"ss = pd.read_csv(os.path.join(CFG.WORK_DIR, \"sample_submission.csv\"))","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"preds = []\n\nfor image_id in ss.image_id:\n    image = Image.open(os.path.join(CFG.WORK_DIR,  \"test_images\", image_id))\n    image = image.resize((CFG.TARGET_SIZE, CFG.TARGET_SIZE))\n    image = np.expand_dims(image, axis = 0)\n    preds.append(np.argmax(model.predict(image)))\n\nss['label'] = preds\nss","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"ss.to_csv('submission.csv', index = False)","metadata":{"trusted":true},"execution_count":null,"outputs":[]}]}