{"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":"none","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":31089,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import os\nimport cv2\nimport numpy as np \nimport random\nimport matplotlib.pyplot as plt \nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import classification_report, accuracy_score\nfrom tqdm import tqdm\nimport zipfile, os\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    \nDATA_DIR = os.path.join(extract_path, \"train\")\n\nIMG_SIZE = 64\n\n# def load_data(data_dir, sample_size=2000):\n#     images = []\n#     labels = []\n\n#     files = os.listdir(data_dir)\n#     random.seed(42)   #random.seed(x) sets the starting point (or \"seed\") for the random number generator. So if you shuffle a list, or randomly sample data, setting the same seed will ensure you get the same result every time.\n#     random.shuffle(files)    #we shuffle because the first 12500 images are entirely of cats' and the next 12500 are of dogs', to get random 2000 we shuffle\n#     files = files[:sample_size]\n\n#     for file in tqdm(files):\n#         label = 1 if 'dog' in file else 0\n#         img_path = os.path.join(data_dir,file)\n#         img = cv2.imread(img_path)\n#         img = cv2.resize(img, (IMG_SIZE,IMG_SIZE))\n#         img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)        #grayscale image\n#         images.append(img.flatten())                       #flatten image to 1D\n#         labels.append(label)\n\n#     return np.array(images), np.array(labels)\n\ndef load_data(data_dir, sample_size=2000):\n    images = []\n    labels = []\n\n    files = os.listdir(data_dir)\n    random.seed(42)\n    random.shuffle(files)\n    files = files[:sample_size]\n\n    for file in tqdm(files):\n        img_path = os.path.join(data_dir, file)\n        label = 1 if 'dog' in file else 0\n\n        img = cv2.imread(img_path)\n        if img is None:\n            print(f\"Skipping unreadable file: {file}\")\n            continue\n\n        img = cv2.resize(img, (IMG_SIZE, IMG_SIZE))\n        img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n        images.append(img.flatten())\n        labels.append(label)\n\n    return np.array(images), np.array(labels)\n\n\nX,y =load_data(DATA_DIR, sample_size=2000)\n\nX_train,X_test, y_train, y_test = train_test_split(X,y,test_size=0.2,random_state=42,stratify=y)\n\nprint(\"Training SVM...\")\nclf=SVC(kernel='linear')\nclf.fit(X_train,y_train)\nprint(\"Training Completed!\")\n\ny_pred=clf.predict(X_test)\n\nprint(\"\\nClassification Report: \")\nprint(classification_report(y_test, y_pred))\n\nprint(\"Accuracy : \", accuracy_score(y_test,y_pred))\n\n# def show_predictions(X, y_true, y_pred, num=10, save_dir=\"visuals\"):\n#     for i in range(num):\n#         img = X[i].reshape(IMG_SIZE, IMG_SIZE)\n#         true_label = 'Dog' if y_true[i] == 1 else 'Cat'\n#         pred_label = 'Dog' if y_pred[i] == 1 else 'Cat'\n\n#         plt.imshow(img, cmap='gray')\n#         plt.title(f\"True: {true_label} | Pred: {pred_label}\")\n#         plt.axis('off')\n#         filename = f\"{save_dir}/sample_prediction_{i+1}.png\"    # Saving the image\n#         plt.savefig(filename, bbox_inches='tight')\n#         plt.show()    # Show the image\n#         plt.close()\n# show_predictions(X_test, y_test, y_pred, num=5)\n\n\n\n\n# Let's save the predictions in a grid format for a better visual representation\n# This function will create a grid of images with their true and predicted labels\ndef save_predictions_grid(X, y_true, y_pred, num=9, save_path=\"/kaggle/working/grid_predictions.png\"):\n    os.makedirs(os.path.dirname(save_path), exist_ok=True)\n\n    cols = 3\n    rows = (num + cols - 1) // cols  # auto-adjust rows\n\n    plt.figure(figsize=(cols * 3, rows * 3))\n\n    for i in range(num):\n        img = X[i].reshape(IMG_SIZE, IMG_SIZE)\n        true_label = 'Dog' if y_true[i] == 1 else 'Cat'\n        pred_label = 'Dog' if y_pred[i] == 1 else 'Cat'\n\n        plt.subplot(rows, cols, i + 1)\n        plt.imshow(img, cmap='gray')\n        plt.title(f\"True: {true_label}\\nPred: {pred_label}\")\n        plt.axis('off')\n\n    plt.tight_layout()\n    plt.savefig(save_path, bbox_inches='tight')\n    plt.show()  # Optional: display the grid\n    plt.close()\n\nsave_predictions_grid(X_test, y_test, y_pred, num=9)","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-07-08T15:34:48.751716Z","iopub.execute_input":"2025-07-08T15:34:48.752013Z","iopub.status.idle":"2025-07-08T15:35:12.789055Z","shell.execute_reply.started":"2025-07-08T15:34:48.751994Z","shell.execute_reply":"2025-07-08T15:35:12.787353Z"}},"outputs":[],"execution_count":null}]}