{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"name":"python","version":"3.10.13","mimetype":"text/x-python","codemirror_mode":{"name":"ipython","version":3},"pygments_lexer":"ipython3","nbconvert_exporter":"python","file_extension":".py"},"kaggle":{"accelerator":"nvidiaTeslaT4","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30698,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":true}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import zipfile\nimport os\n\nzip_path = '/kaggle/input/dogs-vs-cats/train.zip'\nextract_path = '/kaggle/working/'\n\n\nwith zipfile.ZipFile(zip_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_path)\n    \n\ndir_train = os.path.join(extract_path, 'train')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-09-29T21:55:51.472257Z","iopub.execute_input":"2024-09-29T21:55:51.472514Z","iopub.status.idle":"2024-09-29T21:56:01.007974Z","shell.execute_reply.started":"2024-09-29T21:55:51.472490Z","shell.execute_reply":"2024-09-29T21:56:01.007175Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import cv2\nimport numpy as np\nfrom skimage.feature import hog\nfrom skimage.color import rgb2gray\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.svm import SVC\nfrom sklearn.metrics import accuracy_score,classification_report","metadata":{"execution":{"iopub.status.busy":"2024-09-29T21:56:01.015474Z","iopub.execute_input":"2024-09-29T21:56:01.015794Z","iopub.status.idle":"2024-09-29T21:56:02.112099Z","shell.execute_reply.started":"2024-09-29T21:56:01.015763Z","shell.execute_reply":"2024-09-29T21:56:02.110901Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nimage_files = [os.path.join(dir_train, file) for file in os.listdir(dir_train) if file.endswith('.jpg')]","metadata":{"execution":{"iopub.status.busy":"2024-09-29T21:56:05.306716Z","iopub.execute_input":"2024-09-29T21:56:05.307159Z","iopub.status.idle":"2024-09-29T21:56:05.378744Z","shell.execute_reply.started":"2024-09-29T21:56:05.307132Z","shell.execute_reply":"2024-09-29T21:56:05.378054Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"imagefiles1 = image_files[:25000]","metadata":{"execution":{"iopub.status.busy":"2024-09-29T21:56:16.910892Z","iopub.execute_input":"2024-09-29T21:56:16.911262Z","iopub.status.idle":"2024-09-29T21:56:16.916193Z","shell.execute_reply.started":"2024-09-29T21:56:16.911234Z","shell.execute_reply":"2024-09-29T21:56:16.915237Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef compute_hog_features(image):\n    image = rgb2gray(image) \n    features = hog(image, orientations=9, pixels_per_cell=(8, 8),\n                   cells_per_block=(2, 2), block_norm='L2-Hys',\n                   transform_sqrt=True)\n    return features","metadata":{"execution":{"iopub.status.busy":"2024-09-29T21:56:22.793821Z","iopub.execute_input":"2024-09-29T21:56:22.794181Z","iopub.status.idle":"2024-09-29T21:56:22.799462Z","shell.execute_reply.started":"2024-09-29T21:56:22.794142Z","shell.execute_reply":"2024-09-29T21:56:22.798374Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\ndef compute_hog_feature(image):\n    \n    gray_image = rgb2gray(image)\n    \n\n    features, hog_image = hog(gray_image, orientations=9, pixels_per_cell=(8, 8),\n                              cells_per_block=(2,2), block_norm='L2-Hys',\n                              visualize=True, transform_sqrt=True)\n    \n\n    hog_image_rescaled = exposure.rescale_intensity(hog_image, in_range=(0, 20))\n    \n    return features, hog_image_rescaled","metadata":{"execution":{"iopub.status.busy":"2024-09-29T21:56:24.874829Z","iopub.execute_input":"2024-09-29T21:56:24.875492Z","iopub.status.idle":"2024-09-29T21:56:24.881048Z","shell.execute_reply.started":"2024-09-29T21:56:24.875461Z","shell.execute_reply":"2024-09-29T21:56:24.880098Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"total_images = len(imagefiles1)\nprocessed_images = 0","metadata":{"execution":{"iopub.status.busy":"2024-09-29T21:56:28.570003Z","iopub.execute_input":"2024-09-29T21:56:28.570361Z","iopub.status.idle":"2024-09-29T21:56:28.574619Z","shell.execute_reply.started":"2024-09-29T21:56:28.570332Z","shell.execute_reply":"2024-09-29T21:56:28.573616Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nfrom skimage.feature import hog\nfrom skimage import exposure\n\n\nimage_files = image_files[:5]\n\n\noriginal_images = []\nhog_images = []\n\nfor image_path in image_files:\n    image = cv2.imread(image_path)  # Đọc hình ảnh bằng OpenCV\n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  # Chuyển đổi sang định dạng RGB\n    image = cv2.resize(image, (100,150))\n    features, hog_image = compute_hog_feature(image)  # Tính toán các đặc trưng HoG\n    original_images.append(image)\n    hog_images.append(hog_image)\n\n\nfig, axes = plt.subplots(nrows=5, ncols=2, figsize=(10, 15),\n                         subplot_kw={'xticks': [], 'yticks': []})\n\nfor i in range(5):\n    axes[i, 0].imshow(original_images[i])\n    axes[i, 0].set_title(f'Original Image {i+1}')\n    axes[i, 1].imshow(hog_images[i], cmap='gray')\n    axes[i, 1].set_title(f'HoG Image {i+1}')\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-09-29T21:56:31.239095Z","iopub.execute_input":"2024-09-29T21:56:31.239474Z","iopub.status.idle":"2024-09-29T21:56:32.671074Z","shell.execute_reply.started":"2024-09-29T21:56:31.239446Z","shell.execute_reply":"2024-09-29T21:56:32.670210Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"hog_features_list = []\nlabels = []\nfor image_path in imagefiles1:\n    processed_images += 1\n    print(f\"Processing image {processed_images}/{total_images}\", end=\"\\r\")\n    image = cv2.imread(image_path)  \n    image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)  \n    image = cv2.resize(image, (100,150))\n    features = compute_hog_features(image)\n    hog_features_list.append(features)\n    \n    if 'cat' in os.path.basename(image_path):\n        labels.append(0)  # 0 is a cat \n    elif 'dog' in os.path.basename(image_path):\n        labels.append(1)  # 1 is a dog","metadata":{"execution":{"iopub.status.busy":"2024-09-29T21:57:01.830101Z","iopub.execute_input":"2024-09-29T21:57:01.831008Z","iopub.status.idle":"2024-09-29T22:01:20.422035Z","shell.execute_reply.started":"2024-09-29T21:57:01.830977Z","shell.execute_reply":"2024-09-29T22:01:20.421061Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nX = np.array(hog_features_list)\ny = np.array(labels)","metadata":{"execution":{"iopub.status.busy":"2024-09-29T22:02:54.573336Z","iopub.execute_input":"2024-09-29T22:02:54.573696Z","iopub.status.idle":"2024-09-29T22:02:54.978114Z","shell.execute_reply.started":"2024-09-29T22:02:54.573668Z","shell.execute_reply":"2024-09-29T22:02:54.977344Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(X.shape)\nprint(y.shape)","metadata":{"execution":{"iopub.status.busy":"2024-09-29T22:02:57.481754Z","iopub.execute_input":"2024-09-29T22:02:57.482712Z","iopub.status.idle":"2024-09-29T22:02:57.487008Z","shell.execute_reply.started":"2024-09-29T22:02:57.482679Z","shell.execute_reply":"2024-09-29T22:02:57.486011Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)","metadata":{"execution":{"iopub.status.busy":"2024-09-29T22:03:00.458053Z","iopub.execute_input":"2024-09-29T22:03:00.458430Z","iopub.status.idle":"2024-09-29T22:03:00.849197Z","shell.execute_reply.started":"2024-09-29T22:03:00.458401Z","shell.execute_reply":"2024-09-29T22:03:00.848413Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n\nscaler = StandardScaler()\nX_train_normalized = scaler.fit_transform(X_train)\nX_test_normalized = scaler.transform(X_test)\n\n\npca = PCA(n_components=100)  # Bạn có thể chọn số lượng thành phần\nX_train_pca = pca.fit_transform(X_train_normalized)\nX_test_pca = pca.transform(X_test_normalized)","metadata":{"execution":{"iopub.status.busy":"2024-09-29T22:03:03.218140Z","iopub.execute_input":"2024-09-29T22:03:03.218984Z","iopub.status.idle":"2024-09-29T22:03:17.562717Z","shell.execute_reply.started":"2024-09-29T22:03:03.218953Z","shell.execute_reply":"2024-09-29T22:03:17.561274Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.linear_model import LogisticRegression \nfrom sklearn.model_selection import GridSearchCV\nlr = LogisticRegression(max_iter=10000)\nsearch_space = {\n    'C': [0.1, 5, 10, 20]\n}\nGS = GridSearchCV(\n    estimator=lr,  # Mô hình Logistic Regression\n    param_grid=search_space)\nGS.fit(X_train_pca, y_train)","metadata":{"execution":{"iopub.status.busy":"2024-09-29T22:04:38.505859Z","iopub.execute_input":"2024-09-29T22:04:38.506538Z","iopub.status.idle":"2024-09-29T22:04:40.194182Z","shell.execute_reply.started":"2024-09-29T22:04:38.506507Z","shell.execute_reply":"2024-09-29T22:04:40.193033Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_params = GS.best_estimator_\nbest_params","metadata":{"execution":{"iopub.status.busy":"2024-09-29T22:04:50.569233Z","iopub.execute_input":"2024-09-29T22:04:50.569605Z","iopub.status.idle":"2024-09-29T22:04:50.581767Z","shell.execute_reply.started":"2024-09-29T22:04:50.569575Z","shell.execute_reply":"2024-09-29T22:04:50.580976Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"lo_r = LogisticRegression(C=0.1, max_iter=10000)\nlo_r.fit(X_train_pca, y_train)\ny_lo_r_pred = lo_r.predict(X_test_pca)\nprint(classification_report(y_test, y_lo_r_pred))","metadata":{"execution":{"iopub.status.busy":"2024-09-29T22:04:54.759726Z","iopub.execute_input":"2024-09-29T22:04:54.760074Z","iopub.status.idle":"2024-09-29T22:04:54.866958Z","shell.execute_reply.started":"2024-09-29T22:04:54.760046Z","shell.execute_reply":"2024-09-29T22:04:54.865962Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"svm_1 = SVC(C=1, kernel='rbf')\nsvm_1.fit(X_train_pca, y_train)\ny_pred = svm_1.predict(X_test_pca)\nprint(classification_report(y_test, y_pred))","metadata":{"execution":{"iopub.status.busy":"2024-09-29T22:28:36.436665Z","iopub.execute_input":"2024-09-29T22:28:36.437085Z","iopub.status.idle":"2024-09-29T22:29:18.775561Z","shell.execute_reply.started":"2024-09-29T22:28:36.437056Z","shell.execute_reply":"2024-09-29T22:29:18.774566Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.neighbors import KNeighborsClassifier\n\nknn = KNeighborsClassifier()\n\n\nparam_grid = {\n    'n_neighbors': [10],\n    'weights': ['uniform', 'distance'],\n    'metric': ['euclidean', 'manhattan', 'minkowski']\n}\n\n\ngrid_search = GridSearchCV(knn, param_grid, cv=5, n_jobs=-1, verbose=1)\ngrid_search.fit(X_train_pca, y_train)\n\n\nprint(f\"Best parameters found: {grid_search.best_params_}\")\n\n\nbest_knn = grid_search.best_estimator_\ny_pred = best_knn.predict(X_test_pca)\n\n\nprint(classification_report(y_test, y_pred))","metadata":{"execution":{"iopub.status.busy":"2024-09-29T22:06:30.181729Z","iopub.execute_input":"2024-09-29T22:06:30.182064Z","iopub.status.idle":"2024-09-29T22:07:12.023291Z","shell.execute_reply.started":"2024-09-29T22:06:30.182038Z","shell.execute_reply":"2024-09-29T22:07:12.022198Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"\nknn = KNeighborsClassifier()\n\n\nparam_grid = {\n    'n_neighbors': list(range(1,100)),\n    'weights': ['uniform'],\n    'metric': ['euclidean']\n}\n\n\ngrid_search = GridSearchCV(knn, param_grid, cv=5, n_jobs=-1, verbose=1)\ngrid_search.fit(X_train_pca, y_train)\n\n\nprint(f\"Best parameters found: {grid_search.best_params_}\")\n\n\nbest_knn = grid_search.best_estimator_\ny_pred = best_knn.predict(X_test_pca)\n\n\nprint(classification_report(y_test, y_pred))","metadata":{"execution":{"iopub.status.busy":"2024-09-29T22:07:55.024072Z","iopub.execute_input":"2024-09-29T22:07:55.024467Z","iopub.status.idle":"2024-09-29T22:10:38.531831Z","shell.execute_reply.started":"2024-09-29T22:07:55.024435Z","shell.execute_reply":"2024-09-29T22:10:38.530612Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import confusion_matrix, classification_report\nimport seaborn as sns\ncm = confusion_matrix(y_test, y_pred, labels=[0, 1])\nclr = classification_report(y_test, y_pred, labels=[0, 1], target_names=[\"CAT\", \"DOG\"])\n\nplt.figure(figsize=(6, 6))\nsns.heatmap(cm, annot=True, fmt='g', vmin=0, cmap='Blues', cbar=False)\nplt.xticks(ticks=[0.5, 1.5], labels=[\"CAT\", \"DOG\"])\nplt.yticks(ticks=[0.5, 1.5], labels=[\"CAT\", \"DOG\"])\nplt.xlabel(\"Predicted\")\nplt.ylabel(\"Actual\")\nplt.title(\"Confusion Matrix\")\nplt.show()\n\nprint(\"Classification Report:\\n----------------------\\n\", clr)","metadata":{"execution":{"iopub.status.busy":"2024-09-29T22:29:25.443501Z","iopub.execute_input":"2024-09-29T22:29:25.443824Z","iopub.status.idle":"2024-09-29T22:29:25.628189Z","shell.execute_reply.started":"2024-09-29T22:29:25.443800Z","shell.execute_reply":"2024-09-29T22:29:25.627286Z"},"trusted":true},"execution_count":null,"outputs":[]}]}