{"metadata":{"colab":{"provenance":[],"gpuType":"T4"},"kernelspec":{"name":"python3","display_name":"Python 3"},"language_info":{"name":"python"},"accelerator":"GPU","kaggle":{"accelerator":"none","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import numpy as np\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import classification_report, accuracy_score","metadata":{"id":"2Lx721HFR-bw"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!pip install opendatasets","metadata":{"id":"Av85bNYmTiXE","outputId":"23e4e8d7-ea35-4c6c-f6b3-67072043bfc9"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import opendatasets as od\nod.download(\n   \"https://www.kaggle.com/c/dogs-vs-cats/data\")","metadata":{"id":"dfrLJOcDTjIv","outputId":"34a5c5ae-4dd5-4aab-9aa9-c4d112ae9dd2"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import zipfile\nzip_files = ['test1.zip', 'train.zip']\n\nfor zip_file in zip_files:\n    with zipfile.ZipFile(f\"/content/dogs-vs-cats/{zip_file}\", \"r\") as z:\n        z.extractall(\".\")\n        print(f\"{zip_file} unzipped\")","metadata":{"id":"aPylvUEqKlhs","outputId":"6f8b0f33-6449-4843-fc7f-1564e2cbf64c"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import os\nimport pandas as pd\ndef list_files_in_directory(directory):\n    return [os.path.join(directory, filename) for filename in os.listdir(directory) if os.path.isfile(os.path.join(directory, filename))]\n\ntrain_image_paths = list_files_in_directory(\"/content/train\")\ntest_image_paths = list_files_in_directory(\"/content/test1\")\n\ntrain_df = pd.DataFrame({'image_path': train_image_paths})\ntest_df = pd.DataFrame({'image_path': test_image_paths})","metadata":{"id":"VUkpoptJTsYZ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(train_df.head())\nprint(test_df.head())","metadata":{"id":"44wDwPUTLqcL","outputId":"30e4e39c-f207-4b4b-afd5-77d561a49a0a"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAIN_DIR_PATH = './train'\nfile_names = os.listdir(TRAIN_DIR_PATH)\nprint('There are {} number of images in directory.'.format(len(file_names)))","metadata":{"execution":{"iopub.status.busy":"2024-04-05T13:07:53.075328Z","iopub.execute_input":"2024-04-05T13:07:53.075744Z","iopub.status.idle":"2024-04-05T13:07:53.096701Z","shell.execute_reply.started":"2024-04-05T13:07:53.075706Z","shell.execute_reply":"2024-04-05T13:07:53.09557Z"},"id":"MBAO9z5JCOEJ","outputId":"98893efe-aab5-4cfa-c729-b75b98853fcb","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"TRAIN_DIR_PATH = './test1'\nfile_names = os.listdir(TRAIN_DIR_PATH)\nprint('There are {} number of images in directory.'.format(len(file_names)))","metadata":{"execution":{"iopub.status.busy":"2024-04-05T13:07:53.097954Z","iopub.execute_input":"2024-04-05T13:07:53.098349Z","iopub.status.idle":"2024-04-05T13:07:53.175461Z","shell.execute_reply.started":"2024-04-05T13:07:53.098324Z","shell.execute_reply":"2024-04-05T13:07:53.174092Z"},"id":"fvL3wlXiCOEJ","outputId":"f2e7235e-b768-45a9-a96b-27b850c3d9e4","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"IMAGE_FOLDER_PATH = \"./train\"\nFILE_NAMES = os.listdir(IMAGE_FOLDER_PATH)","metadata":{"execution":{"iopub.status.busy":"2024-04-05T13:07:53.179975Z","iopub.execute_input":"2024-04-05T13:07:53.180342Z","iopub.status.idle":"2024-04-05T13:07:53.199375Z","shell.execute_reply.started":"2024-04-05T13:07:53.180311Z","shell.execute_reply":"2024-04-05T13:07:53.198348Z"},"id":"RZ-nELpLCOEJ","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"targets = list()\nfull_paths = list()\ntrain_cats_dir = list()\ntrain_dogs_dir = list()\n\nfor file_name in FILE_NAMES:\n    target = file_name.split(\".\")[0]\n    full_path = os.path.join(IMAGE_FOLDER_PATH, file_name)\n\n    if(target == \"dog\"):\n        train_dogs_dir.append(full_path)\n    if(target == \"cat\"):\n        train_cats_dir.append(full_path)\n\n    full_paths.append(full_path)\n    targets.append(target)\n\ndataset = pd.DataFrame()\ndataset['image_path'] = full_paths\ndataset['target'] = targets","metadata":{"execution":{"iopub.status.busy":"2024-04-05T13:07:53.200799Z","iopub.execute_input":"2024-04-05T13:07:53.201225Z","iopub.status.idle":"2024-04-05T13:07:53.268333Z","shell.execute_reply.started":"2024-04-05T13:07:53.201189Z","shell.execute_reply":"2024-04-05T13:07:53.267248Z"},"id":"qCfkPC7ICOEJ","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_cats_dir[:5]","metadata":{"execution":{"iopub.status.busy":"2024-04-05T13:07:53.270131Z","iopub.execute_input":"2024-04-05T13:07:53.270921Z","iopub.status.idle":"2024-04-05T13:07:53.278003Z","shell.execute_reply.started":"2024-04-05T13:07:53.270879Z","shell.execute_reply":"2024-04-05T13:07:53.276895Z"},"id":"u7W39sE-COEJ","outputId":"8ff26b18-a6b4-4794-a8ed-98be5f529b45","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"train_dogs_dir[:5]","metadata":{"execution":{"iopub.status.busy":"2024-04-05T13:07:53.279327Z","iopub.execute_input":"2024-04-05T13:07:53.279762Z","iopub.status.idle":"2024-04-05T13:07:53.289767Z","shell.execute_reply.started":"2024-04-05T13:07:53.279727Z","shell.execute_reply":"2024-04-05T13:07:53.288341Z"},"id":"j-wKXARWCOEJ","outputId":"a64f86dd-9678-4ce5-ac8d-098a290f4aa4","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset.head()","metadata":{"execution":{"iopub.status.busy":"2024-04-05T13:07:53.291359Z","iopub.execute_input":"2024-04-05T13:07:53.291923Z","iopub.status.idle":"2024-04-05T13:07:53.307429Z","shell.execute_reply.started":"2024-04-05T13:07:53.291882Z","shell.execute_reply":"2024-04-05T13:07:53.306059Z"},"id":"_rEYKsm6COEJ","outputId":"77df58d3-d7b1-4529-b815-2ba8b837055a","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"len(dataset)","metadata":{"execution":{"iopub.status.busy":"2024-04-05T13:07:53.30895Z","iopub.execute_input":"2024-04-05T13:07:53.309556Z","iopub.status.idle":"2024-04-05T13:07:53.318797Z","shell.execute_reply.started":"2024-04-05T13:07:53.309518Z","shell.execute_reply":"2024-04-05T13:07:53.317951Z"},"id":"O1ObYb8BCOEJ","outputId":"084b9780-b1f1-4d24-815b-f64aa091b765","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"total data counts:\", dataset['target'].count())\ncounts = dataset['target'].value_counts()\nprint(counts)","metadata":{"execution":{"iopub.status.busy":"2024-04-05T13:07:53.322431Z","iopub.execute_input":"2024-04-05T13:07:53.322789Z","iopub.status.idle":"2024-04-05T13:07:53.335171Z","shell.execute_reply.started":"2024-04-05T13:07:53.322753Z","shell.execute_reply":"2024-04-05T13:07:53.334058Z"},"id":"J37WNMEjCOEK","outputId":"959e528d-2b21-4399-f191-e7c74d3c59be","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport cv2","metadata":{"id":"1DevTLpkNyll"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def load_image_rgb(image_path):\n    image = cv2.imread(image_path)\n    image_rgb = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n    return image_rgb","metadata":{"id":"CZPLVSOMNxSe"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rows = 5\ncols = 5\naxes = []\nfig = plt.figure(figsize=(20, 10))\ni = 0\n\nfor a in range(rows * cols):\n    b = load_image_rgb(train_cats_dir[i])\n    axes.append(fig.add_subplot(rows, cols, a + 1))\n    plt.imshow(b)\n    plt.axis('off')\n    i += 1\n\nfig.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-05T13:07:53.336978Z","iopub.execute_input":"2024-04-05T13:07:53.337691Z","iopub.status.idle":"2024-04-05T13:07:57.506747Z","shell.execute_reply.started":"2024-04-05T13:07:53.33765Z","shell.execute_reply":"2024-04-05T13:07:57.504362Z"},"id":"XY0blWAPCOEK","outputId":"752fa257-182e-4d06-f073-3196775abdae","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"rows = 5\ncols = 5\naxes = []\nfig = plt.figure(figsize=(20, 10))\ni = 0\n\nfor a in range(rows * cols):\n    b = load_image_rgb(train_dogs_dir[i])\n    axes.append(fig.add_subplot(rows, cols, a + 1))\n    plt.imshow(b)\n    plt.axis('off')\n    i += 1\n\nfig.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-04-05T13:07:57.508559Z","iopub.execute_input":"2024-04-05T13:07:57.509127Z","iopub.status.idle":"2024-04-05T13:08:02.006612Z","shell.execute_reply.started":"2024-04-05T13:07:57.509093Z","shell.execute_reply":"2024-04-05T13:08:02.005448Z"},"id":"AWF52ZxvCOEK","outputId":"01374895-7812-4316-f925-b89c6cebac11","trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def preprocess_image(image_path, size=(64, 64)):\n    image = load_image_rgb(image_path)\n    image_resized = cv2.resize(image, size)\n    image_flattened = image_resized.flatten()\n    return image_flattened","metadata":{"id":"jbn9jcelSECJ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = []\ny = []\n\nfor index, row in dataset.iterrows():\n    image_path = row['image_path']\n    target = row['target']\n\n    image_features = preprocess_image(image_path)\n    X.append(image_features)\n    y.append(0 if target == 'cat' else 1)","metadata":{"id":"JErkSBe7SHAq"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"X = np.array(X)\ny = np.array(y)","metadata":{"id":"cAjIcz20SWml"},"execution_count":null,"outputs":[]},{"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":"_D_iSlNlSX7G"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"scaler = StandardScaler()\nX_train = scaler.fit_transform(X_train)\nX_test = scaler.transform(X_test)","metadata":{"id":"2ucSQzcxSZrO"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.decomposition import PCA\nfrom sklearn.pipeline import make_pipeline\nfrom sklearn.svm import SVC\nfrom sklearn.preprocessing import StandardScaler","metadata":{"id":"fymQVwMHas_L"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pca = PCA(n_components=100)\nscaler = StandardScaler()\nsvm_rbf = SVC(kernel='rbf', random_state=42)","metadata":{"id":"2ORkIxjta6WZ"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pipeline = make_pipeline(scaler, pca, svm_rbf)","metadata":{"id":"_JeuYty6a8bX"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pipeline.fit(X_train, y_train)","metadata":{"id":"cqwoGxH8a-VF","outputId":"b57882c2-7de3-4c48-c60b-4c8d36baf471"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"y_pred = pipeline.predict(X_test)","metadata":{"id":"DEJIWsuqShmX"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(\"Accuracy:\", accuracy_score(y_test, y_pred))\nprint(\"Classification Report:\\n\", classification_report(y_test, y_pred, target_names=['cat', 'dog']))","metadata":{"id":"8jsd9WZfNoR3","outputId":"18002ed0-74f1-496b-c4a9-5b9af81294a8"},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix, ConfusionMatrixDisplay\ncm = confusion_matrix(y_test, y_pred)\ndisp = ConfusionMatrixDisplay(confusion_matrix=cm)\ndisp.plot(cmap=plt.cm.Blues)\nplt.title('Confusion Matrix')\nplt.show()","metadata":{"id":"Lz0zLHwIS5Mt","outputId":"d06b3aeb-2d8d-4da7-dd57-8a7af414b5ef"},"execution_count":null,"outputs":[]}]}