{"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":3362,"databundleVersionId":31148,"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-11T19:41:39.739362Z","iopub.execute_input":"2024-06-11T19:41:39.740348Z","iopub.status.idle":"2024-06-11T19:41:39.749627Z","shell.execute_reply.started":"2024-06-11T19:41:39.740313Z","shell.execute_reply":"2024-06-11T19:41:39.74838Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id='1'></a>\n<div class=\"alert alert-block\" style=\"background-color: pink\"><h2 style=\"text-align:center;color:black;\"> Data Description </h2> </div>\n\n\nThe training archive contains 25,000 images of dogs and cats. \n\nTrain your algorithm on these files and predict the labels for test1.zip.\n* **1 = dog**\n* **0 = cat**","metadata":{"execution":{"iopub.status.busy":"2024-06-11T19:42:20.079292Z","iopub.execute_input":"2024-06-11T19:42:20.079655Z","iopub.status.idle":"2024-06-11T19:42:20.088016Z","shell.execute_reply.started":"2024-06-11T19:42:20.079629Z","shell.execute_reply":"2024-06-11T19:42:20.086355Z"}}},{"cell_type":"markdown","source":"<a id='2'></a>\n<div class=\"alert alert-block\" style=\"background-color: pink\"><h2 style=\"text-align:center;color:black;\"> Libraries </h2> </div>","metadata":{}},{"cell_type":"code","source":"# Basic\nimport os\nfrom os import makedirs\nfrom os import listdir\nfrom shutil import copyfile\nfrom random import seed\nfrom random import random\nimport numpy as np\nimport pandas as pd\n\n# visuals\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom matplotlib.image import imread\nfrom PIL import Image\n\n# Scikit-learn\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import classification_report,confusion_matrix,ConfusionMatrixDisplay\n\n# Tensorflow\nimport tensorflow as tf\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.layers import Dense,MaxPooling2D,Dropout,Flatten,BatchNormalization,Conv2D\nfrom tensorflow.keras.callbacks import ReduceLROnPlateau,EarlyStopping","metadata":{"execution":{"iopub.status.busy":"2024-06-11T19:43:28.585161Z","iopub.execute_input":"2024-06-11T19:43:28.586249Z","iopub.status.idle":"2024-06-11T19:43:28.593869Z","shell.execute_reply.started":"2024-06-11T19:43:28.586211Z","shell.execute_reply":"2024-06-11T19:43:28.59254Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<a id='4'></a>\n<div class=\"alert alert-block\" style=\"background-color:pink\"><h2 style=\"text-align:center;color:black\"> Extract Data </h2> </div>","metadata":{"execution":{"iopub.status.busy":"2024-06-11T19:44:41.428023Z","iopub.execute_input":"2024-06-11T19:44:41.428439Z","iopub.status.idle":"2024-06-11T19:44:41.434996Z","shell.execute_reply.started":"2024-06-11T19:44:41.428409Z","shell.execute_reply":"2024-06-11T19:44:41.433589Z"}}},{"cell_type":"code","source":"train_path = \"../input/dogs-vs-cats/test1.zip\"\ntest_path = \"../input/dogs-vs-cats/train.zip\"\n\nfiles = \"/kaggle/working/\"\n\nimport zipfile\n\nwith zipfile.ZipFile(train_path, 'r') as zipp:\n    zipp.extractall(files)\n    \nwith zipfile.ZipFile(test_path, 'r') as zipp:\n    zipp.extractall(files)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T19:44:56.244894Z","iopub.execute_input":"2024-06-11T19:44:56.245287Z","iopub.status.idle":"2024-06-11T19:45:14.434844Z","shell.execute_reply.started":"2024-06-11T19:44:56.245257Z","shell.execute_reply":"2024-06-11T19:45:14.433622Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Load Images in a Dataframe\nimage_dir = \"../working/train/\"\n\nfilenames = os.listdir(image_dir)\nlabels = [x.split(\".\")[0] for x in filenames]\n\ndata = pd.DataFrame({\"filename\": filenames, \"label\": labels})\n\ndata.head()","metadata":{"execution":{"iopub.status.busy":"2024-06-11T19:47:17.347229Z","iopub.execute_input":"2024-06-11T19:47:17.348123Z","iopub.status.idle":"2024-06-11T19:47:17.393488Z","shell.execute_reply.started":"2024-06-11T19:47:17.348089Z","shell.execute_reply":"2024-06-11T19:47:17.392501Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-block\" style=\"background-color: pink\"><h2 style=\"text-align:center;color:black;\"> Explore Data </h2> </div>","metadata":{}},{"cell_type":"code","source":"# Visiualize some pics\n# Cats \nplt.figure(figsize=(20,20)) # specifying the overall grid size\nplt.subplots_adjust(hspace=0.4)\n\n\nfor i in range(10):\n    \n    plt.subplot(1,10,i+1)    # the number of images in the grid is 10*10 (100)\n    filename = 'train/' + 'dog.' + str(i) + '.jpg'\n    image = imread(filename)\n    plt.imshow(image)\n    plt.title('Dog',fontsize=12)\n    plt.axis('off')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-11T19:48:58.463038Z","iopub.execute_input":"2024-06-11T19:48:58.463463Z","iopub.status.idle":"2024-06-11T19:48:59.451255Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Dogs\nplt.figure(figsize=(20,20)) # specifying the overall grid size\nplt.subplots_adjust(hspace=0.4)\n\n\nfor i in range(10):\n    \n    plt.subplot(1,10,i+1)    # the number of images in the grid is 10*10 (100)\n    filename = 'train/' + 'cat.' + str(i) + '.jpg'\n    image = imread(filename)\n    plt.imshow(image)\n    plt.title('Cat',fontsize=12)\n    plt.axis('off')\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-11T19:49:06.611951Z","iopub.execute_input":"2024-06-11T19:49:06.612356Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-block\" style=\"background-color: pink\"><h2 style=\"text-align:center;color:black;\"> Split Train And Test </h2> </div>","metadata":{}},{"cell_type":"code","source":"# train test split using dataframe\n\nlabels = data['label']\n\nX_train, X_temp = train_test_split(data, test_size=0.2, stratify=labels, random_state = 42)\n\nlabel_test_val = X_temp['label']\n\nX_test, X_val = train_test_split(X_temp, test_size=0.5, stratify=label_test_val, random_state = 42)\n\nprint('The shape of train data',X_train.shape)\nprint('The shape of test data',X_test.shape)\nprint('The shape of validation data',X_val.shape)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T19:50:34.209641Z","iopub.execute_input":"2024-06-11T19:50:34.210528Z","iopub.status.idle":"2024-06-11T19:50:34.258687Z","shell.execute_reply.started":"2024-06-11T19:50:34.21049Z","shell.execute_reply":"2024-06-11T19:50:34.257446Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels = ['Cat','Dog']\n\nlabel1,count1 = np.unique(X_train.label,return_counts=True)\nlabel2,count2 = np.unique(X_val.label,return_counts=True)\nlabel3,count3 = np.unique(X_test.label,return_counts=True)\n\nuni1 = pd.DataFrame(data=count1,index=labels,columns=['Count1'])\nuni2 = pd.DataFrame(data=count2,index=labels,columns=['Count2'])\nuni3 = pd.DataFrame(data=count3,index=labels,columns=['Count3'])\n\n\nplt.figure(figsize=(20,6),dpi=200)\nsns.set_style('darkgrid')\n\nplt.subplot(131)\nsns.barplot(data=uni1,x=uni1.index,y='Count1',palette='icefire',width=0.2).set_title('Class distribution in Training set',fontsize=15)\nplt.xlabel('Labels',fontsize=12)\nplt.ylabel('Count',fontsize=12)\n\nplt.subplot(132)\nsns.barplot(data=uni2,x=uni2.index,y='Count2',palette='icefire',width=0.2).set_title('Class distribution in validation set',fontsize=15)\nplt.xlabel('Labels',fontsize=12)\nplt.ylabel('Count',fontsize=12)\n\n\nplt.subplot(133)\nsns.barplot(data=uni3,x=uni3.index,y='Count3',palette='icefire',width=0.2).set_title('Class distribution in Testing set',fontsize=15)\nplt.xlabel('Labels',fontsize=12)\nplt.ylabel('Count',fontsize=12)\n\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-11T19:58:10.145419Z","iopub.execute_input":"2024-06-11T19:58:10.146568Z","iopub.status.idle":"2024-06-11T19:58:10.998459Z","shell.execute_reply.started":"2024-06-11T19:58:10.14652Z","shell.execute_reply":"2024-06-11T19:58:10.997246Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# --- Use directories ---\n# create directories\ndataset_home = 'dataset_dogs_vs_cats/'\nsubdirs = ['train/', 'test/']\n\nfor subdir in subdirs:\n    # create label subdirectories\n    labeldirs = ['dogs/', 'cats/']\n    for labldir in labeldirs:\n        newdir = dataset_home + subdir + labldir\n        makedirs(newdir, exist_ok=True)\n# seed random number generator\nseed(1)\n# define ratio of pictures to use for validation\nval_ratio = 0.2\n# copy training dataset images into subdirectories\nsrc_directory = 'train/'\nfor file in listdir(src_directory):\n        src = src_directory + '/' + file\n        dst_dir = 'train/'\n        if random() < val_ratio:\n            dst_dir = 'test/'\n        if file.startswith('cat'):\n            dst = dataset_home + dst_dir + 'cats/' + file\n            copyfile(src, dst)\n        elif file.startswith('dog'):\n            dst = dataset_home + dst_dir + 'dogs/' + file\n            copyfile(src, dst)\n\n            \npath1 = \"/kaggle/working/dataset_dogs_vs_cats/train/cats\"\npath2 = \"/kaggle/working/dataset_dogs_vs_cats/train/dogs\"\npath3 = \"/kaggle/working/dataset_dogs_vs_cats/test/cats\"\npath4 = \"/kaggle/working/dataset_dogs_vs_cats/test/dogs\"\n\n\nprint('Then number of cat images in training data is' ,len(os.listdir(path1)))\nprint('Then number of dog images in training data is' ,len(os.listdir(path2)))\nprint('Then number of cat images in validation data is' ,len(os.listdir(path3)))\nprint('Then number of dog images in validation data is' ,len(os.listdir(path4)))\n","metadata":{"execution":{"iopub.status.busy":"2024-06-11T20:00:24.110862Z","iopub.execute_input":"2024-06-11T20:00:24.11165Z","iopub.status.idle":"2024-06-11T20:00:26.774271Z","shell.execute_reply.started":"2024-06-11T20:00:24.111617Z","shell.execute_reply":"2024-06-11T20:00:26.773156Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-block\" style=\"background-color: pink\"><h2 style=\"text-align:center;color:black;\"> Prepare Data </h2> </div>","metadata":{}},{"cell_type":"code","source":"# parameters\nimage_size = 128\nimage_channel = 3\nbat_size = 32","metadata":{"execution":{"iopub.status.busy":"2024-06-11T20:04:10.235721Z","iopub.execute_input":"2024-06-11T20:04:10.236126Z","iopub.status.idle":"2024-06-11T20:04:10.241473Z","shell.execute_reply.started":"2024-06-11T20:04:10.236096Z","shell.execute_reply":"2024-06-11T20:04:10.240217Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Creating image data generator\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n                                    rotation_range = 15,\n                                    horizontal_flip = True,\n                                    zoom_range = 0.2,\n                                    shear_range = 0.1,\n                                    fill_mode = 'reflect',\n                                    width_shift_range = 0.1,\n                                    height_shift_range = 0.1)\n\ntest_datagen = ImageDataGenerator(rescale=1./255)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T20:04:47.148217Z","iopub.execute_input":"2024-06-11T20:04:47.149057Z","iopub.status.idle":"2024-06-11T20:04:47.154882Z","shell.execute_reply.started":"2024-06-11T20:04:47.149017Z","shell.execute_reply":"2024-06-11T20:04:47.153582Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Applying image data gernerator to train and test data\n\ntrain_generator = train_datagen.flow_from_dataframe(X_train,\n                                                    directory = 'train/',\n                                                    x_col= 'filename',\n                                                    y_col= 'label',\n                                                    batch_size = bat_size,\n                                                    target_size = (image_size,image_size)\n                                                   )\nval_generator = test_datagen.flow_from_dataframe(X_val, \n                                                 directory = 'train/',\n                                                 x_col= 'filename',\n                                                 y_col= 'label',\n                                                 batch_size = bat_size,\n                                                 target_size = (image_size,image_size),\n                                                 shuffle=False\n                                                )\n\ntest_generator = test_datagen.flow_from_dataframe(X_test, \n                                                  directory = 'train/',\n                                                  x_col= 'filename',\n                                                  y_col= 'label',\n                                                  batch_size = bat_size,\n                                                  target_size = (image_size,image_size),\n                                                  shuffle=False\n                                                 )","metadata":{"execution":{"iopub.status.busy":"2024-06-11T20:05:08.236982Z","iopub.execute_input":"2024-06-11T20:05:08.237396Z","iopub.status.idle":"2024-06-11T20:05:08.512811Z","shell.execute_reply.started":"2024-06-11T20:05:08.237364Z","shell.execute_reply":"2024-06-11T20:05:08.511848Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Use Directory\ntrain_gen = train_datagen.flow_from_directory('/kaggle/working/dataset_dogs_vs_cats/train/', \n                                              class_mode='binary',\n                                              target_size = (image_size,image_size),\n                                              batch_size = bat_size,\n                                             )\n\nval_gen = test_datagen.flow_from_directory('/kaggle/working/dataset_dogs_vs_cats/test/', \n                                          class_mode='binary',\n                                          batch_size = bat_size,\n                                          target_size = (image_size,image_size),\n                                          shuffle = False\n                                         )","metadata":{"execution":{"iopub.status.busy":"2024-06-11T20:11:55.1692Z","iopub.execute_input":"2024-06-11T20:11:55.172115Z","iopub.status.idle":"2024-06-11T20:11:55.6756Z","shell.execute_reply.started":"2024-06-11T20:11:55.172026Z","shell.execute_reply":"2024-06-11T20:11:55.674214Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-block\" style=\"background-color: pink\"><h2 style=\"text-align:center;color:black;\"> Deep Learning Model </h2> </div>","metadata":{"execution":{"iopub.status.busy":"2024-06-11T20:12:21.617571Z","iopub.execute_input":"2024-06-11T20:12:21.61833Z","iopub.status.idle":"2024-06-11T20:12:21.627371Z","shell.execute_reply.started":"2024-06-11T20:12:21.618293Z","shell.execute_reply":"2024-06-11T20:12:21.625753Z"}}},{"cell_type":"markdown","source":"- The input layer consist of a Conv2D with 32 filters and activation relu.\n- The model contain the 3 blocks of convolution with increasing filters and activation relu.\n- Each convolution block contains Batch Noramlization, Max pooling (pool_size = 2) and Dropout (0.2).\n- The fully connected layers contain Flatten layer, Dense layer with 512 units and a Dropout layer.\n- The output layer is a Dense layer with 2 units and softmax activation.\n--------------------------------\n* **Input Layer:** Receives input images for classification.\n* **Convolutional Layers:** Extract features from the images through convolutional operations.\n* **Pooling Layers:** Reduce the spatial dimensions of the feature maps.\n* **Flatten Layer:** Convert the 2D feature maps into a 1D vector.\n* **Fully Connected Layers:** Perform classification using densely connected layers.\n* **Output Layer:** Provides the final prediction probabilities for cat and dog classes.","metadata":{}},{"cell_type":"code","source":"model = Sequential()\n\n# Input Layer\nmodel.add(Conv2D(32,(3,3),activation='relu',input_shape = (image_size,image_size,image_channel))) \nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.2))\n\n# Bloack 1 \nmodel.add(Conv2D(64,(3,3),activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.2))\n# Block 2\nmodel.add(Conv2D(128,(3,3),activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.2))\n# Block 3\nmodel.add(Conv2D(256,(3,3),activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\nmodel.add(Dropout(0.2))\n\n# Fully Connected layers \nmodel.add(Flatten())\nmodel.add(Dense(512,activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Dropout(0.2))\n\n# Output layer\nmodel.add(Dense(2,activation='softmax'))\n\nmodel.summary()","metadata":{"execution":{"iopub.status.busy":"2024-06-11T20:41:22.461343Z","iopub.execute_input":"2024-06-11T20:41:22.462386Z","iopub.status.idle":"2024-06-11T20:41:22.940737Z","shell.execute_reply.started":"2024-06-11T20:41:22.462346Z","shell.execute_reply":"2024-06-11T20:41:22.939727Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"### Callbacks ###\n# ReduceLROnPlateau : Reduce learning rate when a metric has stopped improving.\nlearning_rate_reduction = ReduceLROnPlateau(monitor = 'val_accuracy',\n                                            patience=2,\n                                            factor=0.5,\n                                            min_lr = 0.00001,\n                                            verbose = 1)\n# EarlyStopping : Stop training when a monitored metric has stopped improving.\nearly_stoping = EarlyStopping(monitor='val_loss',patience= 3,restore_best_weights=True,verbose=0)","metadata":{"execution":{"iopub.status.busy":"2024-06-11T20:47:56.13939Z","iopub.execute_input":"2024-06-11T20:47:56.140371Z","iopub.status.idle":"2024-06-11T20:47:56.145958Z","shell.execute_reply.started":"2024-06-11T20:47:56.140337Z","shell.execute_reply":"2024-06-11T20:47:56.144768Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-block\" style=\"background-color: pink\"><h2 style=\"text-align:center;color:black;\"> Compile the model </h2> </div>","metadata":{}},{"cell_type":"code","source":"model.compile(optimizer='adam',loss='binary_crossentropy',metrics=['accuracy'])","metadata":{"execution":{"iopub.status.busy":"2024-06-11T20:58:10.766532Z","iopub.execute_input":"2024-06-11T20:58:10.76707Z","iopub.status.idle":"2024-06-11T20:58:10.787813Z","shell.execute_reply.started":"2024-06-11T20:58:10.767037Z","shell.execute_reply":"2024-06-11T20:58:10.786679Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# fit the model\ncat_dog = model.fit(train_generator,\n                    validation_data = val_generator, \n                    callbacks=[early_stoping,learning_rate_reduction],\n                    epochs = 30,\n                    # steps_per_epoch = len(train_generator),\n                    # validation_steps = len(val_generaotor),\n                   )","metadata":{"execution":{"iopub.status.busy":"2024-06-11T21:24:57.924751Z","iopub.execute_input":"2024-06-11T21:24:57.925288Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-block\" style=\"background-color: pink\"><h2 style=\"text-align:center;color:black;\"> Results </h2> </div>","metadata":{}},{"cell_type":"code","source":"# plots for accuracy and Loss with epochs\n\nerror = pd.DataFrame(cat_dog.history)\n\nplt.figure(figsize=(18,5),dpi=200)\nsns.set_style('darkgrid')\n\nplt.subplot(121)\nplt.title('Cross Entropy Loss',fontsize=15)\nplt.xlabel('Epochs',fontsize=12)\nplt.ylabel('Loss',fontsize=12)\nplt.plot(error['loss'])\nplt.plot(error['val_loss'])\n\nplt.subplot(122)\nplt.title('Classification Accuracy',fontsize=15)\nplt.xlabel('Epochs',fontsize=12)\nplt.ylabel('Accuracy',fontsize=12)\nplt.plot(error['accuracy'])\nplt.plot(error['val_accuracy'])\n\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Evaluvate for train generator\nloss,acc = model.evaluate(train_generator,batch_size = bat_size, verbose = 0)\n\nprint('The accuracy of the model for training data is:',acc*100)\nprint('The Loss of the model for training data is:',loss)\n\n# Evaluvate for validation generator\nloss,acc = model.evaluate(val_generator,batch_size = bat_size, verbose = 0)\n\nprint('The accuracy of the model for validation data is:',acc*100)\nprint('The Loss of the model for validation data is:',loss)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"### Save The Model\n# model.save(\"model.h5\")\n\n# import tensorflow as tf\n# from tensorflow import keras\n# import numpy as np\n# tf.config.experimental.list_physical_devices()\n\n\n# # Load the Keras model\n# model = tf.keras.models.load_model('model.h5')\n\n# # Convert the model to TensorFlow Lite format\n# converter = tf.lite.TFLiteConverter.from_keras_model(model)\n# tflite_model = converter.convert()\n\n# # Save the TensorFlow Lite model to the /kaggle/working directory\n# tflite_model_path = '/kaggle/working/model.tflite'\n# with open(tflite_model_path, 'wb') as f:\n#     f.write(tflite_model)\n\n# print(f\"Model saved to {tflite_model_path}\")","metadata":{"execution":{"iopub.status.busy":"2024-06-11T21:10:15.444158Z","iopub.status.idle":"2024-06-11T21:10:15.44457Z","shell.execute_reply.started":"2024-06-11T21:10:15.444387Z","shell.execute_reply":"2024-06-11T21:10:15.444404Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-block\" style=\"background-color: pink\"><h2 style=\"text-align:center;color:black;\"> Prediction </h2> </div>","metadata":{}},{"cell_type":"code","source":"result = model.predict(test_generator,batch_size = bat_size,verbose = 0)\n\ny_pred = np.argmax(result, axis = 1)\n\ny_true = test_generator.labels\n\n# Evaluvate\nloss,acc = model.evaluate(test_generator, batch_size = bat_size, verbose = 0)\n\nprint('The accuracy of the model for testing data is:',acc*100)\nprint('The Loss of the model for testing data is:',loss)","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"labels =['Cat','Dog']\nprint(classification_report(y_true, y_pred,target_names=labels))","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"confusion_mtx = confusion_matrix(y_true,y_pred) \n\nf,ax = plt.subplots(figsize = (8,4),dpi=200)\nsns.heatmap(confusion_mtx, annot=True, linewidths=0.1, cmap = \"gist_yarg_r\", linecolor=\"black\", fmt='.0f', ax=ax,cbar=False, xticklabels=labels, yticklabels=labels)\n\nplt.xlabel(\"Predicted Label\",fontsize=10)\nplt.ylabel(\"True Label\",fontsize=10)\nplt.title(\"Confusion Matrix\",fontsize=13)\n\nplt.show()","metadata":{},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"<div class=\"alert alert-block\" style=\"background-color: pink\"><h2 style=\"text-align:center;color:black;\"> Visualize </h2> </div>","metadata":{}},{"cell_type":"code","source":"fig, axes = plt.subplots(1, 10, figsize=(20, 4))\nfor idx in range(10):\n    image_path = os.path.join(test_dir, test_data.iloc[idx]['filename'])\n    image = Image.open(image_path)\n    axes[idx].imshow(image)\n    axes[idx].set_title(\"Label: \" + test_data.iloc[idx]['label'])\n    axes[idx].axis('off')\nplt.show()","metadata":{},"execution_count":null,"outputs":[]}]}