{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.11.11","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":31040,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"markdown","source":"# Import Libraries","metadata":{}},{"cell_type":"code","source":"import os\nimport numpy as np\nfrom tqdm import tqdm\nfrom sklearn.svm import LinearSVC\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.metrics import accuracy_score, classification_report, confusion_matrix\nimport matplotlib.pyplot as plt\nimport seaborn as sns\nimport tensorflow as tf\nfrom tensorflow.keras.applications.vgg16 import VGG16, preprocess_input\nfrom tensorflow.keras.preprocessing.image import load_img, img_to_array\nfrom tensorflow.keras.models import Model\nimport zipfile\n","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","trusted":true,"execution":{"iopub.status.busy":"2025-07-16T18:54:43.786479Z","iopub.execute_input":"2025-07-16T18:54:43.786838Z","iopub.status.idle":"2025-07-16T18:55:02.294091Z","shell.execute_reply.started":"2025-07-16T18:54:43.786809Z","shell.execute_reply":"2025-07-16T18:55:02.293045Z"}},"outputs":[],"execution_count":null},{"cell_type":"code","source":"zip_path = \"/kaggle/input/dogs-vs-cats/train.zip\"\nextract_path = \"/kaggle/working/\"\n\nwith zipfile.ZipFile(zip_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_path)\n\ntrain_dir = \"/kaggle/working/train\"\n\nprint(f\" Extracted training images to: {extract_path}\")\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-16T18:55:02.295555Z","iopub.execute_input":"2025-07-16T18:55:02.296337Z","iopub.status.idle":"2025-07-16T18:55:12.774076Z","shell.execute_reply.started":"2025-07-16T18:55:02.296301Z","shell.execute_reply":"2025-07-16T18:55:12.773095Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 3. Load VGG16 Model\n","metadata":{}},{"cell_type":"code","source":"base_model = VGG16(weights=\"imagenet\", include_top=False, input_shape=(128, 128, 3))\nmodel = Model(inputs=base_model.input, outputs=base_model.output)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-16T18:55:12.775039Z","iopub.execute_input":"2025-07-16T18:55:12.775467Z","iopub.status.idle":"2025-07-16T18:55:13.760101Z","shell.execute_reply.started":"2025-07-16T18:55:12.775429Z","shell.execute_reply":"2025-07-16T18:55:13.759235Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 4. Feature Extraction using VGG16","metadata":{}},{"cell_type":"code","source":"def extract_features(image_path):\n    img = load_img(image_path, target_size=(128, 128))\n    img_array = img_to_array(img)\n    img_array = np.expand_dims(img_array, axis=0)\n    img_array = preprocess_input(img_array)\n    features = model.predict(img_array, verbose=0)\n    return features.flatten()\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-16T18:55:13.761730Z","iopub.execute_input":"2025-07-16T18:55:13.762913Z","iopub.status.idle":"2025-07-16T18:55:13.767852Z","shell.execute_reply.started":"2025-07-16T18:55:13.762872Z","shell.execute_reply":"2025-07-16T18:55:13.766841Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 5. Load Image Paths\n","metadata":{}},{"cell_type":"code","source":"cat_images = [os.path.join(train_dir, img) for img in os.listdir(train_dir) if img.startswith(\"cat\")]\ndog_images = [os.path.join(train_dir, img) for img in os.listdir(train_dir) if img.startswith(\"dog\")]\n\ncat_images = cat_images[:10000]\ndog_images = dog_images[:10000]\n\nimage_paths = cat_images + dog_images\nlabels = [0]*len(cat_images) + [1]*len(dog_images)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-16T18:55:13.768905Z","iopub.execute_input":"2025-07-16T18:55:13.769831Z","iopub.status.idle":"2025-07-16T18:55:13.844889Z","shell.execute_reply.started":"2025-07-16T18:55:13.769807Z","shell.execute_reply":"2025-07-16T18:55:13.844036Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#  6. Extract Features\n","metadata":{}},{"cell_type":"code","source":"X = []\nfor path in tqdm(image_paths, desc=\"🔍 Extracting features\"):\n    feat = extract_features(path)\n    X.append(feat)\n\nX = np.array(X)\ny = np.array(labels)\nprint(\" Features shape:\", X.shape)\n","metadata":{"trusted":true,"execution":{"iopub.status.busy":"2025-07-16T18:55:13.845778Z","iopub.execute_input":"2025-07-16T18:55:13.846047Z","execution_failed":"2025-07-16T19:08:43.386Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 7. Train-Test Split","metadata":{}},{"cell_type":"code","source":"X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\nprint(f\"🔀 Split: {X_train.shape[0]} train | {X_test.shape[0]} test\")\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-07-16T19:08:43.390Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"#  8. Train SVM\n","metadata":{}},{"cell_type":"code","source":"clf = LinearSVC(C=1.0, max_iter=2000)\nclf.fit(X_train, y_train)\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-07-16T19:08:43.392Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 9. Evaluate\n","metadata":{}},{"cell_type":"code","source":"y_pred = clf.predict(X_test)\naccuracy = accuracy_score(y_test, y_pred)\nprint(f\"\\n Accuracy: {accuracy*100:.2f}%\")\n\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-07-16T19:08:43.393Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 10. Classification Report","metadata":{}},{"cell_type":"code","source":"print(\"\\n Classification Report:\")\nprint(classification_report(y_test, y_pred, target_names=[\"Cat\", \"Dog\"]))","metadata":{"trusted":true,"execution":{"execution_failed":"2025-07-16T19:08:43.393Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# 11. Confusion Matrix","metadata":{}},{"cell_type":"code","source":"cm = confusion_matrix(y_test, y_pred)\nplt.figure(figsize=(6, 5))\nsns.heatmap(cm, annot=True, fmt='d', cmap='Blues', xticklabels=['Cat', 'Dog'], yticklabels=['Cat', 'Dog'])\nplt.title('Confusion Matrix')\nplt.xlabel('Predicted')\nplt.ylabel('Actual')\nplt.show()\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-07-16T19:08:43.394Z"}},"outputs":[],"execution_count":null},{"cell_type":"markdown","source":"# Save the Model","metadata":{}},{"cell_type":"code","source":"# Example for TensorFlow / Keras\nmodel.save('imageclassifier.h5')\n# OR for PyTorch\ntorch.save(model.state_dict(), 'imageclassifier.pth')\n","metadata":{"trusted":true,"execution":{"execution_failed":"2025-07-16T19:08:43.394Z"}},"outputs":[],"execution_count":null}]}