{"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":3362,"databundleVersionId":31148,"sourceType":"competition"},{"sourceId":5441,"databundleVersionId":38425,"sourceType":"competition"},{"sourceId":791828,"sourceType":"datasetVersion","datasetId":119698},{"sourceId":1003830,"sourceType":"datasetVersion","datasetId":550917}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"<div class=\"alert alert-block alert-info\"><h1 style=\"text-align:center;color:black\"> Dogs Vs Cats Classification Problem 📷 🚀 </h1> </div> \nThe Dogs & Cats is a foundational problem for a basic CNN(convolutional neural network) model which involves classifying images as a dog or a cat.The dataset can be used for learning how to develop,evaluate and use convolutional deep learning neural networks for classification of images. This includes how to develop a robust test harness for estimating the performance of the model, exploring improvements for the model by changing the paramters of the model, saving and loading the model to make predicitions on new data.\n\n![1_EvMbMNRHm_aOf1n4tDO1Xg.jpg](attachment:0e084368-1f23-4445-a9d6-d0bd7fb563a7.jpg)","metadata":{}},{"cell_type":"markdown","source":"![](http://images.app.goo.gl/29Wq1asdGB8UMKeb8)","metadata":{}},{"cell_type":"markdown","source":"<a id='1'></a>\n<div class=\"alert alert-block alert-danger\"><h2 style=\"text-align:center;color:black\"> Introduction 💥</h2> </div> \n\nIn this article, we will discover how to develop a CNN to classify images of dogs and cats.\n\nAfter reading this article, you will know :\n\n* How to load and prepare the images for training purpose.\n* How to split data for training and validation purpose.\n* How to apply Data Augmentation to the data.\n* How to develop a CNN model using keras and how to choose various parameters for improving performance of the model.\n* How to evaluate performance of our model.\n* How to save and load a model for further predictions.\n* How to draw the confusion matrix for trained model.","metadata":{}},{"cell_type":"markdown","source":"<a id='2'></a>\n<div class=\"alert alert-block alert-info\"><h2 style=\"text-align:center;color:black\"> Data Description </h2> </div>\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**\n","metadata":{}},{"cell_type":"markdown","source":"<a id='3'></a>\n<div class=\"alert alert-block alert-info\"><h2 style=\"text-align:center;color:black\"> Loading 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\nfrom keras.optimizers import Adam","metadata":{"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.805243Z","iopub.status.idle":"2025-07-10T09:34:18.805597Z","shell.execute_reply.started":"2025-07-10T09:34:18.805406Z","shell.execute_reply":"2025-07-10T09:34:18.805422Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='4'></a>\n<div class=\"alert alert-block alert-info\"><h2 style=\"text-align:center;color:black\"> Data Extraction </h2> </div>","metadata":{}},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.807191Z","iopub.status.idle":"2025-07-10T09:34:18.807538Z","shell.execute_reply.started":"2025-07-10T09:34:18.807336Z","shell.execute_reply":"2025-07-10T09:34:18.807353Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### Loading Images in a Dataframe","metadata":{}},{"cell_type":"code","source":"image_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":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.809147Z","iopub.status.idle":"2025-07-10T09:34:18.809463Z","shell.execute_reply.started":"2025-07-10T09:34:18.809334Z","shell.execute_reply":"2025-07-10T09:34:18.809348Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='5'></a>\n<div class=\"alert alert-block alert-info\"><h2 style=\"text-align:center;color:black\"> Data Exploration </h2> </div>","metadata":{}},{"cell_type":"markdown","source":"[](https://hoanghamobile.com/tin-tuc/wp-content/uploads/2024/04/anh-con-cho-51.jpg)First, we start by visualizing the variable of interest.\n\nLet's view more images in a grid format.\n\n<h5 style=\"text-align:center;color:Green\">We visualize few images of Dogs. </h5>","metadata":{}},{"cell_type":"markdown","source":"![](http://images.app.goo.gl/xYMLqpcXwp12TyNn8) </h2> </div>\n![](https://images.app.goo.gl/yk1hEHWeZnCATs7h6)","metadata":{}},{"cell_type":"code","source":"plt.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":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.810935Z","iopub.status.idle":"2025-07-10T09:34:18.81126Z","shell.execute_reply.started":"2025-07-10T09:34:18.811104Z","shell.execute_reply":"2025-07-10T09:34:18.811117Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<h5 style=\"text-align:center;color:Red\">We visualize few images of Cats. </h5> ","metadata":{}},{"cell_type":"markdown","source":"![](http://https://images.app.goo.gl/oHBQP3KQE6Yw5fC37)\n![](http://https://images.app.goo.gl/ZTQbAGu38U6kFkuk6)","metadata":{}},{"cell_type":"code","source":"plt.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":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.811796Z","iopub.status.idle":"2025-07-10T09:34:18.812022Z","shell.execute_reply.started":"2025-07-10T09:34:18.811913Z","shell.execute_reply":"2025-07-10T09:34:18.811924Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Images are of varying size.\n\nEvery time the cell is run different set of images will be displayed, one can scan the images of both categories. Presence of humans in some images could be a challenge for the model to classify.\n\nSome images have more than one cats or dogs respectively.","metadata":{}},{"cell_type":"markdown","source":"<a id='6'></a>\n<div class=\"alert alert-block alert-info\"><h2 style=\"text-align:center;color:black\"> Train Test Split </h2> </div>","metadata":{}},{"cell_type":"markdown","source":"<a id='7'></a>\n<div class=\"alert alert-block alert-warning\"><h4 style=\"text-align:center;color:black\"> Using Dataframe </h4> </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":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.813247Z","iopub.status.idle":"2025-07-10T09:34:18.813481Z","shell.execute_reply.started":"2025-07-10T09:34:18.813374Z","shell.execute_reply":"2025-07-10T09:34:18.813383Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Now we will Create a barplot to see the class distrubtion in trainting dataset.","metadata":{}},{"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":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.815206Z","iopub.status.idle":"2025-07-10T09:34:18.815537Z","shell.execute_reply.started":"2025-07-10T09:34:18.815345Z","shell.execute_reply":"2025-07-10T09:34:18.815362Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='8'></a>\n<div class=\"alert alert-block alert-warning\"><h4 style=\"text-align:center;color:black\"> Using Directory </h4> </div>","metadata":{}},{"cell_type":"code","source":"# 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":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:43:55.340687Z","iopub.execute_input":"2025-07-10T09:43:55.340991Z","iopub.status.idle":"2025-07-10T09:43:58.322517Z","shell.execute_reply.started":"2025-07-10T09:43:55.340966Z","shell.execute_reply":"2025-07-10T09:43:58.32173Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='9'></a>\n<div class=\"alert alert-block alert-info\"><h2 style=\"text-align:center;color:black\"> Data Preparation </h2> </div>\n\nfirstly, we will list out all the important parameters and respective values.","metadata":{}},{"cell_type":"code","source":"# parameters\nimage_size = 128\nimage_channel = 3\nbat_size = 256","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.817486Z","iopub.status.idle":"2025-07-10T09:34:18.817729Z","shell.execute_reply.started":"2025-07-10T09:34:18.817615Z","shell.execute_reply":"2025-07-10T09:34:18.817625Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='10'></a>\n<div class=\"alert alert-block alert-danger\"><h3 style=\"text-align:center;color:black\">Image Data Generator </h3> </div>\n\n* The data for will used by flow_from_dataframe and flow_from_directory.\n* The batch size is 32 and the image size is (128,128).\n","metadata":{}},{"cell_type":"code","source":"# Creating image data generator\ntrain_datagen = ImageDataGenerator(rescale=1./255,\n                                    fill_mode = 'reflect')\n\ntest_datagen = ImageDataGenerator(rescale=1./255)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.818839Z","iopub.status.idle":"2025-07-10T09:34:18.819211Z","shell.execute_reply.started":"2025-07-10T09:34:18.819008Z","shell.execute_reply":"2025-07-10T09:34:18.819023Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='11'></a>\n<div class=\"alert alert-block alert-warning\"><h4 style=\"text-align:center;color:black\"> Using Dataframe </h4> </div>","metadata":{}},{"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":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.821494Z","iopub.status.idle":"2025-07-10T09:34:18.821799Z","shell.execute_reply.started":"2025-07-10T09:34:18.821674Z","shell.execute_reply":"2025-07-10T09:34:18.821688Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='12'></a>\n<div class=\"alert alert-block alert-warning\"><h4 style=\"text-align:center;color:black\"> Using Directory </h4> </div>","metadata":{}},{"cell_type":"code","source":"train_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":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.823597Z","iopub.status.idle":"2025-07-10T09:34:18.824001Z","shell.execute_reply.started":"2025-07-10T09:34:18.823764Z","shell.execute_reply":"2025-07-10T09:34:18.823776Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='13'></a>\n<div class=\"alert alert-block alert-info\"><h2 style=\"text-align:center;color:black\"> Deep Learning Model </h2> </div>","metadata":{}},{"cell_type":"markdown","source":"<a id='14'></a>\n<div class=\"alert alert-block alert-danger\"><h3 style=\"text-align:center;color:black\">Model Layers </h3> </div>\n\n\n### Architecture\n\nThe architecture of the Cat vs Dog Image Classification model consists of the following Layers and components:\n\n#### Layers :\n* 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#### Components:\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(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n    \n# Block 1\nmodel.add(Conv2D(64, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n    \n# Block 2\nmodel.add(Conv2D(128, (3, 3), activation='relu'))\nmodel.add(MaxPooling2D(pool_size=(2, 2)))\nmodel.add(Dropout(0.25))\n    \n# Fully Connected layers\nmodel.add(Flatten())\nmodel.add(Dense(128, activation='relu'))\nmodel.add(Dropout(0.5))\n    \n# Output layer\nmodel.add(Dense(2,activation='softmax'))\n    \nmodel.summary()","metadata":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.824893Z","iopub.status.idle":"2025-07-10T09:34:18.825193Z","shell.execute_reply.started":"2025-07-10T09:34:18.825028Z","shell.execute_reply":"2025-07-10T09:34:18.825058Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='23'></a>\n<div class=\"alert alert-block alert-danger\"><h3 style=\"text-align:center;color:black\"> Compile the model </h3> </div>\nFinally we will compile the model .There are 3 things to mention here : Optimizer,Loss, Metrics\n\n* **Optimizer** :- To minimize cost function we use different methods For ex :- like gradient descent, stochastic gradient descent. So these are call optimizers. We are using a default one here which is adam.\n​\n* **Loss** :- To make our model better we either minimize loss or maximize accuracy. Neural Networks always minimize loss. To measure it we can use different formulas like 'categorical_crossentropy' or 'binary_crossentropy'. Here I have used binary_crossentropy.\n​\n* **Metrics** :- This is to denote the measure of your model. Can be accuracy or some other metric.","metadata":{}},{"cell_type":"code","source":"model.compile(optimizer=Adam(learning_rate=0.0001),loss='binary_crossentropy',metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:44:34.997533Z","iopub.execute_input":"2025-07-10T09:44:34.998246Z","iopub.status.idle":"2025-07-10T09:44:35.006008Z","shell.execute_reply.started":"2025-07-10T09:44:34.998219Z","shell.execute_reply":"2025-07-10T09:44:35.005516Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='16'></a>\n<div class=\"alert alert-block alert-danger\"><h3 style=\"text-align:center;color:black\"> Fit the model </h3> </div>\n\nWe are now going to train our compiled model using the train iterator (train_generator) and use the val iterator (val_generator) as a validation dataset during training.\n\nThe number of steps for the train and validation iterators must be specified. This is the number of batches that will comprise one epoch. This can be specified via the length of each iterator, and will be the total number of images in the train and validation directories divided by the batch size (32).\n\nThe model will be fit for 30 epochs.","metadata":{}},{"cell_type":"code","source":"cat_dog = model.fit(train_generator,\n                    validation_data = val_generator, \n                    epochs = 10)","metadata":{"_kg_hide-output":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.828735Z","iopub.status.idle":"2025-07-10T09:34:18.8291Z","shell.execute_reply.started":"2025-07-10T09:34:18.828906Z","shell.execute_reply":"2025-07-10T09:34:18.82892Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='17'></a>\n<div class=\"alert alert-block alert-danger\"><h3 style=\"text-align:center;color:black\"> Plot the results </h3> </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":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.83047Z","iopub.status.idle":"2025-07-10T09:34:18.830703Z","shell.execute_reply.started":"2025-07-10T09:34:18.830601Z","shell.execute_reply":"2025-07-10T09:34:18.83061Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='18'></a>\n<div class=\"alert alert-block alert-danger\"><h3 style=\"text-align:center;color:black\"> Evaluvation </h3> </div>\n\nwe will evaluvate the Training and validation data accuracy and loss.","metadata":{}},{"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":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.83196Z","iopub.status.idle":"2025-07-10T09:34:18.832272Z","shell.execute_reply.started":"2025-07-10T09:34:18.832139Z","shell.execute_reply":"2025-07-10T09:34:18.832153Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Finally, we will save the model for future use.","metadata":{}},{"cell_type":"code","source":"# Save the Model\nmodel.save(\"model.h5\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.833873Z","iopub.status.idle":"2025-07-10T09:34:18.834222Z","shell.execute_reply.started":"2025-07-10T09:34:18.834034Z","shell.execute_reply":"2025-07-10T09:34:18.834066Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='19'></a>\n<div class=\"alert alert-block alert-info\"><h2 style=\"text-align:center;color:black\"> Prediction </h2> </div>\n\nNow, we will predict the model on test dataset.","metadata":{}},{"cell_type":"code","source":"# prediction\nresult = 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":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.834847Z","iopub.status.idle":"2025-07-10T09:34:18.835215Z","shell.execute_reply.started":"2025-07-10T09:34:18.835009Z","shell.execute_reply":"2025-07-10T09:34:18.835024Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"Classification report","metadata":{}},{"cell_type":"code","source":"labels =['Cat','Dog']\nprint(classification_report(y_true, y_pred,target_names=labels))","metadata":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.837125Z","iopub.status.idle":"2025-07-10T09:34:18.837526Z","shell.execute_reply.started":"2025-07-10T09:34:18.837306Z","shell.execute_reply":"2025-07-10T09:34:18.837323Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"confusioin matrix","metadata":{}},{"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":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.838543Z","iopub.status.idle":"2025-07-10T09:34:18.838854Z","shell.execute_reply.started":"2025-07-10T09:34:18.838681Z","shell.execute_reply":"2025-07-10T09:34:18.838692Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='20'></a>\n<div class=\"alert alert-block alert-info\"><h2 style=\"text-align:center;color:black\"> submission </h2> </div>\nMake predictions on kaggle test data for submission.","metadata":{}},{"cell_type":"code","source":"size =(128,128)\n\n# loading into dataframe\ntest_dir = \"../working/test1/\"\nfilenames = os.listdir(test_dir)\ntest_data = pd.DataFrame({\"filename\": filenames})\ntest_data['label'] = 'unknown'\n\n# Create data genenerator for test data\ntest1_idg =  test_datagen.flow_from_dataframe(test_data, \n                                     \"test1/\", \n                                     x_col= \"filename\",\n                                     y_col = 'label',\n                                     batch_size = bat_size,\n                                     target_size=size, \n                                     shuffle = False)\n\n# Test Prediction\ntest1_predict = model.predict(test1_idg,verbose = 0)\n\ntest1_predict_argmax = np.argmax(test1_predict, axis=1)\n\ny_test_pred = test1_predict_argmax\n\ntest_data['label'] = y_test_pred\n\n# mapping\nlabel_mapping = {0: 'cat', 1: 'dog'}\ntest_data['label'] = test_data['label'].map(label_mapping)\ntest_data.head()\n\n# csv file output for submission\nsub = pd.read_csv('/kaggle/input/dogs-vs-cats/sampleSubmission.csv',index_col='id')\n\nsub['label'] = y_test_pred\n\nsub.to_csv('submission.csv',index=True)","metadata":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.84026Z","iopub.status.idle":"2025-07-10T09:34:18.840593Z","shell.execute_reply.started":"2025-07-10T09:34:18.840416Z","shell.execute_reply":"2025-07-10T09:34:18.84043Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"<a id='21'></a>\n<div class=\"alert alert-block alert-danger\"><h3 style=\"text-align:center;color:black\"> Visualize Classified Images  </h3> </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":{"_kg_hide-input":true,"trusted":true,"execution":{"iopub.status.busy":"2025-07-10T09:34:18.84185Z","iopub.status.idle":"2025-07-10T09:34:18.842316Z","shell.execute_reply.started":"2025-07-10T09:34:18.842018Z","shell.execute_reply":"2025-07-10T09:34:18.842032Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"After watching the images we can see the our model is quite accurate with 94% accuracy.","metadata":{}},{"cell_type":"markdown","source":"\n<a id='22'></a>\n<div class=\"alert alert-block alert-info\"><h2 style=\"text-align:center;color:black\"> Conclusion </h2> </div>\n\n\nWe successfully built a deep neural network model by implementing Convolutional Neural Network (CNN) to classify dog and cat images with very high accuracy 97.32 %. \n\nThe model was used to predict the classes of the images from the independent test set and results were submitted to test the accuracy of the prediction with fresh data.\n\nThe Cat vs Dog Image Classification model demonstrates the successful implementation of a Convolutional Neural Network for image classification tasks. By accurately distinguishing between images of cats and dogs, this project showcases the potential of deep learning algorithms in solving real-world problems involving image analysis. Through this project, we aim to inspire further exploration of CNNs and their applications in various domains,","metadata":{}}]}