{"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":"none","dataSources":[{"sourceId":13836,"databundleVersionId":1718836,"sourceType":"competition"}],"dockerImageVersionId":30732,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"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-15T17:43:19.243727Z","iopub.execute_input":"2024-06-15T17:43:19.244588Z","iopub.status.idle":"2024-06-15T17:43:19.253469Z","shell.execute_reply.started":"2024-06-15T17:43:19.244555Z","shell.execute_reply":"2024-06-15T17:43:19.252139Z"},"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-15T17:43:24.102877Z","iopub.execute_input":"2024-06-15T17:43:24.103393Z","iopub.status.idle":"2024-06-15T17:43:24.161237Z","shell.execute_reply.started":"2024-06-15T17:43:24.10335Z","shell.execute_reply":"2024-06-15T17:43:24.160271Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.info()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T17:43:26.236289Z","iopub.execute_input":"2024-06-15T17:43:26.237117Z","iopub.status.idle":"2024-06-15T17:43:26.271303Z","shell.execute_reply.started":"2024-06-15T17:43:26.237087Z","shell.execute_reply":"2024-06-15T17:43:26.270368Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.columns = df.columns.str.strip()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T17:43:30.16076Z","iopub.execute_input":"2024-06-15T17:43:30.161763Z","iopub.status.idle":"2024-06-15T17:43:30.167399Z","shell.execute_reply.started":"2024-06-15T17:43:30.161732Z","shell.execute_reply":"2024-06-15T17:43:30.166118Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"df.label.unique()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T17:43:31.976668Z","iopub.execute_input":"2024-06-15T17:43:31.977124Z","iopub.status.idle":"2024-06-15T17:43:31.987219Z","shell.execute_reply.started":"2024-06-15T17:43:31.977086Z","shell.execute_reply":"2024-06-15T17:43:31.986173Z"},"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-15T17:43:33.801004Z","iopub.execute_input":"2024-06-15T17:43:33.801904Z","iopub.status.idle":"2024-06-15T17:43:33.806988Z","shell.execute_reply.started":"2024-06-15T17:43:33.801864Z","shell.execute_reply":"2024-06-15T17:43:33.805938Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"## import","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-15T17:43:39.623627Z","iopub.execute_input":"2024-06-15T17:43:39.624357Z","iopub.status.idle":"2024-06-15T17:43:58.078462Z","shell.execute_reply.started":"2024-06-15T17:43:39.624324Z","shell.execute_reply":"2024-06-15T17:43:58.077474Z"},"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        \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","metadata":{"execution":{"iopub.status.busy":"2024-06-15T17:44:03.783563Z","iopub.execute_input":"2024-06-15T17:44:03.784185Z","iopub.status.idle":"2024-06-15T17:44:03.795297Z","shell.execute_reply.started":"2024-06-15T17:44:03.784155Z","shell.execute_reply":"2024-06-15T17:44:03.794335Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:44:11.516217Z","iopub.execute_input":"2024-06-15T17:44:11.516696Z","iopub.status.idle":"2024-06-15T17:44:11.523203Z","shell.execute_reply.started":"2024-06-15T17:44:11.516665Z","shell.execute_reply":"2024-06-15T17:44:11.522004Z"},"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-15T17:44:16.126182Z","iopub.execute_input":"2024-06-15T17:44:16.126548Z","iopub.status.idle":"2024-06-15T17:44:17.336702Z","shell.execute_reply.started":"2024-06-15T17:44:16.12652Z","shell.execute_reply":"2024-06-15T17:44:17.335699Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_1.summary()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T17:44:22.305011Z","iopub.execute_input":"2024-06-15T17:44:22.305836Z","iopub.status.idle":"2024-06-15T17:44:22.334648Z","shell.execute_reply.started":"2024-06-15T17:44:22.305808Z","shell.execute_reply":"2024-06-15T17:44:22.333775Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T17:44:26.69042Z","iopub.execute_input":"2024-06-15T17:44:26.690747Z","iopub.status.idle":"2024-06-15T18:17:21.108741Z","shell.execute_reply.started":"2024-06-15T17:44:26.690724Z","shell.execute_reply":"2024-06-15T18:17:21.107843Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"### Resnet Mode","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-15T18:17:54.116943Z","iopub.execute_input":"2024-06-15T18:17:54.117337Z","iopub.status.idle":"2024-06-15T18:17:56.09319Z","shell.execute_reply.started":"2024-06-15T18:17:54.117309Z","shell.execute_reply":"2024-06-15T18:17:56.092416Z"},"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-15T18:18:03.171028Z","iopub.execute_input":"2024-06-15T18:18:03.171368Z","iopub.status.idle":"2024-06-15T18:18:03.201868Z","shell.execute_reply.started":"2024-06-15T18:18:03.171345Z","shell.execute_reply":"2024-06-15T18:18:03.201101Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"model_2.summary()","metadata":{"execution":{"iopub.status.busy":"2024-06-15T18:18:05.184531Z","iopub.execute_input":"2024-06-15T18:18:05.184885Z","iopub.status.idle":"2024-06-15T18:18:05.4348Z","shell.execute_reply.started":"2024-06-15T18:18:05.184859Z","shell.execute_reply":"2024-06-15T18:18:05.433996Z"},"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-15T18:18:17.506602Z","iopub.execute_input":"2024-06-15T18:18:17.507346Z","iopub.status.idle":"2024-06-15T18:36:23.767117Z","shell.execute_reply.started":"2024-06-15T18:18:17.507308Z","shell.execute_reply":"2024-06-15T18:36:23.766219Z"},"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-15T18:36:28.695448Z","iopub.execute_input":"2024-06-15T18:36:28.695819Z","iopub.status.idle":"2024-06-15T18:36:28.700246Z","shell.execute_reply.started":"2024-06-15T18:36:28.695792Z","shell.execute_reply":"2024-06-15T18:36:28.699355Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T18:36:36.139208Z","iopub.execute_input":"2024-06-15T18:36:36.139888Z","iopub.status.idle":"2024-06-15T18:36:36.473621Z","shell.execute_reply.started":"2024-06-15T18:36:36.139859Z","shell.execute_reply":"2024-06-15T18:36:36.472509Z"},"trusted":true},"execution_count":null,"outputs":[]},{"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-15T18:36:47.232597Z","iopub.execute_input":"2024-06-15T18:36:47.233445Z","iopub.status.idle":"2024-06-15T18:36:47.454581Z","shell.execute_reply.started":"2024-06-15T18:36:47.233414Z","shell.execute_reply":"2024-06-15T18:36:47.453613Z"},"trusted":true},"execution_count":null,"outputs":[]}]}