{"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":"markdown","source":"## Cassava Leaf Disease Classification:\n\n# Best Keras CNN\n\n![Cassava](https://cdn.hauschka.com/images/system/plant_library/hauschka/manihot-esculenta-crantz-gross.jpg)\n\n### The final part of this [Cassava Leaf Disease: Keras CNN baseline](https://www.kaggle.com/maksymshkliarevskyi/cassava-leaf-disease-keras-cnn-baseline) and this [Cassava Leaf Disease: Keras CNN prediction](https://www.kaggle.com/maksymshkliarevskyi/cassava-leaf-disease-keras-cnn-prediction) notebooks.\n\n### Some models and weights stored in this dataset: [Cassava Leaf Disease Models](https://www.kaggle.com/maksymshkliarevskyi/cassava-leaf-disease-models)\n\n#### Here you'll find:\n* examples of ImageDataGenerator work;\n* my best experiments with EfficientNet CNNs;\n* visualizations of CNN intermediate activations;\n* something else interesting in the future.\n\n#### Ideas for future improvements:\n* try various image sizes;\n* try various batch sizes;\n* experiments with learning rate;\n* experiments with data augmentation;\n* other.\n\n#### I am grateful to François Cholet for the book \"Deep Learning with Python\", wherefrom I borrowed some useful techniques.\n\n### History of changes:\n#### Ver.4: changed TARGET_SIZE; removed unnecessary parameters of ImageDataGenerator","metadata":{}},{"cell_type":"markdown","source":"## Loading packages","metadata":{}},{"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":"2022-08-18T06:46:50.001685Z","iopub.execute_input":"2022-08-18T06:46:50.002041Z","iopub.status.idle":"2022-08-18T06:46:55.533425Z","shell.execute_reply.started":"2022-08-18T06:46:50.002005Z","shell.execute_reply":"2022-08-18T06:46:55.532603Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Work directory","metadata":{}},{"cell_type":"code","source":"WORK_DIR = '../input/cassava-leaf-disease-classification'\nos.listdir(WORK_DIR)","metadata":{"execution":{"iopub.status.busy":"2022-08-18T06:47:00.043085Z","iopub.execute_input":"2022-08-18T06:47:00.043411Z","iopub.status.idle":"2022-08-18T06:47:00.052850Z","shell.execute_reply.started":"2022-08-18T06:47:00.043381Z","shell.execute_reply":"2022-08-18T06:47:00.051797Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# First look at the data","metadata":{}},{"cell_type":"code","source":"print('Train images: %d' %len(os.listdir(\n    os.path.join(WORK_DIR, \"train_images\"))))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-08-18T06:47:05.532616Z","iopub.execute_input":"2022-08-18T06:47:05.533035Z","iopub.status.idle":"2022-08-18T06:47:05.781222Z","shell.execute_reply.started":"2022-08-18T06:47:05.533001Z","shell.execute_reply":"2022-08-18T06:47:05.780455Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"with open(os.path.join(WORK_DIR, \"label_num_to_disease_map.json\")) as file:\n    print(json.dumps(json.loads(file.read()), indent=4))","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-08-18T06:47:07.999743Z","iopub.execute_input":"2022-08-18T06:47:08.000108Z","iopub.status.idle":"2022-08-18T06:47:08.010433Z","shell.execute_reply.started":"2022-08-18T06:47:08.000077Z","shell.execute_reply":"2022-08-18T06:47:08.009446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_labels = pd.read_csv(os.path.join(WORK_DIR, \"train.csv\"))\ntrain_labels.head()","metadata":{"execution":{"iopub.status.busy":"2022-08-18T06:47:13.385691Z","iopub.execute_input":"2022-08-18T06:47:13.386166Z","iopub.status.idle":"2022-08-18T06:47:13.428537Z","shell.execute_reply.started":"2022-08-18T06:47:13.386115Z","shell.execute_reply":"2022-08-18T06:47:13.427699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.set_style(\"whitegrid\")\nfig, ax = plt.subplots(figsize = (6, 4))\n\nfor i in ['top', 'right', 'left']:\n    ax.spines[i].set_visible(False)\nax.spines['bottom'].set_color('black')\n\nsns.countplot(train_labels.label, edgecolor = 'black',\n              palette = reversed(sns.color_palette(\"viridis\", 5)))\nplt.xlabel('Classes', fontfamily = 'serif', size = 15)\nplt.ylabel('Count', fontfamily = 'serif', size = 15)\nplt.xticks(fontfamily = 'serif', size = 12)\nplt.yticks(fontfamily = 'serif', size = 12)\nax.grid(axis = 'y', linestyle = '--', alpha = 0.9)\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-08-18T06:47:19.373425Z","iopub.execute_input":"2022-08-18T06:47:19.373744Z","iopub.status.idle":"2022-08-18T06:47:19.551227Z","shell.execute_reply.started":"2022-08-18T06:47:19.373713Z","shell.execute_reply":"2022-08-18T06:47:19.550295Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Some photos of \"0\": \"Cassava Bacterial Blight (CBB)\"","metadata":{}},{"cell_type":"code","source":"sample = train_labels[train_labels.label == 0].sample(3)\nplt.figure(figsize=(15, 5))\nfor ind, (image_id, label) in enumerate(zip(sample.image_id, sample.label)):\n    plt.subplot(1, 3, ind + 1)\n    img = cv2.imread(os.path.join(WORK_DIR, \"train_images\", image_id))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    plt.imshow(img)\n    plt.axis(\"off\")\n    \nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-08-18T06:47:25.775008Z","iopub.execute_input":"2022-08-18T06:47:25.775344Z","iopub.status.idle":"2022-08-18T06:47:26.486167Z","shell.execute_reply.started":"2022-08-18T06:47:25.775315Z","shell.execute_reply":"2022-08-18T06:47:26.484679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Some photos of \"1\": \"Cassava Brown Streak Disease (CBSD)\"","metadata":{}},{"cell_type":"code","source":"sample = train_labels[train_labels.label == 1].sample(3)\nplt.figure(figsize=(15, 5))\nfor ind, (image_id, label) in enumerate(zip(sample.image_id, sample.label)):\n    plt.subplot(1, 3, ind + 1)\n    img = cv2.imread(os.path.join(WORK_DIR, \"train_images\", image_id))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    plt.imshow(img)\n    plt.axis(\"off\")\n    \nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-08-18T06:47:32.134807Z","iopub.execute_input":"2022-08-18T06:47:32.135275Z","iopub.status.idle":"2022-08-18T06:47:32.769166Z","shell.execute_reply.started":"2022-08-18T06:47:32.135240Z","shell.execute_reply":"2022-08-18T06:47:32.767461Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Some photos of \"2\": \"Cassava Green Mottle (CGM)\"","metadata":{}},{"cell_type":"code","source":"sample = train_labels[train_labels.label == 2].sample(3)\nplt.figure(figsize=(15, 5))\nfor ind, (image_id, label) in enumerate(zip(sample.image_id, sample.label)):\n    plt.subplot(1, 3, ind + 1)\n    img = cv2.imread(os.path.join(WORK_DIR, \"train_images\", image_id))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    plt.imshow(img)\n    plt.axis(\"off\")\n    \nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-08-18T06:47:38.987452Z","iopub.execute_input":"2022-08-18T06:47:38.987849Z","iopub.status.idle":"2022-08-18T06:47:39.617556Z","shell.execute_reply.started":"2022-08-18T06:47:38.987814Z","shell.execute_reply":"2022-08-18T06:47:39.616670Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Some photos of \"3\": \"Cassava Mosaic Disease (CMD)\"","metadata":{}},{"cell_type":"code","source":"sample = train_labels[train_labels.label == 3].sample(3)\nplt.figure(figsize=(15, 5))\nfor ind, (image_id, label) in enumerate(zip(sample.image_id, sample.label)):\n    plt.subplot(1, 3, ind + 1)\n    img = cv2.imread(os.path.join(WORK_DIR, \"train_images\", image_id))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    plt.imshow(img)\n    plt.axis(\"off\")\n    \nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-08-18T06:47:44.559312Z","iopub.execute_input":"2022-08-18T06:47:44.559636Z","iopub.status.idle":"2022-08-18T06:47:45.196212Z","shell.execute_reply.started":"2022-08-18T06:47:44.559604Z","shell.execute_reply":"2022-08-18T06:47:45.194474Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Some photos of \"4\": \"Healthy\"","metadata":{}},{"cell_type":"code","source":"sample = train_labels[train_labels.label == 4].sample(3)\nplt.figure(figsize=(15, 5))\nfor ind, (image_id, label) in enumerate(zip(sample.image_id, sample.label)):\n    plt.subplot(1, 3, ind + 1)\n    img = cv2.imread(os.path.join(WORK_DIR, \"train_images\", image_id))\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    plt.imshow(img)\n    plt.axis(\"off\")\n    \nplt.show()","metadata":{"_kg_hide-input":true,"execution":{"iopub.status.busy":"2022-08-18T06:47:50.102994Z","iopub.execute_input":"2022-08-18T06:47:50.103357Z","iopub.status.idle":"2022-08-18T06:47:50.766567Z","shell.execute_reply.started":"2022-08-18T06:47:50.103322Z","shell.execute_reply":"2022-08-18T06:47:50.765701Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Preparation for modeling","metadata":{}},{"cell_type":"code","source":"# Main parameters\nBATCH_SIZE = 8\nSTEPS_PER_EPOCH = len(train_labels)*0.8 / BATCH_SIZE\nVALIDATION_STEPS = len(train_labels)*0.2 / BATCH_SIZE\nEPOCHS = 20\nTARGET_SIZE = 512","metadata":{"execution":{"iopub.status.busy":"2022-08-18T06:47:55.806115Z","iopub.execute_input":"2022-08-18T06:47:55.806439Z","iopub.status.idle":"2022-08-18T06:47:55.811294Z","shell.execute_reply.started":"2022-08-18T06:47:55.806407Z","shell.execute_reply":"2022-08-18T06:47:55.810371Z"},"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,\n                                     preprocessing_function = None,\n                                     rotation_range = 45,\n                                     zoom_range = 0.2,\n                                     horizontal_flip = True,\n                                     vertical_flip = True,\n                                     fill_mode = 'nearest',\n                                     shear_range = 0.1,\n                                     height_shift_range = 0.1,\n                                     width_shift_range = 0.1)\n\ntrain_generator = train_datagen.flow_from_dataframe(train_labels,\n                         directory = os.path.join(WORK_DIR, \"train_images\"),\n                         subset = \"training\",\n                         x_col = \"image_id\",\n                         y_col = \"label\",\n                         target_size = (TARGET_SIZE, TARGET_SIZE),\n                         batch_size = BATCH_SIZE,\n                         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(WORK_DIR, \"train_images\"),\n                         subset = \"validation\",\n                         x_col = \"image_id\",\n                         y_col = \"label\",\n                         target_size = (TARGET_SIZE, TARGET_SIZE),\n                         batch_size = BATCH_SIZE,\n                         class_mode = \"sparse\")","metadata":{"execution":{"iopub.status.busy":"2022-08-18T06:47:59.934198Z","iopub.execute_input":"2022-08-18T06:47:59.934532Z","iopub.status.idle":"2022-08-18T06:48:26.683429Z","shell.execute_reply.started":"2022-08-18T06:47:59.934494Z","shell.execute_reply":"2022-08-18T06:48:26.682463Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"There is a wide space for experimentation here. The cells below show how the ImageDataGenerator works.","metadata":{}},{"cell_type":"markdown","source":"### Random photo before augmentation","metadata":{}},{"cell_type":"code","source":"img_path = os.path.join(WORK_DIR, \"train_images\", train_labels.image_id[20])\nimg = image.load_img(img_path, target_size = (TARGET_SIZE, 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":"2022-08-18T06:48:26.685184Z","iopub.execute_input":"2022-08-18T06:48:26.685510Z","iopub.status.idle":"2022-08-18T06:48:26.926576Z","shell.execute_reply.started":"2022-08-18T06:48:26.685474Z","shell.execute_reply":"2022-08-18T06:48:26.925723Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### This photo after augmentation","metadata":{}},{"cell_type":"code","source":"generator = train_datagen.flow_from_dataframe(train_labels.iloc[20:21],\n                         directory = os.path.join(WORK_DIR, \"train_images\"),\n                         x_col = \"image_id\",\n                         y_col = \"label\",\n                         target_size = (TARGET_SIZE, TARGET_SIZE),\n                         batch_size = BATCH_SIZE,\n                         class_mode = \"sparse\")\n\naug_images = [generator[0][0][0]/255 for i in range(10)]\nfig, axes = plt.subplots(2, 5, figsize = (20, 10))\naxes = axes.flatten()\nfor img, ax in zip(aug_images, axes):\n    ax.imshow(img)\n    ax.axis('off')\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2022-08-18T06:48:38.192946Z","iopub.execute_input":"2022-08-18T06:48:38.193277Z","iopub.status.idle":"2022-08-18T06:48:42.194359Z","shell.execute_reply.started":"2022-08-18T06:48:38.193244Z","shell.execute_reply":"2022-08-18T06:48:42.191682Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Modeling","metadata":{}},{"cell_type":"markdown","source":"At first, we'll load the basic EfficientNetB0 CNN with \"imagenet\" weights. I created this model before and store it in my dataset created especially for this competition: [Cassava Leaf Disease Models](https://www.kaggle.com/maksymshkliarevskyi/cassava-leaf-disease-models).","metadata":{}},{"cell_type":"code","source":"# Code for basic EfficientNetB0 CNN\n\n# def create_model():\n#     conv_base = EfficientNetB0(include_top = False, weights = 'imagenet',\n#                                input_shape = (TARGET_SIZE, 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\n\n# model = create_model()\n# model.summary()","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model.save('./basic_EfNetB0_imagenet_512.h5')","metadata":{"_kg_hide-input":true,"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Creating the CNN","metadata":{}},{"cell_type":"code","source":"def create_model():\n    conv_base = EfficientNetB0(include_top = False, weights = None,\n                               input_shape = (TARGET_SIZE, 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":"2022-08-18T06:49:15.262351Z","iopub.execute_input":"2022-08-18T06:49:15.262687Z","iopub.status.idle":"2022-08-18T06:49:15.271037Z","shell.execute_reply.started":"2022-08-18T06:49:15.262655Z","shell.execute_reply":"2022-08-18T06:49:15.270004Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model = create_model()\nmodel.summary()","metadata":{"_kg_hide-output":true,"execution":{"iopub.status.busy":"2022-08-18T06:49:19.455701Z","iopub.execute_input":"2022-08-18T06:49:19.456071Z","iopub.status.idle":"2022-08-18T06:49:23.807739Z","shell.execute_reply.started":"2022-08-18T06:49:19.456039Z","shell.execute_reply":"2022-08-18T06:49:23.806966Z"},"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":"2022-08-18T06:49:23.812446Z","iopub.execute_input":"2022-08-18T06:49:23.812704Z","iopub.status.idle":"2022-08-18T06:49:23.820486Z","shell.execute_reply.started":"2022-08-18T06:49:23.812677Z","shell.execute_reply":"2022-08-18T06:49:23.819095Z"},"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":"2022-08-18T06:49:36.482211Z","iopub.execute_input":"2022-08-18T06:49:36.482540Z","iopub.status.idle":"2022-08-18T06:49:37.346521Z","shell.execute_reply.started":"2022-08-18T06:49:36.482502Z","shell.execute_reply":"2022-08-18T06:49:37.345733Z"},"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 = 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":"2022-08-18T06:49:44.234313Z","iopub.execute_input":"2022-08-18T06:49:44.234635Z"},"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,"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":"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":{"trusted":true},"execution_count":null,"outputs":[]},{"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":"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":{"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(WORK_DIR, \"sample_submission.csv\"))\nss","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(WORK_DIR,  \"test_images\", image_id))\n    image = image.resize((TARGET_SIZE, 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":[]},{"cell_type":"markdown","source":"### See also [Cassava Leaf Disease: Keras CNN baseline](https://www.kaggle.com/maksymshkliarevskyi/cassava-leaf-disease-keras-cnn-baseline)","metadata":{}},{"cell_type":"markdown","source":"## WORK IN PROGRESS...","metadata":{}}]}