{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.7.12","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"gpu","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30236,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"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":{"execution":{"iopub.status.busy":"2024-08-05T07:54:18.511664Z","iopub.execute_input":"2024-08-05T07:54:18.512375Z","iopub.status.idle":"2024-08-05T07:54:18.538162Z","shell.execute_reply.started":"2024-08-05T07:54:18.512295Z","shell.execute_reply":"2024-08-05T07:54:18.537290Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Dog and Cat Calssification - Accuracy - 54%","metadata":{}},{"cell_type":"code","source":"import os\nimport zipfile\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix\n\n# Unzip the dataset files\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats/train.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/train')\n    \nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats/test1.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/test')\n\n# Define paths to the dataset\nTRAIN_DIR = '/kaggle/working/train/train'\nTEST_DIR = '/kaggle/working/test/test1'\n\n# Function to load images and their labels\ndef load_images_labels(directory, limit=None):\n    images = []\n    labels = []\n    for idx, filename in enumerate(os.listdir(directory)):\n        if limit and idx >= limit:\n            break\n        label = 1 if 'dog' in filename else 0\n        img_path = os.path.join(directory, filename)\n        img = cv2.imread(img_path, cv2.IMREAD_COLOR)\n        img = cv2.resize(img, (64, 64))  # Resize to a smaller size for faster processing\n        images.append(img)\n        labels.append(label)\n    return np.array(images), np.array(labels)\n\n# Load training data\nX, y = load_images_labels(TRAIN_DIR, limit=2000)  # Limit to 2000 images for faster processing\n\n# EDA: Visualize the distribution of classes\nsns.countplot(y)\nplt.title('Distribution of Cats and Dogs')\nplt.xlabel('Class')\nplt.ylabel('Count')\nplt.xticks(ticks=[0, 1], labels=['Cat', 'Dog'])\nplt.show()\n\n# Show some sample images\ndef plot_samples(images, labels, n=10):\n    plt.figure(figsize=(20, 4))\n    for i in range(n):\n        ax = plt.subplot(2, n, i + 1)\n        # Convert to uint8 before displaying\n        img = images[i].astype('uint8')\n        plt.imshow(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))\n        plt.title(\"Dog\" if labels[i] == 1 else \"Cat\")\n        plt.axis(\"off\")\n\nplot_samples(X, y, n=10)\n\n# Flatten images for SVM\nX_flattened = X.reshape(X.shape[0], -1)\n\n# Split data into training and test sets\nX_train, X_test, y_train, y_test = train_test_split(X_flattened, y, test_size=0.2, random_state=42)\n\n# Standardize features\nscaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)\n\n# Train SVM classifier\nsvm = SVC(kernel='linear', C=1.0, random_state=42)\nsvm.fit(X_train, y_train)\n\n# Predict and evaluate\ny_pred = svm.predict(X_test)\naccuracy = accuracy_score(y_test, y_pred)\nprint(f'Accuracy: {accuracy * 100:.2f}%')\nprint(classification_report(y_test, y_pred, target_names=['Cat', 'Dog']))\n\n# Confusion Matrix\nconf_matrix = confusion_matrix(y_test, y_pred)\nsns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', xticklabels=['Cat', 'Dog'], yticklabels=['Cat', 'Dog'])\nplt.xlabel('Predicted')\nplt.ylabel('Actual')\nplt.title('Confusion Matrix')\nplt.show()\n\n# Visualize some predictions\nplot_samples(X_test.reshape(-1, 64, 64, 3)[:10], y_test[:10], n=10)\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-08-05T07:58:42.731908Z","iopub.execute_input":"2024-08-05T07:58:42.732607Z","iopub.status.idle":"2024-08-05T07:59:23.378233Z","shell.execute_reply.started":"2024-08-05T07:58:42.732570Z","shell.execute_reply":"2024-08-05T07:59:23.377353Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"markdown","source":"# Improve the Accuracy Using CNN (Accuracy : 71%)","metadata":{}},{"cell_type":"code","source":"import os\nimport zipfile\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix\nfrom tensorflow.keras.models import Sequential\nfrom tensorflow.keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\nfrom tensorflow.keras.utils import to_categorical\n\n# Unzip the dataset files\nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats/train.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/train')\n    \nwith zipfile.ZipFile('/kaggle/input/dogs-vs-cats/test1.zip', 'r') as zip_ref:\n    zip_ref.extractall('/kaggle/working/test')\n\n# Define paths to the dataset\nTRAIN_DIR = '/kaggle/working/train/train'\nTEST_DIR = '/kaggle/working/test/test1'\n\n# Function to load images and their labels\ndef load_images_labels(directory, limit=None):\n    images = []\n    labels = []\n    for idx, filename in enumerate(os.listdir(directory)):\n        if limit and idx >= limit:\n            break\n        label = 1 if 'dog' in filename else 0\n        img_path = os.path.join(directory, filename)\n        img = cv2.imread(img_path, cv2.IMREAD_COLOR)\n        img = cv2.resize(img, (64, 64))  # Resize to a smaller size for faster processing\n        images.append(img)\n        labels.append(label)\n    return np.array(images), np.array(labels)\n\n# Load training data\nX, y = load_images_labels(TRAIN_DIR, limit=2000)  # Limit to 2000 images for faster processing\n\n# Normalize the images\nX = X / 255.0\n\n# Convert labels to categorical\ny = to_categorical(y, 2)\n\n# Split data into training and test sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Build the CNN model\nmodel = Sequential([\n    Conv2D(32, (3, 3), activation='relu', input_shape=(64, 64, 3)),\n    MaxPooling2D((2, 2)),\n    Conv2D(64, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    Conv2D(128, (3, 3), activation='relu'),\n    MaxPooling2D((2, 2)),\n    Flatten(),\n    Dense(512, activation='relu'),\n    Dropout(0.5),\n    Dense(2, activation='softmax')\n])\n\n# Compile the model\nmodel.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n\n# Train the model\nhistory = model.fit(X_train, y_train, epochs=10, validation_data=(X_test, y_test), batch_size=32)\n\n# Evaluate the model\nloss, accuracy = model.evaluate(X_test, y_test)\nprint(f'Accuracy: {accuracy * 100:.2f}%')\n\n# Plot accuracy and loss over epochs\nplt.figure(figsize=(12, 4))\nplt.subplot(1, 2, 1)\nplt.plot(history.history['accuracy'], label='Train Accuracy')\nplt.plot(history.history['val_accuracy'], label='Validation Accuracy')\nplt.xlabel('Epochs')\nplt.ylabel('Accuracy')\nplt.legend()\nplt.title('Accuracy Over Epochs')\n\nplt.subplot(1, 2, 2)\nplt.plot(history.history['loss'], label='Train Loss')\nplt.plot(history.history['val_loss'], label='Validation Loss')\nplt.xlabel('Epochs')\nplt.ylabel('Loss')\nplt.legend()\nplt.title('Loss Over Epochs')\n\nplt.show()\n\n# Predict and evaluate\ny_pred = model.predict(X_test)\ny_pred_classes = np.argmax(y_pred, axis=1)\ny_true = np.argmax(y_test, axis=1)\n\nprint(classification_report(y_true, y_pred_classes, target_names=['Cat', 'Dog']))\n\n# Confusion Matrix\nconf_matrix = confusion_matrix(y_true, y_pred_classes)\nsns.heatmap(conf_matrix, annot=True, fmt='d', cmap='Blues', xticklabels=['Cat', 'Dog'], yticklabels=['Cat', 'Dog'])\nplt.xlabel('Predicted')\nplt.ylabel('Actual')\nplt.title('Confusion Matrix')\nplt.show()\n","metadata":{"execution":{"iopub.status.busy":"2024-08-05T08:01:29.556704Z","iopub.execute_input":"2024-08-05T08:01:29.557655Z","iopub.status.idle":"2024-08-05T08:02:05.457994Z","shell.execute_reply.started":"2024-08-05T08:01:29.557618Z","shell.execute_reply":"2024-08-05T08:02:05.456965Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"","metadata":{},"execution_count":null,"outputs":[]}]}