{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.9","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":13836,"databundleVersionId":1718836,"sourceType":"competition"}],"dockerImageVersionId":30060,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Libraries and Configurations","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport tensorflow as tf\nimport tensorflow_addons as tfa\nimport glob, warnings\nimport matplotlib.pyplot as plt\nfrom sklearn.metrics import confusion_matrix, classification_report\nimport seaborn as sns\n\nwarnings.filterwarnings('ignore')\nprint('TensorFlow Version ' + tf.__version__)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-05-29T15:16:20.655778Z","iopub.execute_input":"2024-05-29T15:16:20.656154Z","iopub.status.idle":"2024-05-29T15:16:20.662474Z","shell.execute_reply.started":"2024-05-29T15:16:20.656123Z","shell.execute_reply":"2024-05-29T15:16:20.661516Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_SIZE = 224\nBATCH_SIZE = 16\nEPOCHS = 7\n\nTRAIN_PATH = '/kaggle/input/cassava-leaf-disease-classification/train_images'\nTEST_PATH = '/kaggle/input/cassava-leaf-disease-classification/test_images'\n\nDF_TRAIN = pd.read_csv('/kaggle/input/cassava-leaf-disease-classification/train.csv', dtype='str')\nTEST_IMAGES = glob.glob(TEST_PATH + '/*.jpg')\nDF_TEST = pd.DataFrame(TEST_IMAGES, columns = ['image_path'])\n\nclasses = {0 : \"Cassava Bacterial Blight (CBB)\",\n           1 : \"Cassava Brown Streak Disease (CBSD)\",\n           2 : \"Cassava Green Mottle (CGM)\",\n           3 : \"Cassava Mosaic Disease (CMD)\",\n           4 : \"Healthy\"}","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:16:21.806770Z","iopub.execute_input":"2024-05-29T15:16:21.807147Z","iopub.status.idle":"2024-05-29T15:16:21.839289Z","shell.execute_reply.started":"2024-05-29T15:16:21.807115Z","shell.execute_reply":"2024-05-29T15:16:21.838373Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Augmentations","metadata":{}},{"cell_type":"code","source":"def data_augment(image):\n    p_spatial = tf.random.uniform([], 0, 1.0, dtype = tf.float32)\n    p_rotate = tf.random.uniform([], 0, 1.0, dtype = tf.float32)\n    p_pixel_1 = tf.random.uniform([], 0, 1.0, dtype = tf.float32)\n    p_pixel_2 = tf.random.uniform([], 0, 1.0, dtype = tf.float32)\n    p_pixel_3 = tf.random.uniform([], 0, 1.0, dtype = tf.float32)\n    \n    # Flips\n    image = tf.image.random_flip_left_right(image)\n    image = tf.image.random_flip_up_down(image)\n    \n    if p_spatial > .75:\n        image = tf.image.transpose(image)\n        \n    # Rotates\n    if p_rotate > .75:\n        image = tf.image.rot90(image, k = 3) # rotate 270º\n    elif p_rotate > .5:\n        image = tf.image.rot90(image, k = 2) # rotate 180º\n    elif p_rotate > .25:\n        image = tf.image.rot90(image, k = 1) # rotate 90º\n        \n    # Pixel-level transforms\n    if p_pixel_1 >= .4:\n        image = tf.image.random_saturation(image, lower = .7, upper = 1.3)\n    if p_pixel_2 >= .4:\n        image = tf.image.random_contrast(image, lower = .8, upper = 1.2)\n    if p_pixel_3 >= .4:\n        image = tf.image.random_brightness(image, max_delta = .1)\n        \n    return image","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:16:23.355992Z","iopub.execute_input":"2024-05-29T15:16:23.356323Z","iopub.status.idle":"2024-05-29T15:16:23.367274Z","shell.execute_reply.started":"2024-05-29T15:16:23.356296Z","shell.execute_reply":"2024-05-29T15:16:23.366344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Data Generator","metadata":{}},{"cell_type":"code","source":"datagen = tf.keras.preprocessing.image.ImageDataGenerator(rescale = 1./255,\n                                                          samplewise_center = True,\n                                                          samplewise_std_normalization = True,\n                                                          validation_split = 0.2,\n                                                          preprocessing_function = data_augment)\n\ntrain_gen = datagen.flow_from_dataframe(dataframe = DF_TRAIN,\n                                        directory = TRAIN_PATH,\n                                        x_col = 'image_id',\n                                        y_col = 'label',\n                                        subset = 'training',\n                                        batch_size = BATCH_SIZE,\n                                        seed = 1,\n                                        color_mode = 'rgb',\n                                        shuffle = True,\n                                        class_mode = 'categorical',\n                                        target_size = (IMAGE_SIZE, IMAGE_SIZE))\n\nvalid_gen = datagen.flow_from_dataframe(dataframe = DF_TRAIN,\n                                        directory = TRAIN_PATH,\n                                        x_col = 'image_id',\n                                        y_col = 'label',\n                                        subset = 'validation',\n                                        batch_size = BATCH_SIZE,\n                                        seed = 1,\n                                        color_mode = 'rgb',\n                                        shuffle = False,\n                                        class_mode = 'categorical',\n                                        target_size = (IMAGE_SIZE, IMAGE_SIZE))\n\ntest_gen = datagen.flow_from_dataframe(dataframe = DF_TEST,\n                                       x_col = 'image_path',\n                                       y_col = None,\n                                       batch_size = BATCH_SIZE,\n                                       seed = 1,\n                                       color_mode = 'rgb',\n                                       shuffle = False,\n                                       class_mode = None,\n                                       target_size = (IMAGE_SIZE, IMAGE_SIZE))","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:25:40.588277Z","iopub.execute_input":"2024-05-29T15:25:40.588671Z","iopub.status.idle":"2024-05-29T15:26:03.433913Z","shell.execute_reply.started":"2024-05-29T15:25:40.588637Z","shell.execute_reply":"2024-05-29T15:26:03.433092Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"images = [train_gen[0][0][i] for i in range(16)]\nfig, axes = plt.subplots(3, 5, figsize = (10, 10))\n\naxes = axes.flatten()\n\nfor img, ax in zip(images, axes):\n    ax.imshow(img.reshape(IMAGE_SIZE, IMAGE_SIZE, 3))\n    ax.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:16:34.989449Z","iopub.status.idle":"2024-05-29T15:16:34.990172Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Building the Model","metadata":{}},{"cell_type":"code","source":"!pip install --quiet vit-keras\n\nfrom vit_keras import vit","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:16:44.846386Z","iopub.execute_input":"2024-05-29T15:16:44.846717Z","iopub.status.idle":"2024-05-29T15:16:51.724262Z","shell.execute_reply.started":"2024-05-29T15:16:44.846686Z","shell.execute_reply":"2024-05-29T15:16:51.723235Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 1. ViT B32 Model","metadata":{}},{"cell_type":"code","source":"vit_model = vit.vit_b32(\n        image_size = IMAGE_SIZE,\n        activation = 'softmax',\n        pretrained = True,\n        include_top = False,\n        pretrained_top = False,\n        classes = 5)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:16:51.726455Z","iopub.execute_input":"2024-05-29T15:16:51.726763Z","iopub.status.idle":"2024-05-29T15:16:54.548924Z","shell.execute_reply.started":"2024-05-29T15:16:51.726733Z","shell.execute_reply":"2024-05-29T15:16:54.548164Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Visualizing Attention Maps of Sample Test Image","metadata":{}},{"cell_type":"code","source":"from vit_keras import visualize\n\nx = test_gen.next()\nimage = x[0]\n\nattention_map = visualize.attention_map(model = vit_model, image = image)\n\n# Plot results\nfig, (ax1, ax2) = plt.subplots(ncols = 2)\nax1.axis('off')\nax2.axis('off')\nax1.set_title('Original')\nax2.set_title('Attention Map')\n_ = ax1.imshow(image)\n_ = ax2.imshow(attention_map)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:16:54.550139Z","iopub.execute_input":"2024-05-29T15:16:54.550400Z","iopub.status.idle":"2024-05-29T15:16:57.739774Z","shell.execute_reply.started":"2024-05-29T15:16:54.550374Z","shell.execute_reply":"2024-05-29T15:16:57.738789Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## 2. Fine-tuning the Model","metadata":{}},{"cell_type":"code","source":"model = tf.keras.Sequential([\n        vit_model,\n        tf.keras.layers.Flatten(),\n        tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.Dense(11, activation = tfa.activations.gelu),\n        tf.keras.layers.BatchNormalization(),\n        tf.keras.layers.Dense(5, 'softmax')\n    ],\n    name = 'vision_transformer')\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:30:55.348826Z","iopub.execute_input":"2024-05-29T15:30:55.349221Z","iopub.status.idle":"2024-05-29T15:30:56.754578Z","shell.execute_reply.started":"2024-05-29T15:30:55.349190Z","shell.execute_reply":"2024-05-29T15:30:56.753768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Training the Model","metadata":{}},{"cell_type":"code","source":"learning_rate = 1e-4\n\noptimizer = tfa.optimizers.RectifiedAdam(learning_rate = learning_rate)\n\nmodel.compile(optimizer = optimizer, \n              loss = tf.keras.losses.CategoricalCrossentropy(label_smoothing = 0.2), \n              metrics = ['accuracy'])\n\nSTEP_SIZE_TRAIN = train_gen.n // train_gen.batch_size\nSTEP_SIZE_VALID = valid_gen.n // valid_gen.batch_size\n\nreduce_lr = tf.keras.callbacks.ReduceLROnPlateau(monitor = 'val_accuracy',\n                                                 factor = 0.2,\n                                                 patience = 2,\n                                                 verbose = 1,\n                                                 min_delta = 1e-4,\n                                                 min_lr = 1e-6,\n                                                 mode = 'max')\n\nearlystopping = tf.keras.callbacks.EarlyStopping(monitor = 'val_accuracy',\n                                                 min_delta = 1e-4,\n                                                 patience = 5,\n                                                 mode = 'max',\n                                                 restore_best_weights = True,\n                                                 verbose = 1)\n\ncheckpointer = tf.keras.callbacks.ModelCheckpoint(filepath = './model.hdf5',\n                                                  monitor = 'val_accuracy', \n                                                  verbose = 1, \n                                                  save_best_only = True,\n                                                  save_weights_only = True,\n                                                  mode = 'max')\n\ncallbacks = [earlystopping, reduce_lr, checkpointer]\n\nmodel.fit(x = train_gen,\n          steps_per_epoch = STEP_SIZE_TRAIN,\n          validation_data = valid_gen,\n          validation_steps = STEP_SIZE_VALID,\n          epochs = EPOCHS,\n          callbacks = callbacks)","metadata":{"execution":{"iopub.status.busy":"2024-05-29T13:32:34.821307Z","iopub.execute_input":"2024-05-29T13:32:34.821684Z","iopub.status.idle":"2024-05-29T14:35:45.921899Z","shell.execute_reply.started":"2024-05-29T13:32:34.821646Z","shell.execute_reply":"2024-05-29T14:35:45.920250Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.save_weights('model.h5')\n#model.load_weights('model.h5')","metadata":{"execution":{"iopub.status.busy":"2024-05-29T14:39:44.100898Z","iopub.execute_input":"2024-05-29T14:39:44.101308Z","iopub.status.idle":"2024-05-29T14:39:44.665101Z","shell.execute_reply.started":"2024-05-29T14:39:44.101271Z","shell.execute_reply":"2024-05-29T14:39:44.664024Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:40:02.049610Z","iopub.execute_input":"2024-05-29T15:40:02.050045Z","iopub.status.idle":"2024-05-29T15:40:02.433487Z","shell.execute_reply.started":"2024-05-29T15:40:02.050009Z","shell.execute_reply":"2024-05-29T15:40:02.432482Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Results","metadata":{}},{"cell_type":"code","source":"predicted_classes = np.argmax(model.predict(valid_gen, steps = valid_gen.n // valid_gen.batch_size + 1), axis = 1)\ntrue_classes = valid_gen.classes\nclass_labels = list(valid_gen.class_indices.keys())  \n\nconfusionmatrix = confusion_matrix(true_classes, predicted_classes)\nplt.figure(figsize = (16, 16))\nsns.heatmap(confusionmatrix, cmap = 'Blues', annot = True, cbar = True)\n\nprint(classification_report(true_classes, predicted_classes))","metadata":{"execution":{"iopub.status.busy":"2024-05-29T15:40:04.418905Z","iopub.execute_input":"2024-05-29T15:40:04.419261Z","iopub.status.idle":"2024-05-29T15:41:23.258971Z","shell.execute_reply.started":"2024-05-29T15:40:04.419230Z","shell.execute_reply":"2024-05-29T15:41:23.257967Z"},"trusted":true},"execution_count":null,"outputs":[]}]}