{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":13836,"databundleVersionId":1718836,"sourceType":"competition"}],"dockerImageVersionId":30733,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# This Python 3 environment comes with many helpful analytics libraries installed\n# It is defined by the kaggle/python Docker image: https://github.com/kaggle/docker-python\n# For example, here's several helpful packages to load\n\nimport numpy as np # linear algebra\nimport pandas as pd # data processing, CSV file I/O (e.g. pd.read_csv)\n\n# Input data files are available in the read-only \"../input/\" directory\n# For example, running this (by clicking run or pressing Shift+Enter) will list all files under the input directory\n\nimport os\nfor dirname, _, filenames in os.walk('/kaggle/input'):\n    for filename in filenames:\n#         print(os.path.join(dirname, filename))\n\n# You can write up to 20GB to the current directory (/kaggle/working/) that gets preserved as output when you create a version using \"Save & Run All\" \n# You can also write temporary files to /kaggle/temp/, but they won't be saved outside of the current session","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-06-15T08:53:13.222363Z","iopub.execute_input":"2024-06-15T08:53:13.222925Z","iopub.status.idle":"2024-06-15T08:53:13.229731Z","shell.execute_reply.started":"2024-06-15T08:53:13.222868Z","shell.execute_reply":"2024-06-15T08:53:13.228668Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df = pd.read_csv('/kaggle/input/cassava-leaf-disease-classification/train.csv')\ndf.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T08:53:15.890668Z","iopub.execute_input":"2024-06-15T08:53:15.89103Z","iopub.status.idle":"2024-06-15T08:53:15.940295Z","shell.execute_reply.started":"2024-06-15T08:53:15.890999Z","shell.execute_reply":"2024-06-15T08:53:15.93942Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.info()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T08:53:18.412713Z","iopub.execute_input":"2024-06-15T08:53:18.413599Z","iopub.status.idle":"2024-06-15T08:53:18.438093Z","shell.execute_reply.started":"2024-06-15T08:53:18.413558Z","shell.execute_reply":"2024-06-15T08:53:18.437227Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.columns = df.columns.str.strip()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T08:53:21.411209Z","iopub.execute_input":"2024-06-15T08:53:21.411903Z","iopub.status.idle":"2024-06-15T08:53:21.416379Z","shell.execute_reply.started":"2024-06-15T08:53:21.411864Z","shell.execute_reply":"2024-06-15T08:53:21.415404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.label.unique()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T08:53:23.635198Z","iopub.execute_input":"2024-06-15T08:53:23.635551Z","iopub.status.idle":"2024-06-15T08:53:23.643498Z","shell.execute_reply.started":"2024-06-15T08:53:23.635524Z","shell.execute_reply":"2024-06-15T08:53:23.642686Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train = df.iloc[:20000,:]\ntest = df.iloc[20000:,:]","metadata":{"execution":{"iopub.status.busy":"2024-06-15T08:53:26.180871Z","iopub.execute_input":"2024-06-15T08:53:26.181541Z","iopub.status.idle":"2024-06-15T08:53:26.186021Z","shell.execute_reply.started":"2024-06-15T08:53:26.181509Z","shell.execute_reply":"2024-06-15T08:53:26.185077Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"execution":{"iopub.status.busy":"2024-06-15T08:38:13.901296Z","iopub.execute_input":"2024-06-15T08:38:13.901775Z","iopub.status.idle":"2024-06-15T08:38:13.909694Z","shell.execute_reply.started":"2024-06-15T08:38:13.901735Z","shell.execute_reply":"2024-06-15T08:38:13.908524Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Importing modules","metadata":{}},{"cell_type":"code","source":"import tensorflow as tf\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.utils import Sequence\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array\nfrom tensorflow.keras.models import Sequential,Model\nfrom tensorflow.keras.layers import Conv2D,MaxPooling2D,Flatten,Dense,BatchNormalization,Dropout\nfrom tensorflow.keras.applications import ResNet50","metadata":{"execution":{"iopub.status.busy":"2024-06-15T09:26:25.446433Z","iopub.execute_input":"2024-06-15T09:26:25.447212Z","iopub.status.idle":"2024-06-15T09:26:25.452673Z","shell.execute_reply.started":"2024-06-15T09:26:25.447174Z","shell.execute_reply":"2024-06-15T09:26:25.451754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Load Dataset","metadata":{}},{"cell_type":"code","source":"class CustomDataGenerator(Sequence):\n    def __init__(self, dataframe, image_dir, image_id_col, label_col, batch_size, image_size, shuffle=True):\n        self.dataframe = dataframe\n        self.image_dir = image_dir\n        self.image_id_col = image_id_col\n        self.label_col = label_col\n        self.batch_size = batch_size\n        self.image_size = image_size\n        self.shuffle = shuffle\n        self.indices = np.arange(len(self.dataframe))\n        self.on_epoch_end()\n\n    def __len__(self):\n        return int(np.floor(len(self.dataframe) / self.batch_size))\n\n    def __getitem__(self, index):\n        indices = self.indices[index * self.batch_size:(index + 1) * self.batch_size]\n        batch_samples = [self.dataframe.iloc[k] for k in indices]\n        X, y = self.__data_generation(batch_samples)\n        return X, y\n\n    def on_epoch_end(self):\n        if self.shuffle:\n            np.random.shuffle(self.indices)\n\n    def __data_generation(self, batch_samples):\n        X = np.empty((self.batch_size, *self.image_size, 3), dtype=np.float32)\n        y = np.empty((self.batch_size), dtype=np.int32)\n\n        for i, sample in enumerate(batch_samples):\n            image_path = f\"{self.image_dir}/{sample[self.image_id_col]}\"\n            image = load_img(image_path, target_size=self.image_size)\n            image = img_to_array(image) / 255.0\n            X[i,] = image\n            y[i] = sample[self.label_col]\n\n        return X, y\n","metadata":{"execution":{"iopub.status.busy":"2024-06-15T08:54:04.477087Z","iopub.execute_input":"2024-06-15T08:54:04.477705Z","iopub.status.idle":"2024-06-15T08:54:04.488541Z","shell.execute_reply.started":"2024-06-15T08:54:04.47767Z","shell.execute_reply":"2024-06-15T08:54:04.487597Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Generating Dataset","metadata":{}},{"cell_type":"code","source":"folder = '/kaggle/input/cassava-leaf-disease-classification/train_images'\n\ntrain_datagen = CustomDataGenerator(train,folder,image_id_col='image_id',label_col='label',batch_size=32,image_size=(224,224))\ntest_datagen = CustomDataGenerator(test,folder,image_id_col='image_id',label_col='label',batch_size=32,image_size=(224,224))","metadata":{"execution":{"iopub.status.busy":"2024-06-15T08:54:07.024796Z","iopub.execute_input":"2024-06-15T08:54:07.025431Z","iopub.status.idle":"2024-06-15T08:54:07.031087Z","shell.execute_reply.started":"2024-06-15T08:54:07.025396Z","shell.execute_reply":"2024-06-15T08:54:07.030144Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Model Implementation","metadata":{}},{"cell_type":"markdown","source":"## Custom Model","metadata":{}},{"cell_type":"code","source":"model_1 = Sequential()\n\nmodel_1.add(Conv2D(64,(3,3),activation='elu',input_shape=(224,224,3)))\nmodel_1.add(Conv2D(64,(3,3),activation='elu'))\n\nmodel_1.add(Conv2D(64,(3,3),activation='elu'))\nmodel_1.add(MaxPooling2D(2,2))\n\nmodel_1.add(Conv2D(64,(3,3),activation='elu'))\nmodel_1.add(Conv2D(64,(3,3),activation='elu'))\nmodel_1.add(MaxPooling2D(2,2))\n\nmodel_1.add(Flatten())\nmodel_1.add(Dense(128,activation='elu'))\nmodel_1.add(Dropout(0.2))\n\nmodel_1.add(Dense(128,activation='elu'))\nmodel_1.add(Dropout(0.2))\n\nmodel_1.add(Dense(5,activation='softmax'))","metadata":{"execution":{"iopub.status.busy":"2024-06-15T08:54:12.495612Z","iopub.execute_input":"2024-06-15T08:54:12.495997Z","iopub.status.idle":"2024-06-15T08:54:12.627866Z","shell.execute_reply.started":"2024-06-15T08:54:12.495965Z","shell.execute_reply":"2024-06-15T08:54:12.627116Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_1.summary()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T08:54:16.255664Z","iopub.execute_input":"2024-06-15T08:54:16.256047Z","iopub.status.idle":"2024-06-15T08:54:16.284662Z","shell.execute_reply.started":"2024-06-15T08:54:16.256015Z","shell.execute_reply":"2024-06-15T08:54:16.283886Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"#### Model Compile","metadata":{}},{"cell_type":"markdown","source":"","metadata":{}},{"cell_type":"code","source":"model_1.compile(optimizer='adam',loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nh1 = model_1.fit(train_datagen,epochs=10,validation_data=test_datagen)","metadata":{"execution":{"iopub.status.busy":"2024-06-15T08:54:43.29089Z","iopub.execute_input":"2024-06-15T08:54:43.291635Z","iopub.status.idle":"2024-06-15T09:13:14.10662Z","shell.execute_reply.started":"2024-06-15T08:54:43.291602Z","shell.execute_reply":"2024-06-15T09:13:14.105811Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## Resnet Model","metadata":{}},{"cell_type":"code","source":"resnet = ResNet50(weights='imagenet',include_top=False,input_shape=(224,224,3))\nresnet.trainable = False\nx = resnet.output\nx = MaxPooling2D((2,2))(x)\nx = Flatten()(x)\n\nx = Dense(512,activation='elu')(x)\nx = Dropout(0.2)(x)\n\nprediction = Dense(5,activation='softmax')(x)","metadata":{"execution":{"iopub.status.busy":"2024-06-15T09:35:24.186883Z","iopub.execute_input":"2024-06-15T09:35:24.187266Z","iopub.status.idle":"2024-06-15T09:35:25.340713Z","shell.execute_reply.started":"2024-06-15T09:35:24.187237Z","shell.execute_reply":"2024-06-15T09:35:25.339739Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_2 = Model(inputs=resnet.input,outputs=prediction)","metadata":{"execution":{"iopub.status.busy":"2024-06-15T09:35:35.943793Z","iopub.execute_input":"2024-06-15T09:35:35.944708Z","iopub.status.idle":"2024-06-15T09:35:35.976518Z","shell.execute_reply.started":"2024-06-15T09:35:35.944674Z","shell.execute_reply":"2024-06-15T09:35:35.975651Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# model_2.summary()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T10:10:22.518322Z","iopub.execute_input":"2024-06-15T10:10:22.518716Z","iopub.status.idle":"2024-06-15T10:10:22.523343Z","shell.execute_reply.started":"2024-06-15T10:10:22.518681Z","shell.execute_reply":"2024-06-15T10:10:22.522466Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_2.compile(optimizer='adam',loss='sparse_categorical_crossentropy', metrics=['accuracy'])\nh2 = model_2.fit(train_datagen,epochs=10,validation_data=test_datagen)","metadata":{"execution":{"iopub.status.busy":"2024-06-15T09:35:47.516614Z","iopub.execute_input":"2024-06-15T09:35:47.517304Z","iopub.status.idle":"2024-06-15T09:58:30.930628Z","shell.execute_reply.started":"2024-06-15T09:35:47.517269Z","shell.execute_reply":"2024-06-15T09:58:30.929873Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Plot Graph","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt","metadata":{"execution":{"iopub.status.busy":"2024-06-15T10:02:21.215264Z","iopub.execute_input":"2024-06-15T10:02:21.215633Z","iopub.status.idle":"2024-06-15T10:02:21.220026Z","shell.execute_reply.started":"2024-06-15T10:02:21.215603Z","shell.execute_reply":"2024-06-15T10:02:21.219074Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### validation Loss","metadata":{}},{"cell_type":"code","source":"plt.plot(h1.history['loss'],color='red',label='train Custom model')\nplt.plot(h1.history['val_loss'],color='blue',label='validation custom model')\nplt.plot(h2.history['loss'],color='green',label='train Resnet')\nplt.plot(h2.history['val_loss'],color='orange',label='validation Resnet')\nplt.legend()\nplt.grid()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T10:06:34.854643Z","iopub.execute_input":"2024-06-15T10:06:34.855033Z","iopub.status.idle":"2024-06-15T10:06:35.05989Z","shell.execute_reply.started":"2024-06-15T10:06:34.855003Z","shell.execute_reply":"2024-06-15T10:06:35.059066Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Accuracy","metadata":{}},{"cell_type":"code","source":"plt.plot(h1.history['accuracy'],color='red',label='train Custom model')\nplt.plot(h1.history['val_accuracy'],color='blue',label='validation custom model')\nplt.plot(h2.history['accuracy'],color='green',label='train Resnet')\nplt.plot(h2.history['val_accuracy'],color='orange',label='validation Resnet')\nplt.legend()\nplt.grid()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T10:06:46.640145Z","iopub.execute_input":"2024-06-15T10:06:46.641007Z","iopub.status.idle":"2024-06-15T10:06:46.908906Z","shell.execute_reply.started":"2024-06-15T10:06:46.640973Z","shell.execute_reply":"2024-06-15T10:06:46.90801Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_2.save('resnet.h5')","metadata":{"execution":{"iopub.status.busy":"2024-06-15T10:07:55.244814Z","iopub.execute_input":"2024-06-15T10:07:55.245231Z","iopub.status.idle":"2024-06-15T10:07:55.802503Z","shell.execute_reply.started":"2024-06-15T10:07:55.2452Z","shell.execute_reply":"2024-06-15T10:07:55.801511Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}