{"metadata":{"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"},"colab":{"provenance":[],"collapsed_sections":["Qw7qc1lGyka3","IKJa6fTNy9-X","qrM5DPrVzCcJ"],"machine_shape":"hm","gpuType":"A100"},"accelerator":"GPU","kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":31011,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# CAT DOG PICTURE CLASSIFICATION\n\n## INTRODUCTION\n\nThis project aims 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,\" and our goal is to create a deep learning model that can accurately predict the label based on the content of each image. CNNs are highly effective for image classification tasks due to their ability to automatically learn hierarchical features from raw pixel data. The project will focus on data preprocessing, model development, evaluation, and prediction.\n\n## AIM\n\nThe aim of this project is to develop a CNN model capable of classifying images into two categories: cat and dog while achieving high accuracy and minimizing misclassification between the two categories. We will explore the performance of the model through metrics such as accuracy, precision, recall, and confusion matrices, providing insights into the effectiveness of CNNs in solving image classification tasks. By 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":{"id":"8w1V1OLswOo6"}},{"cell_type":"markdown","source":"### IMPORTS","metadata":{"id":"Qw7qc1lGyka3"}},{"cell_type":"code","source":"#pip install opencv-python","metadata":{"id":"kKDRAgkAyo6z"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"#!pip install scikit-learn","metadata":{"id":"v4HIIJd5yn1_"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"# !pip install --upgrade tensorflow","metadata":{"id":"dvv3eeRGymbw"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"import os\nimport random\nimport warnings\n\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nfrom PIL import Image\nimport re\nfrom sklearn.model_selection import train_test_split\n#from IPython.display import Image\n\nfrom keras.models import Sequential, Model, load_model\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout, Input, BatchNormalization, Reshape, GlobalAveragePooling2D,Activation\nfrom keras.regularizers import l2\nimport tensorflow as tf\nfrom tensorflow.keras.preprocessing import image\nfrom tensorflow.keras.preprocessing.image import ImageDataGenerator\nfrom tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau\nfrom tensorflow.keras.applications import EfficientNetB0\nfrom tensorflow.keras.applications.resnet50 import preprocess_input, decode_predictions\n\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)","metadata":{"id":"XEiNYUvgwNyL"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### READING DATA","metadata":{"id":"IKJa6fTNy9-X"}},{"cell_type":"code","source":"img_path= '/content/data/train'\n\nzip_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)\n\nimg_path = extract_path + \"/train\"\nlabel_list=[]\nimg_list=[]\n\nfor f in os.listdir(img_path):\n    label_list.append(f[:3])\n    img_list.append(img_path+'/'+f)\n\t","metadata":{"id":"a8uOIOviy5Gw"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### CREATING DATAFRAME","metadata":{"id":"qrM5DPrVzCcJ"}},{"cell_type":"code","source":"df = pd.DataFrame({'img':img_list,'label':label_list})\ndf.head()","metadata":{"id":"b-fu08Xty7P1","outputId":"7d9a75ab-1790-4760-bf17-db4f24c948ba"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### EDA","metadata":{"id":"pODuDeh3zyOw"}},{"cell_type":"code","source":"selected_images = df.groupby('label', as_index=False).apply(lambda x: x.sample(n=3, random_state=1)).reset_index(drop=True)\n\nsns.set(style='whitegrid')\nfig, axes = plt.subplots(2, 3, figsize=(5, 5))\n\naxes = axes.flatten()\n\nfor ax, (img_path, label) in zip(axes, zip(selected_images['img'], selected_images['label'])):\n    img = Image.open(img_path)\n    ax.imshow(img)\n    ax.axis('off')\n    ax.set_title(label, fontsize=14)\n\nplt.tight_layout()\nplt.show()","metadata":{"id":"JBhnT2_szfM8","outputId":"2e9b6ded-1c53-4857-e4e4-b677d8ec3162"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"label_values = df['label'].value_counts()\nplt.figure(figsize=(3, 3))\nplt.pie(label_values, labels=label_values.index, autopct='%1.1f%%', startangle=90, colors=['skyblue', 'lightcoral'])\nplt.show()","metadata":{"id":"rLOhgjmu1Gki","outputId":"c35a6a5e-d318-4ea6-eebc-df2b31b3dcd8"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"labelEncode = {'cat':0,'dog':1}\ndf['encoded_label'] = df['label'].map(labelEncode)","metadata":{"id":"15OunnyGz03O"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df.head()","metadata":{"id":"v-MikyOlz9l9","outputId":"4f007154-a5d1-403e-e6e2-d4f05acadd5e"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"### PREPARING TEST DATA","metadata":{"id":"H6V08sBD0DgA"}},{"cell_type":"code","source":"img_width, img_height = 170, 170","metadata":{"id":"weAn5b770HJ5"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x = []\ny = []\n\nfor img_path, label in zip(df['img'], df['encoded_label']):\n    img = cv2.imread(img_path)\n    if img is None:\n        continue\n\n    img = cv2.resize(img, (img_width, img_height))\n    img = img / 255.0\n    x.append(img)\n    y.append(label)","metadata":{"id":"JWqZxPbK0Jol"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x = np.array(x)\ny = np.array(y)","metadata":{"id":"52zZ7jRr0K_h"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_train,x_test,y_train,y_test = train_test_split(x,y,test_size=0.2,random_state=42)","metadata":{"id":"C6EXsB8M0MV_"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## CNN","metadata":{"id":"whi4JmAI2-PR"}},{"cell_type":"code","source":"model = Sequential()\nmodel.add(Input(shape=(img_width,img_height, 3)))\nmodel.add(Conv2D(64, 3, padding='same', activation='relu'))\nmodel.add(MaxPooling2D())\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(64, 3, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(MaxPooling2D())\nmodel.add(Conv2D(64, 3, padding='same', activation='relu'))\nmodel.add(MaxPooling2D())\n\nmodel.add(Conv2D(128, 3, padding='same', activation='relu'))\nmodel.add(BatchNormalization())\nmodel.add(Conv2D(128, 3, padding='same', activation='relu'))\nmodel.add(MaxPooling2D())\nmodel.add(Dropout(0.2))\n\nmodel.add(Conv2D(256, 3, padding='same', activation='relu'))\nmodel.add(MaxPooling2D())\nmodel.add(Dropout(0.2))\n\nmodel.add(Flatten())\n\nmodel.add(Dense(256, activation='relu'))\nmodel.add(Dense(2, activation='softmax'))\nmodel.compile(optimizer='adam', loss='sparse_categorical_crossentropy', metrics=['accuracy']);","metadata":{"id":"QZ1TpezR6gxG"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"early_stopping = EarlyStopping(monitor='val_loss', patience=3)\n\nhistory = model.fit(x_train, y_train, epochs=20, validation_data=(x_test, y_test), verbose=1, callbacks=[early_stopping])","metadata":{"id":"rJw6eI_N3Hdb","outputId":"1835b71a-05bd-4895-d773-78c4aa578867"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.summary()","metadata":{"id":"3AKOwpEV_bfb","outputId":"c4dca3ae-d109-40d6-b37b-d30a576c911b"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"history_df = pd.DataFrame(history.history)\nhistory_df","metadata":{"id":"CvsXZn7X_3TQ","outputId":"3beca340-edb8-454c-f461-61cf403bee40"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"ax = history_df[['accuracy','val_accuracy']].plot(title = \"Train and Validation Accuracies\" , marker='o')\nax.set(xlabel =\"Epochs\", ylabel = \"Accuracy\")\nplt.show()","metadata":{"id":"_mn1p82X_Vng","outputId":"b8b9d606-f69b-4166-b6c5-8162351d4758"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"model.save('Cat_Dog.keras')","metadata":{"id":"A52Rq4EB_JuC"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"img_size = (img_width, img_height)\ntest_images = df.sample(n=12)\n\nimages = []\npredicted_classes = []\nactual_classes = []\n\nfor index, row in test_images.iterrows():\n    img_path = row['img']\n    actual_class = row['encoded_label']\n    img = image.load_img(img_path, target_size=img_size)\n    img_array = image.img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)\n    img_array /= 255.0\n\n    predictions = model.predict(img_array)\n    predicted_class = np.argmax(predictions, axis=1)\n\n    images.append(img)\n    predicted_classes.append(predicted_class[0])\n    actual_classes.append(actual_class)\n\nclass_labels = {0: 'Cat', 1: 'Dog'}\n\nnum_images = len(images)\ncols = 3\nrows = (num_images // cols) + (num_images % cols > 0)\n\nplt.figure(figsize=(15, rows * 5))\nfor i in range(num_images):\n    plt.subplot(rows, cols, i + 1)\n    plt.imshow(images[i])\n    plt.title(f'Actual: {class_labels[actual_classes[i]]}\\nPredicted: {class_labels[predicted_classes[i]]}')\n    plt.axis('off')\n\nplt.tight_layout()\nplt.show()","metadata":{"id":"4BQJ8pv04l7M","outputId":"11da94b1-f653-48aa-9023-c005c2c54930"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# MODEL TESTING","metadata":{"id":"HeAMXhwJmwVp"}},{"cell_type":"markdown","source":"## READING TEST DATA","metadata":{"id":"KixLPMqcnXLr"}},{"cell_type":"code","source":"img_path= '/content/data/test1'\n\nzip_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)\n\nimg_path = extract_path + \"/test1\"\nid_list=[]\nimg_list=[]\n\nfor f in os.listdir(img_path):\n    match = re.search(r\"(\\d+)\", f)\n    if match:\n        id_list.append(int(match.group(1)))\n    img_list.append(img_path+'/'+f)\n\n","metadata":{"id":"D5tD6bqCm0zL"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"df_test = pd.DataFrame({'img':img_list,'id':id_list})\ndf_test.head()\n\ndf_test= df_test.sort_values(by='id', ascending=True)","metadata":{"id":"16515oUxnpBs","outputId":"271bf46f-56d9-4e7b-a0d8-49d3e63c0493"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"## PREDICT IMAGES","metadata":{"id":"JiYaelEVqCH7"}},{"cell_type":"code","source":"img_width, img_height = 170, 170","metadata":{"id":"c7cY_uU6qBdB"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x = []\n\nfor img_path in df_test['img']:\n    img = cv2.imread(img_path)\n    if img is None:\n        continue\n\n    img = cv2.resize(img, (img_width, img_height))\n    img = img / 255.0\n    x.append(img)","metadata":{"id":"xlMvqzHoqGqN"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"x_test = np.array(x)","metadata":{"id":"XPT_LlTdq4Rh"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"predictions=model.predict(x_test)\npredictions=predictions.argmax(axis=-1)\npredictions=np.array(predictions)","metadata":{"id":"ZZxYoWzbq7CB","outputId":"89d4fcd4-e7cd-4a80-9f71-967aed07d415"},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# SUBMIT MODEL","metadata":{"id":"6EG4YqXfmg2V"}},{"cell_type":"code","source":"submission=pd.DataFrame({\n    'id':df_test['id'],\n    'label':predictions\n})","metadata":{"id":"Cf2WRuBUmghB"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.head()","metadata":{"id":"I4w-RAuMq_Za","outputId":"b3595b0c-46c1-46a3-b9e4-cc64c383e1bd"},"outputs":[],"execution_count":null},{"cell_type":"code","source":"submission.to_csv('submission.csv',index=False)","metadata":{"id":"Rc0-cVl8rAqh"},"outputs":[],"execution_count":null}]}