{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.13","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"},{"sourceId":666612,"sourceType":"modelInstanceVersion","modelInstanceId":504596,"modelId":519560},{"sourceId":666672,"sourceType":"modelInstanceVersion","modelInstanceId":504644,"modelId":519613}],"dockerImageVersionId":31193,"isInternetEnabled":false,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# <div style=\"text-align: center;\">Cassava Leaf Disease Classification</div> \n<div style=\"text-align: center;\"><img src=\"https://www.shutterstock.com/image-vector/vector-illustration-about-cassava-leaves-600nw-2538964517.jpg\"width=400 style\"></div>\nIn this project, we will train a CNN model to classify cassava leaf diseases, enabling the identification and treatment of common conditions. The classes in the dataset are 'Cassava Bacterial Blight (CBB)', 'Cassava Brown Streak Disease (CBSD)', 'Cassava Green Mottle (CGM)', 'Cassava Mosaic Disease (CMD)', and 'Healthy'. The evaluation metric for this competition is classification accuracy.","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19"}},{"cell_type":"markdown","source":"## Importing Libraries","metadata":{}},{"cell_type":"code","source":"import pandas as pd\nimport numpy as np\nimport os\nimport cv2\nimport json\nfrom PIL import Image\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten, Input, MaxPooling2D,Dropout,BatchNormalization,Reshape\nfrom sklearn.model_selection import train_test_split\nfrom tensorflow.keras.callbacks import EarlyStopping\nimport warnings\nwarnings.filterwarnings('ignore')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:23:31.143849Z","iopub.execute_input":"2025-11-30T10:23:31.144448Z","iopub.status.idle":"2025-11-30T10:23:31.151569Z","shell.execute_reply.started":"2025-11-30T10:23:31.144421Z","shell.execute_reply":"2025-11-30T10:23:31.150963Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Reading Dataset","metadata":{}},{"cell_type":"code","source":"BASE_DIR = '/kaggle/input/cassava-leaf-disease-classification'\nTRAIN_IMG_DIR = os.path.join(BASE_DIR, 'train_images')\nTRAIN_CSV_PATH = os.path.join(BASE_DIR, 'train.csv')\nJSON_PATH = os.path.join(BASE_DIR, 'label_num_to_disease_map.json')","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:18:41.305546Z","iopub.execute_input":"2025-11-30T10:18:41.305911Z","iopub.status.idle":"2025-11-30T10:18:41.310012Z","shell.execute_reply.started":"2025-11-30T10:18:41.305895Z","shell.execute_reply":"2025-11-30T10:18:41.309218Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df = pd.read_csv(TRAIN_CSV_PATH)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:18:41.312511Z","iopub.execute_input":"2025-11-30T10:18:41.312761Z","iopub.status.idle":"2025-11-30T10:18:41.336162Z","shell.execute_reply.started":"2025-11-30T10:18:41.312744Z","shell.execute_reply":"2025-11-30T10:18:41.335648Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['image_id']='/kaggle/input/cassava-leaf-disease-classification/train_images/'+df['image_id']","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:18:41.336831Z","iopub.execute_input":"2025-11-30T10:18:41.337048Z","iopub.status.idle":"2025-11-30T10:18:41.344376Z","shell.execute_reply.started":"2025-11-30T10:18:41.337024Z","shell.execute_reply":"2025-11-30T10:18:41.343778Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"with open(JSON_PATH, 'r') as f:\n    label_map = json.load(f)\nlabel_map = {int(k): v for k, v in label_map.items()}","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:18:41.345164Z","iopub.execute_input":"2025-11-30T10:18:41.345531Z","iopub.status.idle":"2025-11-30T10:18:41.355980Z","shell.execute_reply.started":"2025-11-30T10:18:41.345503Z","shell.execute_reply":"2025-11-30T10:18:41.355151Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df['class_name'] = df['label'].map(label_map)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:18:41.356844Z","iopub.execute_input":"2025-11-30T10:18:41.357170Z","iopub.status.idle":"2025-11-30T10:18:41.363331Z","shell.execute_reply.started":"2025-11-30T10:18:41.357146Z","shell.execute_reply":"2025-11-30T10:18:41.362744Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:18:41.364114Z","iopub.execute_input":"2025-11-30T10:18:41.364388Z","iopub.status.idle":"2025-11-30T10:18:41.378144Z","shell.execute_reply.started":"2025-11-30T10:18:41.364364Z","shell.execute_reply":"2025-11-30T10:18:41.377385Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(8, 6))\nsns.countplot(x=df['class_name'], palette='Spectral')\nplt.xticks(rotation=45);","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:18:41.378810Z","iopub.execute_input":"2025-11-30T10:18:41.379094Z","iopub.status.idle":"2025-11-30T10:18:41.629672Z","shell.execute_reply.started":"2025-11-30T10:18:41.379075Z","shell.execute_reply":"2025-11-30T10:18:41.629109Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Data Processing","metadata":{}},{"cell_type":"code","source":"x = []\nfor img in df['image_id']:\n    img=cv2.imread(str(img))\n    if img is None:\n        print(f\"Resim yüklenemedi: {img}\") \n        continue\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img=cv2.resize(img, (128,128))\n    img=img / 255.0\n    x.append(img)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:18:41.630304Z","iopub.execute_input":"2025-11-30T10:18:41.630557Z","iopub.status.idle":"2025-11-30T10:20:26.422529Z","shell.execute_reply.started":"2025-11-30T10:18:41.630533Z","shell.execute_reply":"2025-11-30T10:20:26.421660Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x = np.array(x)","metadata":{"trusted":true},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y=df[[\"label\"]]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:20:26.423409Z","iopub.execute_input":"2025-11-30T10:20:26.424052Z","iopub.status.idle":"2025-11-30T10:20:26.428987Z","shell.execute_reply.started":"2025-11-30T10:20:26.424027Z","shell.execute_reply":"2025-11-30T10:20:26.428355Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_train,x_test,y_train,y_test=train_test_split(x,y,test_size=.2,random_state=42)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:22:40.702362Z","iopub.execute_input":"2025-11-30T10:22:40.703080Z","iopub.status.idle":"2025-11-30T10:22:41.179917Z","shell.execute_reply.started":"2025-11-30T10:22:40.703058Z","shell.execute_reply":"2025-11-30T10:22:41.179268Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Modelling","metadata":{}},{"cell_type":"code","source":"model=Sequential()\nmodel.add(Input(shape=(128,128,3)))\nmodel.add(Conv2D(64,kernel_size=(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(128,kernel_size=(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(256,kernel_size=(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(512,kernel_size=(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.25))\nmodel.add(Conv2D(1024,kernel_size=(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\nmodel.add(Flatten())\nmodel.add(Dense(1024,activation='relu'))\nmodel.add(Dense(512,activation='relu'))\nmodel.add(Dense(256,activation='relu'))\nmodel.add(Dense(128,activation='relu'))\nmodel.add(Dropout(0.5))\nmodel.add(Dense(5,activation='softmax'))\n\nmodel.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:22:49.478763Z","iopub.execute_input":"2025-11-30T10:22:49.479430Z","iopub.status.idle":"2025-11-30T10:22:51.605577Z","shell.execute_reply.started":"2025-11-30T10:22:49.479407Z","shell.execute_reply":"2025-11-30T10:22:51.604952Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"early_stop=EarlyStopping(monitor='val_loss',patience=20)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:23:37.047685Z","iopub.execute_input":"2025-11-30T10:23:37.048317Z","iopub.status.idle":"2025-11-30T10:23:37.051853Z","shell.execute_reply.started":"2025-11-30T10:23:37.048289Z","shell.execute_reply":"2025-11-30T10:23:37.050989Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history=model.fit(x_train,y_train,validation_data=(x_test,y_test),epochs=50,batch_size=36,\n                  callbacks=[early_stop],verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:23:41.305003Z","iopub.execute_input":"2025-11-30T10:23:41.306008Z","iopub.status.idle":"2025-11-30T10:39:24.772889Z","shell.execute_reply.started":"2025-11-30T10:23:41.305974Z","shell.execute_reply":"2025-11-30T10:39:24.772233Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save(\"cnn_leaf.h5\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:39:24.774635Z","iopub.execute_input":"2025-11-30T10:39:24.775114Z","iopub.status.idle":"2025-11-30T10:39:25.040373Z","shell.execute_reply.started":"2025-11-30T10:39:24.775096Z","shell.execute_reply":"2025-11-30T10:39:25.039758Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"image_path=\"/kaggle/input/cassava-leaf-disease-classification/test_images/\"\nimg_list=[]\nimg_id=[]\nfor img in os.listdir(image_path):\n    img_list.append(image_path+\"/\"+img)\n    img_id.append(img)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:39:25.041132Z","iopub.execute_input":"2025-11-30T10:39:25.041388Z","iopub.status.idle":"2025-11-30T10:39:25.054874Z","shell.execute_reply.started":"2025-11-30T10:39:25.041365Z","shell.execute_reply":"2025-11-30T10:39:25.054137Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test=pd.DataFrame({'img_id':img_id,'img_file':img_list})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:39:25.056736Z","iopub.execute_input":"2025-11-30T10:39:25.056927Z","iopub.status.idle":"2025-11-30T10:39:25.060796Z","shell.execute_reply.started":"2025-11-30T10:39:25.056914Z","shell.execute_reply":"2025-11-30T10:39:25.060268Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_test=[]\nfor img in df_test['img_file']:\n    img=cv2.imread(img)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img=cv2.resize(img,(128,128))\n    img=img/255.0 \n    x_test.append(img)\nx_test=np.array(x_test)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:39:25.061513Z","iopub.execute_input":"2025-11-30T10:39:25.061772Z","iopub.status.idle":"2025-11-30T10:39:25.085076Z","shell.execute_reply.started":"2025-11-30T10:39:25.061751Z","shell.execute_reply":"2025-11-30T10:39:25.084544Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_test = x_test.reshape((-1, 128,128, 3))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:39:25.085896Z","iopub.execute_input":"2025-11-30T10:39:25.086141Z","iopub.status.idle":"2025-11-30T10:39:25.089325Z","shell.execute_reply.started":"2025-11-30T10:39:25.086118Z","shell.execute_reply":"2025-11-30T10:39:25.088635Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions=model.predict(x_test)\npredictions=predictions.argmax(axis=-1)\npredictions=np.array(predictions)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:39:25.090092Z","iopub.execute_input":"2025-11-30T10:39:25.090394Z","iopub.status.idle":"2025-11-30T10:39:26.236518Z","shell.execute_reply.started":"2025-11-30T10:39:25.090378Z","shell.execute_reply":"2025-11-30T10:39:26.235900Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test['label']=predictions\ndf_test.to_csv('submission.csv',index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T10:39:26.237257Z","iopub.execute_input":"2025-11-30T10:39:26.237529Z","iopub.status.idle":"2025-11-30T10:39:26.246709Z","shell.execute_reply.started":"2025-11-30T10:39:26.237506Z","shell.execute_reply":"2025-11-30T10:39:26.246070Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test['label'] = predictions\n\nfinal_submission = df_test[['img_id', 'label']]\nfinal_submission.columns = ['image_id', 'label']  \n\nfinal_submission.to_csv('submission.csv', index=False)\n\nprint(final_submission.head())","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-11-30T11:51:27.384594Z","iopub.execute_input":"2025-11-30T11:51:27.385145Z","iopub.status.idle":"2025-11-30T11:51:27.395316Z","shell.execute_reply.started":"2025-11-30T11:51:27.385112Z","shell.execute_reply":"2025-11-30T11:51:27.394566Z"}},"outputs":[],"execution_count":null}]}