{"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 sys\nsys.path.append('/usr/local/lib/python3.7/site-packages')","metadata":{"execution":{"iopub.status.busy":"2023-09-18T13:53:19.881159Z","iopub.execute_input":"2023-09-18T13:53:19.883280Z","iopub.status.idle":"2023-09-18T13:53:19.893625Z","shell.execute_reply.started":"2023-09-18T13:53:19.883253Z","shell.execute_reply":"2023-09-18T13:53:19.892770Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install opencv-python","metadata":{"execution":{"iopub.status.busy":"2023-09-18T13:53:28.265734Z","iopub.execute_input":"2023-09-18T13:53:28.266281Z","iopub.status.idle":"2023-09-18T13:53:40.917875Z","shell.execute_reply.started":"2023-09-18T13:53:28.266194Z","shell.execute_reply":"2023-09-18T13:53:40.916673Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2","metadata":{"execution":{"iopub.status.busy":"2023-09-18T13:54:00.607148Z","iopub.execute_input":"2023-09-18T13:54:00.607540Z","iopub.status.idle":"2023-09-18T13:54:00.612469Z","shell.execute_reply.started":"2023-09-18T13:54:00.607508Z","shell.execute_reply":"2023-09-18T13:54:00.611369Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt \nimport seaborn as ans \nimport datetime\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.image import ImageDataGenerator\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.applications import ResNet50, DenseNet121, EfficientNetB0\nfrom keras.optimizers import Adam\nimport warnings\nwarnings.simplefilter (\"ignore\")\nimport os,cv2,json\nfrom PIL import Image","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:02:26.156826Z","iopub.execute_input":"2023-09-18T14:02:26.157215Z","iopub.status.idle":"2023-09-18T14:02:26.164592Z","shell.execute_reply.started":"2023-09-18T14:02:26.157182Z","shell.execute_reply":"2023-09-18T14:02:26.163666Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"WORK_DIR=\"/kaggle/input/cassava-leaf-disease-classification\"\nos.listdir (WORK_DIR)\n","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:02:33.961537Z","iopub.execute_input":"2023-09-18T14:02:33.962266Z","iopub.status.idle":"2023-09-18T14:02:33.968824Z","shell.execute_reply.started":"2023-09-18T14:02:33.962232Z","shell.execute_reply":"2023-09-18T14:02:33.967873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print('Train images: %d' %len (os.listdir ( os.path.join (WORK_DIR, \"train_images\"))))","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:02:38.253713Z","iopub.execute_input":"2023-09-18T14:02:38.254077Z","iopub.status.idle":"2023-09-18T14:02:38.270629Z","shell.execute_reply.started":"2023-09-18T14:02:38.254047Z","shell.execute_reply":"2023-09-18T14:02:38.269751Z"},"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 : print (json.dumps (json. loads (file.read()), indent=4))","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:02:41.119517Z","iopub.execute_input":"2023-09-18T14:02:41.120231Z","iopub.status.idle":"2023-09-18T14:02:41.126911Z","shell.execute_reply.started":"2023-09-18T14:02:41.120196Z","shell.execute_reply":"2023-09-18T14:02:41.125663Z"},"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":"2023-09-18T14:02:44.143414Z","iopub.execute_input":"2023-09-18T14:02:44.144704Z","iopub.status.idle":"2023-09-18T14:02:44.179972Z","shell.execute_reply.started":"2023-09-18T14:02:44.144657Z","shell.execute_reply":"2023-09-18T14:02:44.179079Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import seaborn as sns","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:02:47.702839Z","iopub.execute_input":"2023-09-18T14:02:47.703199Z","iopub.status.idle":"2023-09-18T14:02:47.708310Z","shell.execute_reply.started":"2023-09-18T14:02:47.703169Z","shell.execute_reply":"2023-09-18T14:02:47.707230Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sns.countplot (train_labels.label, edgecolor = 'black',palette = sns.color_palette (\"viridis\", 5))\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:02:50.280588Z","iopub.execute_input":"2023-09-18T14:02:50.280996Z","iopub.status.idle":"2023-09-18T14:02:50.486663Z","shell.execute_reply.started":"2023-09-18T14:02:50.280966Z","shell.execute_reply":"2023-09-18T14:02:50.485542Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nsample = train_labels [train_labels.label == 3].sample(6)\n\nplt.figure(figsize=(16, 8)) \nfor ind, (image_id, label) in enumerate (zip (sample.image_id,sample.label)):\n    plt.subplot(2, 3, ind + 1)\n    image = cv2.imread (os.path.join (WORK_DIR, \"train_images\", image_id) )\n    image = cv2.cvtColor (image, cv2.COLOR_BGR2RGB) \n    plt.imshow(image)\n    plt.axis (\"off\")\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:02:53.894629Z","iopub.execute_input":"2023-09-18T14:02:53.895003Z","iopub.status.idle":"2023-09-18T14:02:54.961198Z","shell.execute_reply.started":"2023-09-18T14:02:53.894975Z","shell.execute_reply":"2023-09-18T14:02:54.957187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"sample = train_labels [train_labels.label == 4].sample (6)\n\nplt.figure(figsize=(16, 8)) \nfor ind, (image_id, label) in enumerate (zip (sample.image_id, sample.label)):\n    plt.subplot (2, 3, ind+ 1)\n    image =cv2.imread(os.path.join(WORK_DIR, \"train_images\", image_id))\n    image =cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    plt.imshow(image) \n    plt.axis (\"off\")\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:02:59.771512Z","iopub.execute_input":"2023-09-18T14:02:59.771917Z","iopub.status.idle":"2023-09-18T14:03:00.797923Z","shell.execute_reply.started":"2023-09-18T14:02:59.771885Z","shell.execute_reply":"2023-09-18T14:03:00.797023Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"BATCH_SIZE= 16\n\nSTEPS_PER_EPOCH = len(train_labels) *0.8 / BATCH_SIZE\nVALIDATION_STEPS= len(train_labels) *0.2 / BATCH_SIZE\n\nEPOCHS= 20\nTARGET_SIZE = 224\ntrain_labels.label = train_labels.label.astype ('str')\ntrain_generator = ImageDataGenerator (validation_split = 0.2,\n                                      preprocessing_function = None,\n                                      zoom_range= 0.2,\n                                      cval = 0.2,\n                                      horizontal_flip = True,\n                                      vertical_flip = True,\n                                      fill_mode='nearest',\n                                      shear_range= 0.2,\n                                      height_shift_range = 0.2,\n                                      width_shift_range = 0.2) \\\n.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\")\nvalidation_generator = ImageDataGenerator (validation_split = 0.2)\\\n.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\")\n\ndef create_model():\n    model = models. Sequential()\n    model.add(EfficientNetB0 (include_top= False, weights = 'imagenet', input_shape = (TARGET_SIZE, TARGET_SIZE, 3)))\n    model.add(layers.GlobalAveragePooling2D())\n    model.add(layers.Dense (5, activation =\"softmax\"))\n    model.compile (optimizer = Adam (lr = 0.001),\n                   loss=\"sparse_categorical_crossentropy\",\n                   metrics =[\"acc\"])\n    return model\nmodel=create_model()\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-09-18T14:03:06.082717Z","iopub.execute_input":"2023-09-18T14:03:06.083075Z","iopub.status.idle":"2023-09-18T14:03:17.317084Z","shell.execute_reply.started":"2023-09-18T14:03:06.083047Z","shell.execute_reply":"2023-09-18T14:03:17.316019Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_save = ModelCheckpoint ('./best_baseline_model.h5',\n                              save_best_only = True,\n                              save_weights_only = True,\n                              monitor = 'val_loss',\n                              mode = 'min', verbose = 1)\n\nearly_stop = EarlyStopping (monitor = 'val_loss', min_delta = 0.001,\n                            patience = 5, mode = 'min', verbose = 1,\n                            restore_best_weights = True)\n\nreduce_lr = ReduceLROnPlateau (monitor = 'val_loss', factor = 0.3,\n                               patience=2, min_delta = 0.001,\n                               mode='min', verbose = 1)\n\nhistory = model.fit_generator (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\nacc =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, (axl, ax2) =plt.subplots(1, 2, figsize=(15, 5)) \nsns.set_style(\"white\") \nplt.suptitle('Train history', size = 15)\n \naxl.plot (epochs, acc, \"bo\", label = \"Training acc\")\naxl.plot (epochs, val_acc, \"b\", label = \"Validation acc\") \naxl.set_title(\"Training and validation acc\") \naxl.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":{"execution":{"iopub.status.busy":"2023-09-18T14:04:01.637448Z","iopub.execute_input":"2023-09-18T14:04:01.638365Z","iopub.status.idle":"2023-09-18T15:06:58.375447Z","shell.execute_reply.started":"2023-09-18T14:04:01.638329Z","shell.execute_reply":"2023-09-18T15:06:58.374509Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import numpy as np\n\nimport pandas as pd\n\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score\n\nimport tensorflow as tf\n\nfrom tensorflow.keras import models, layers\n\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator \nfrom keras.callbacks import ModelCheckpoint, EarlyStopping, ReduceLROnPlateau \nfrom tensorflow.keras.applications import ResNet50, DenseNet121, EfficientNetB0\nfrom keras.optimizers import Adam\n\n#ignoring warnings\nimport warnings\nwarnings.simplefilter(\"ignore\")\nimport os, cv2, json\nfrom PIL import Image\n\nTARGET_SIZE=224\n\ndef create_model():\n    model= models.Sequential()\n    model.add(EfficientNetB0(include_top=False, weights=None, input_shape =(TARGET_SIZE, TARGET_SIZE, 3)))\n    model.add(layers. GlobalAveragePooling2D())\n    model.add(layers.Dense(5, activation = \"softmax\"))\n    model.compile(optimizer= Adam(lr=0.001), loss=\"sparse_categorical_crossentropy\",metrics = [\"acc\"])\n    return model\n\nmodel=create_model() \nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2023-09-18T15:09:04.806053Z","iopub.execute_input":"2023-09-18T15:09:04.806455Z","iopub.status.idle":"2023-09-18T15:09:07.674067Z","shell.execute_reply.started":"2023-09-18T15:09:04.806424Z","shell.execute_reply":"2023-09-18T15:09:07.673085Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model.load_weights(r\"/kaggle/working/best_baseline_model.h5\")","metadata":{"execution":{"iopub.status.busy":"2023-09-18T15:09:28.496828Z","iopub.execute_input":"2023-09-18T15:09:28.497202Z","iopub.status.idle":"2023-09-18T15:09:28.739722Z","shell.execute_reply.started":"2023-09-18T15:09:28.497172Z","shell.execute_reply":"2023-09-18T15:09:28.738754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"image =Image.open(\"/kaggle/input/cassava-leaf-disease-classification/test_images/2216849948.jpg\")\nimage =image.resize((TARGET_SIZE, TARGET_SIZE)) \nimage= np.expand_dims(image, axis= 0) \npred= np.argmax(model.predict(image)) \nprint(model.predict(image))\n\nlabels={\n    \"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\"\n}","metadata":{"execution":{"iopub.status.busy":"2023-09-18T15:15:46.176696Z","iopub.execute_input":"2023-09-18T15:15:46.177063Z","iopub.status.idle":"2023-09-18T15:15:46.326639Z","shell.execute_reply.started":"2023-09-18T15:15:46.177033Z","shell.execute_reply":"2023-09-18T15:15:46.325198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(labels[str(pred)])","metadata":{"execution":{"iopub.status.busy":"2023-09-18T15:15:48.819660Z","iopub.execute_input":"2023-09-18T15:15:48.820027Z","iopub.status.idle":"2023-09-18T15:15:48.826036Z","shell.execute_reply.started":"2023-09-18T15:15:48.819998Z","shell.execute_reply":"2023-09-18T15:15:48.824944Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}