{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.12","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"}],"dockerImageVersionId":30887,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Dog vs Cat Prediction","metadata":{}},{"cell_type":"markdown","source":"# Introduction\n\nIn this project, we aim to build a Convolutional Neural Network (CNN) to classify images of cats and dogs. The dataset consists of images labeled as either \"cat\" or \"dog\", where each image contains a photo of either a cat or a dog. Our goal is to create a deep learning model that can accurately predict the label of an image based on its content.\n\nConvolutional Neural Networks (CNNs) have proven to be highly effective for image classification tasks due to their ability to automatically learn hierarchical features from the raw pixel data. By training the model on a dataset of labeled images, we can enable it to recognize patterns and features specific to each class.\n\nThis project will focus on the following steps:\n1. **Data Preprocessing**: Cleaning, resizing, and normalizing the images.\n2. **Model Development**: Designing and training a CNN model for image classification.\n3. **Model Evaluation**: Assessing the performance of the trained model using various evaluation metrics like accuracy, confusion matrix, etc.\n4. **Prediction**: Using the trained model to predict the class (cat or dog) of new, unseen images.\n\n## Aim\n\nThe aim of this project is to:\n1. Develop a CNN model capable of classifying images into two categories: **cat** and **dog**.\n2. Achieve high accuracy and minimize misclassification between the two categories.\n3. Explore the performance of the model through metrics such as accuracy, precision, recall, and confusion matrices.\n4. Provide insights into the effectiveness of CNNs in solving image classification tasks.\n\nBy the end of this project, we aim to have a functional image classification model that can distinguish between images of cats and dogs with a high level of accuracy.","metadata":{}},{"cell_type":"markdown","source":"## Requirements","metadata":{}},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom tensorflow.keras.datasets import cifar10\nimport cv2\nimport pandas as pd\nimport os\nimport re\nimport zipfile\nimport numpy as np\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten, Input, MaxPooling2D,Dropout,BatchNormalization,Reshape\nimport warnings\nwarnings.filterwarnings(\"ignore\")\nfrom sklearn.model_selection import train_test_split\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Conv2D, Flatten, Input, MaxPooling2D,Dropout,BatchNormalization,Reshape\nfrom sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nfrom sklearn.metrics import accuracy_score\nimport math\nfrom tensorflow.keras.models import load_model","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:45:28.49196Z","iopub.execute_input":"2025-02-19T16:45:28.492239Z","iopub.status.idle":"2025-02-19T16:45:28.497572Z","shell.execute_reply.started":"2025-02-19T16:45:28.492213Z","shell.execute_reply":"2025-02-19T16:45:28.496663Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Import Data","metadata":{}},{"cell_type":"code","source":"zip_path = \"/kaggle/input/dogs-vs-cats/train.zip\"\nextract_path = \"/kaggle/working/train\"\n\nwith zipfile.ZipFile(zip_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:22:11.702657Z","iopub.execute_input":"2025-02-19T16:22:11.702928Z","iopub.status.idle":"2025-02-19T16:22:21.018312Z","shell.execute_reply.started":"2025-02-19T16:22:11.702908Z","shell.execute_reply":"2025-02-19T16:22:21.017588Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"folder_path = extract_path + \"/train\"\nlabels=[]\nimg=[]\nfor f in os.listdir(folder_path):\n    labels.append(f[:3])\n    img.append(folder_path+'/'+f)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:27:51.822422Z","iopub.execute_input":"2025-02-19T16:27:51.822782Z","iopub.status.idle":"2025-02-19T16:27:51.851057Z","shell.execute_reply.started":"2025-02-19T16:27:51.822759Z","shell.execute_reply":"2025-02-19T16:27:51.850442Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df=pd.DataFrame({\n    'img':img,\n    'label':labels\n})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:29:10.73271Z","iopub.execute_input":"2025-02-19T16:29:10.733061Z","iopub.status.idle":"2025-02-19T16:29:10.741125Z","shell.execute_reply.started":"2025-02-19T16:29:10.733036Z","shell.execute_reply":"2025-02-19T16:29:10.740281Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## EDA (Exploratory Data Analysis)","metadata":{}},{"cell_type":"code","source":"df.sample(10)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:30:01.608803Z","iopub.execute_input":"2025-02-19T16:30:01.609117Z","iopub.status.idle":"2025-02-19T16:30:01.621371Z","shell.execute_reply.started":"2025-02-19T16:30:01.609097Z","shell.execute_reply":"2025-02-19T16:30:01.620581Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"sample_size = 10  \n\nimages = []\nfor label in labels[:sample_size]:  \n    img_path = df[df['label'] == label]['img'].iloc[0]\n    image = Image.open(img_path).resize((128, 128))  \n    images.append((image, label))\n\nimages_per_row = 5\nnum_rows = math.ceil(len(images) / images_per_row)\n\nplt.figure(figsize=(12, num_rows * 3)) \nfor i, (image, label) in enumerate(images):\n    plt.subplot(num_rows, images_per_row, i + 1) \n    plt.imshow(image)\n    plt.title(label)\n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T17:07:13.573621Z","iopub.execute_input":"2025-02-19T17:07:13.573904Z","iopub.status.idle":"2025-02-19T17:07:14.378836Z","shell.execute_reply.started":"2025-02-19T17:07:13.573883Z","shell.execute_reply":"2025-02-19T17:07:14.377944Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label_encoding={'dog':1,'cat':0}\ndf['label_encoding']=df['label'].map(label_encoding)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:31:05.504654Z","iopub.execute_input":"2025-02-19T16:31:05.504939Z","iopub.status.idle":"2025-02-19T16:31:05.513917Z","shell.execute_reply.started":"2025-02-19T16:31:05.504919Z","shell.execute_reply":"2025-02-19T16:31:05.513253Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.sample(5)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:31:10.672015Z","iopub.execute_input":"2025-02-19T16:31:10.672289Z","iopub.status.idle":"2025-02-19T16:31:10.683891Z","shell.execute_reply.started":"2025-02-19T16:31:10.672268Z","shell.execute_reply":"2025-02-19T16:31:10.683046Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.figure(figsize=(23,8))\nax=sns.countplot(x=df[\"label\"],palette=\"viridis\",order=df['label'].value_counts().index)\nfor p in ax.containers:\n    ax.bar_label(p, fontsize=12, color='black', padding=5)\nplt.xticks(rotation=90);","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:31:35.292568Z","iopub.execute_input":"2025-02-19T16:31:35.292872Z","iopub.status.idle":"2025-02-19T16:31:35.735046Z","shell.execute_reply.started":"2025-02-19T16:31:35.292847Z","shell.execute_reply":"2025-02-19T16:31:35.734232Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Preprocess Image","metadata":{}},{"cell_type":"code","source":"x=[]\nfor img in df['img']:\n    img=cv2.imread(img)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img=cv2.resize(img,(32,32))\n    img=img/255.0 \n    x.append(img)\nx=np.array(x)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:53:53.662803Z","iopub.execute_input":"2025-02-19T16:53:53.663082Z","iopub.status.idle":"2025-02-19T16:54:25.414991Z","shell.execute_reply.started":"2025-02-19T16:53:53.663062Z","shell.execute_reply":"2025-02-19T16:54:25.414265Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"y=df[[\"label_encoding\"]]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:54:25.416309Z","iopub.execute_input":"2025-02-19T16:54:25.416596Z","iopub.status.idle":"2025-02-19T16:54:25.42139Z","shell.execute_reply.started":"2025-02-19T16:54:25.416561Z","shell.execute_reply":"2025-02-19T16:54:25.420552Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x.shape,y.shape","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:54:25.422739Z","iopub.execute_input":"2025-02-19T16:54:25.422963Z","iopub.status.idle":"2025-02-19T16:54:25.435732Z","shell.execute_reply.started":"2025-02-19T16:54:25.422943Z","shell.execute_reply":"2025-02-19T16:54:25.434912Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Modelling","metadata":{}},{"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-02-19T16:54:25.43659Z","iopub.execute_input":"2025-02-19T16:54:25.43681Z","iopub.status.idle":"2025-02-19T16:54:25.6169Z","shell.execute_reply.started":"2025-02-19T16:54:25.436791Z","shell.execute_reply":"2025-02-19T16:54:25.61595Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model=Sequential()\nmodel.add(Input(shape=(32,32,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))\n\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))\n\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))\n\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))\n\nmodel.add(Conv2D(1024,kernel_size=(3,3),activation='relu',padding='same'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D(pool_size=(2,2)))\n\n\n\nmodel.add(Flatten())\n\nmodel.add(Dense(1024,activation='relu'))\nmodel.add(Dense(512,activation='relu'))\nmodel.add(Dense(256,activation='relu'))\nmodel.add(Dense(128,activation='relu'))\n\nmodel.add(Dropout(0.5))\nmodel.add(Dense(2,activation='softmax'))\n\nmodel.compile(optimizer='adam',loss='sparse_categorical_crossentropy',metrics=['accuracy'])","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:34:15.315723Z","iopub.execute_input":"2025-02-19T16:34:15.316038Z","iopub.status.idle":"2025-02-19T16:34:17.88267Z","shell.execute_reply.started":"2025-02-19T16:34:15.316Z","shell.execute_reply":"2025-02-19T16:34:17.881944Z"}},"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,verbose=1)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:34:35.789649Z","iopub.execute_input":"2025-02-19T16:34:35.78996Z","iopub.status.idle":"2025-02-19T16:40:27.337686Z","shell.execute_reply.started":"2025-02-19T16:34:35.789938Z","shell.execute_reply":"2025-02-19T16:40:27.336943Z"},"collapsed":true,"jupyter":{"outputs_hidden":true}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save(\"cnn_model.h5\")","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:40:27.338958Z","iopub.execute_input":"2025-02-19T16:40:27.339182Z","iopub.status.idle":"2025-02-19T16:40:27.564332Z","shell.execute_reply.started":"2025-02-19T16:40:27.339163Z","shell.execute_reply":"2025-02-19T16:40:27.563644Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Modelling Overview","metadata":{}},{"cell_type":"code","source":"history.history['accuracy'][-1]","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:40:27.56557Z","iopub.execute_input":"2025-02-19T16:40:27.565862Z","iopub.status.idle":"2025-02-19T16:40:27.570785Z","shell.execute_reply.started":"2025-02-19T16:40:27.56584Z","shell.execute_reply":"2025-02-19T16:40:27.569973Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"plt.plot(history.history['accuracy'],label='Accuracy')\nplt.plot(history.history['val_accuracy'],label='Val_Accuracy')\nplt.legend();","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:40:27.571613Z","iopub.execute_input":"2025-02-19T16:40:27.571868Z","iopub.status.idle":"2025-02-19T16:40:27.751933Z","shell.execute_reply.started":"2025-02-19T16:40:27.571838Z","shell.execute_reply":"2025-02-19T16:40:27.751262Z"}},"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-02-19T16:55:54.579347Z","iopub.execute_input":"2025-02-19T16:55:54.579685Z","iopub.status.idle":"2025-02-19T16:55:55.18749Z","shell.execute_reply.started":"2025-02-19T16:55:54.579657Z","shell.execute_reply":"2025-02-19T16:55:55.186558Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"accuracy_score(predictions,y_test)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:56:00.225422Z","iopub.execute_input":"2025-02-19T16:56:00.225751Z","iopub.status.idle":"2025-02-19T16:56:00.23469Z","shell.execute_reply.started":"2025-02-19T16:56:00.225727Z","shell.execute_reply":"2025-02-19T16:56:00.233956Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"cm = confusion_matrix(y_test, predictions)\n\nlabel_name = ['Dog', 'Cat'] \n\nplt.figure(figsize=(10, 8))\nsns.heatmap(\n    cm,\n    annot=True,\n    fmt='g',\n    cmap='Blues',\n    xticklabels=label_name,\n    yticklabels=label_name,\n    cbar=False\n)\nplt.xlabel('Predicted Labels')\nplt.ylabel('Actual Labels')\nplt.title('Confusion Matrix');","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:57:13.80793Z","iopub.execute_input":"2025-02-19T16:57:13.808203Z","iopub.status.idle":"2025-02-19T16:57:13.927249Z","shell.execute_reply.started":"2025-02-19T16:57:13.808181Z","shell.execute_reply":"2025-02-19T16:57:13.926555Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"random_indices = np.random.choice(len(x_test), size=min(10, len(x_test)), replace=False)\n\nx_test_resized = x_test[random_indices]\ny_test_array = np.array(y_test)\nactual_labels = y_test_array[random_indices].flatten()\n\npredictions = model.predict(x_test_resized)\npredicted_labels = np.argmax(predictions, axis=1)\n\nplt.figure(figsize=(15, 8))\nfor i, idx in enumerate(random_indices):\n    plt.subplot(2, 5, i+1)\n    plt.imshow(x_test[idx])  \n    plt.title(f\"Actual: {labels[actual_labels[i]]}\\nPredicted: {labels[predicted_labels[i]]}\", fontsize=10)\n    plt.axis('off')  \nplt.tight_layout()\nplt.show()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T17:02:12.559976Z","iopub.execute_input":"2025-02-19T17:02:12.560318Z","iopub.status.idle":"2025-02-19T17:02:14.580603Z","shell.execute_reply.started":"2025-02-19T17:02:12.560291Z","shell.execute_reply":"2025-02-19T17:02:14.579749Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Testing the Model","metadata":{}},{"cell_type":"code","source":"zip_path = \"/kaggle/input/dogs-vs-cats/test1.zip\"\nextract_path = \"/kaggle/working/test1\"\n\nwith zipfile.ZipFile(zip_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_path)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:42:16.939447Z","iopub.execute_input":"2025-02-19T16:42:16.939744Z","iopub.status.idle":"2025-02-19T16:42:19.388756Z","shell.execute_reply.started":"2025-02-19T16:42:16.939722Z","shell.execute_reply":"2025-02-19T16:42:19.387675Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"folder_path = extract_path + \"/test1\"\nimg=[]\nids=[]\nfor f in os.listdir(folder_path):\n    img.append(folder_path+'/'+f)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:42:23.321196Z","iopub.execute_input":"2025-02-19T16:42:23.321544Z","iopub.status.idle":"2025-02-19T16:42:23.33394Z","shell.execute_reply.started":"2025-02-19T16:42:23.321509Z","shell.execute_reply":"2025-02-19T16:42:23.333337Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"folder_path = extract_path + \"/test1\"\nimg = []\nids = []\n\nfor f in os.listdir(folder_path):\n    img.append(folder_path + '/' + f)  \n\n    match = re.search(r\"(\\d+)\", f)  \n    if match:\n        ids.append(int(match.group(1)))","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:44:59.869706Z","iopub.execute_input":"2025-02-19T16:44:59.870016Z","iopub.status.idle":"2025-02-19T16:44:59.898548Z","shell.execute_reply.started":"2025-02-19T16:44:59.869994Z","shell.execute_reply":"2025-02-19T16:44:59.89787Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test=pd.DataFrame({\n    'id':ids,\n    'img':img\n})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:48:13.057582Z","iopub.execute_input":"2025-02-19T16:48:13.057903Z","iopub.status.idle":"2025-02-19T16:48:13.065905Z","shell.execute_reply.started":"2025-02-19T16:48:13.05788Z","shell.execute_reply":"2025-02-19T16:48:13.065236Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:48:18.719103Z","iopub.execute_input":"2025-02-19T16:48:18.719416Z","iopub.status.idle":"2025-02-19T16:48:18.727169Z","shell.execute_reply.started":"2025-02-19T16:48:18.71939Z","shell.execute_reply":"2025-02-19T16:48:18.726354Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test.info()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:48:30.381532Z","iopub.execute_input":"2025-02-19T16:48:30.38181Z","iopub.status.idle":"2025-02-19T16:48:30.395453Z","shell.execute_reply.started":"2025-02-19T16:48:30.38179Z","shell.execute_reply":"2025-02-19T16:48:30.394709Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test= df_test.sort_values(by='id', ascending=True)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:49:29.693542Z","iopub.execute_input":"2025-02-19T16:49:29.693841Z","iopub.status.idle":"2025-02-19T16:49:29.700062Z","shell.execute_reply.started":"2025-02-19T16:49:29.693816Z","shell.execute_reply":"2025-02-19T16:49:29.69923Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:49:36.706407Z","iopub.execute_input":"2025-02-19T16:49:36.706745Z","iopub.status.idle":"2025-02-19T16:49:36.714325Z","shell.execute_reply.started":"2025-02-19T16:49:36.706722Z","shell.execute_reply":"2025-02-19T16:49:36.713537Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_test=[]\nfor img in df_test['img']:\n    img=cv2.imread(img)\n    img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\n    img=cv2.resize(img,(32,32))\n    img=img/255.0 \n    x_test.append(img)\nx_test=np.array(x_test)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:51:31.048111Z","iopub.execute_input":"2025-02-19T16:51:31.048398Z","iopub.status.idle":"2025-02-19T16:51:47.26592Z","shell.execute_reply.started":"2025-02-19T16:51:31.048375Z","shell.execute_reply":"2025-02-19T16:51:47.265147Z"}},"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-02-19T16:51:47.267677Z","iopub.execute_input":"2025-02-19T16:51:47.26788Z","iopub.status.idle":"2025-02-19T16:51:49.606337Z","shell.execute_reply.started":"2025-02-19T16:51:47.267862Z","shell.execute_reply":"2025-02-19T16:51:49.605673Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission=pd.DataFrame({\n    'id':df_test['id'],\n    'label':predictions\n})","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:51:49.607598Z","iopub.execute_input":"2025-02-19T16:51:49.607826Z","iopub.status.idle":"2025-02-19T16:51:49.611812Z","shell.execute_reply.started":"2025-02-19T16:51:49.607806Z","shell.execute_reply":"2025-02-19T16:51:49.611069Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.head()","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:51:49.612715Z","iopub.execute_input":"2025-02-19T16:51:49.612997Z","iopub.status.idle":"2025-02-19T16:51:49.628269Z","shell.execute_reply.started":"2025-02-19T16:51:49.612977Z","shell.execute_reply":"2025-02-19T16:51:49.62765Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.to_csv('submission.csv',index=False)","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-02-19T16:52:05.833345Z","iopub.execute_input":"2025-02-19T16:52:05.833692Z","iopub.status.idle":"2025-02-19T16:52:05.850378Z","shell.execute_reply.started":"2025-02-19T16:52:05.833666Z","shell.execute_reply":"2025-02-19T16:52:05.849534Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## Conclusion\n\nIn this project, we successfully developed a Convolutional Neural Network (CNN) to classify images of cats and dogs. The model was trained on a labeled dataset and evaluated using multiple performance metrics.\n\nThe accuracy of our model on the test dataset was **85.02%**, indicating that the CNN performed well in distinguishing between the two categories. The confusion matrix provides additional insights into the model's classification performance:\n- **True Positives (Dog correctly classified as Dog)**: 2049\n- **True Negatives (Cat correctly classified as Cat)**: 2202\n- **False Positives (Dog misclassified as Cat)**: 418\n- **False Negatives (Cat misclassified as Dog)**: 331\n\nFrom the confusion matrix, we observe that while the model has a relatively high accuracy, there is still room for improvement, particularly in reducing the number of misclassifications. \n\n### Key Takeaways:\n1. **Effectiveness of CNNs**: The results demonstrate that CNNs are powerful for image classification, capturing key patterns and features from raw images.\n2. **Misclassification Analysis**: Some images were misclassified, which may be due to similarities in features or limitations in dataset quality and diversity.\n3. **Future Improvements**:\n   - **Data Augmentation**: Increasing the variability in training data to improve generalization.\n   - **Hyperparameter Tuning**: Experimenting with different architectures, learning rates, and regularization techniques.\n   - **Transfer Learning**: Leveraging pre-trained models like VGG16 or ResNet to enhance performance.\n\nOverall, our CNN model achieved a solid accuracy score, proving its capability in image classification tasks. Further enhancements can lead to even better performance and robustness in real-world applications.","metadata":{}}]}