{"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":"none","dataSources":[{"sourceId":3362,"databundleVersionId":31148,"sourceType":"competition"}],"dockerImageVersionId":30715,"isInternetEnabled":true,"language":"python","sourceType":"notebook","isGpuEnabled":false}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"import zipfile\nimport os\n# Specify the path to the zip file\nzip_path = '/kaggle/input/dogs-vs-cats/train.zip'\nextract_path = '/kaggle/working/'\n\n# Extract the zip file\nwith zipfile.ZipFile(zip_path, 'r') as zip_ref:\n    zip_ref.extractall(extract_path)\n    \n# After extracting, specify the directory of the actual images\ndir_train = os.path.join(extract_path, 'train')","metadata":{"_uuid":"8f2839f25d086af736a60e9eeb907d3b93b6e0e5","_cell_guid":"b1076dfc-b9ad-4769-8c92-a6c4dae69d19","execution":{"iopub.status.busy":"2024-06-17T19:41:25.739015Z","iopub.execute_input":"2024-06-17T19:41:25.740219Z","iopub.status.idle":"2024-06-17T19:41:40.837420Z","shell.execute_reply.started":"2024-06-17T19:41:25.740158Z","shell.execute_reply":"2024-06-17T19:41:40.835844Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def sobel_filters(img):\n    Sx=np.array([[-1,0,1],[-2,0,2],[-1,0,1]],np.float32)\n    Sy=np.array([[1,2,1],[0,0,0],[-1,-2,-1]],np.float32)\n\n    Ix = cv2.filter2D(img, -1, Sx)\n    Iy = cv2.filter2D(img, -1, Sy)\n\n    G=np.hypot(Ix,Iy)\n    G=G/G.max()*255\n    theta=np.arctan2(Iy,Ix)\n\n    return Ix,Iy,G,theta\n\ndef calFeatureVector(img_src):\n  img_dst = img_src.copy()\n  img_dst = cv2.resize(img_dst, (100, 150))\n  Ix, Iy, G, theta  = sobel_filters(img_dst)\n\n  fearture = []\n  for i in range(G.shape[0]):\n    tmp = 0\n    for j in range(G.shape[1]):\n      tmp = tmp + G[i,j]\n    fearture.append(tmp)\n\n  for j in range(G.shape[1]):\n    tmp = 0\n    for i in range(G.shape[0]):\n      tmp = tmp + G[i,j]\n    fearture.append(tmp)\n  return fearture","metadata":{"execution":{"iopub.status.busy":"2024-06-17T19:41:40.839801Z","iopub.execute_input":"2024-06-17T19:41:40.840206Z","iopub.status.idle":"2024-06-17T19:41:40.913937Z","shell.execute_reply.started":"2024-06-17T19:41:40.840155Z","shell.execute_reply":"2024-06-17T19:41:40.912635Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Lấy danh sách tất cả các tệp tin hình ảnh trong thư mục\nimage_files = [os.path.join(dir_train, file) for file in os.listdir(dir_train) if file.endswith('.jpg')]\nimagefiles1 = image_files[:25000]","metadata":{"execution":{"iopub.status.busy":"2024-06-17T19:41:40.920001Z","iopub.execute_input":"2024-06-17T19:41:40.920475Z","iopub.status.idle":"2024-06-17T19:41:41.010900Z","shell.execute_reply.started":"2024-06-17T19:41:40.920435Z","shell.execute_reply":"2024-06-17T19:41:41.009703Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"import matplotlib.pyplot as plt\nimport cv2 \nimport numpy as np\n\n# Chỉ lấy 5 hình ảnh đầu tiên để hiển thị\nimage_files = image_files[:5]\n\noriginal_images = []\nsobel_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    # Chuyển đổi ảnh sang grayscale\n    img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    # Áp dụng bộ lọc Sobel lên ảnh \n    _, _, G, _ = sobel_filters(img_gray)\n    original_images.append(image)\n    sobel_images.append(G)\n\n# Hiển thị ảnh gốc và ảnh HoG\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(sobel_images[i], cmap='gray')\n    axes[i, 1].set_title(f'Sobel Image {i+1}')\n\nplt.tight_layout()\nplt.show()","metadata":{"execution":{"iopub.status.busy":"2024-06-17T19:41:41.014870Z","iopub.execute_input":"2024-06-17T19:41:41.015285Z","iopub.status.idle":"2024-06-17T19:41:42.526894Z","shell.execute_reply.started":"2024-06-17T19:41:41.015253Z","shell.execute_reply":"2024-06-17T19:41:42.525467Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"total_images = len(imagefiles1)\nprocessed_images = 0\nsobel_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)  # Đọ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     # Chuyển đổi ảnh sang grayscale\n    img_gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n    # Áp dụng bộ lọc Sobel lên ảnh\n    features = calFeatureVector(img_gray)  # Tính toán các đặc trưng Sobel\n    sobel_features_list.append(features)\n    \n    if 'cat' in os.path.basename(image_path):\n        labels.append(0)  # 0 cho mèo\n    elif 'dog' in os.path.basename(image_path):\n        labels.append(1)  # 1 cho chó","metadata":{"execution":{"iopub.status.busy":"2024-06-17T19:41:42.528531Z","iopub.execute_input":"2024-06-17T19:41:42.528893Z","iopub.status.idle":"2024-06-17T19:52:45.579607Z","shell.execute_reply.started":"2024-06-17T19:41:42.528862Z","shell.execute_reply":"2024-06-17T19:52:45.578362Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Chuyển đổi danh sách các vector đặc trưng và nhãn thành các mảng numpy\nX = np.array(sobel_features_list)\ny = np.array(labels)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T19:52:45.581091Z","iopub.execute_input":"2024-06-17T19:52:45.581446Z","iopub.status.idle":"2024-06-17T19:52:46.116682Z","shell.execute_reply.started":"2024-06-17T19:52:45.581415Z","shell.execute_reply":"2024-06-17T19:52:46.115475Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"print(X.shape)\nprint(y.shape)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T19:52:46.118313Z","iopub.execute_input":"2024-06-17T19:52:46.118736Z","iopub.status.idle":"2024-06-17T19:52:46.135509Z","shell.execute_reply.started":"2024-06-17T19:52:46.118701Z","shell.execute_reply":"2024-06-17T19:52:46.134067Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Chia dữ liệu thành tập huấn luyện và tập kiểm tra\nfrom sklearn.model_selection import train_test_split\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-06-17T19:52:46.137306Z","iopub.execute_input":"2024-06-17T19:52:46.137832Z","iopub.status.idle":"2024-06-17T19:52:47.041598Z","shell.execute_reply.started":"2024-06-17T19:52:46.137789Z","shell.execute_reply":"2024-06-17T19:52:47.040262Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.decomposition import PCA\nfrom sklearn.preprocessing import StandardScaler\n# Sử dụng PCA để giảm chiều dữ liệu\n# Chuẩn hóa tập huấn luyện\n# Chuẩn hóa dữ liệu\nscaler = StandardScaler()\nX_train_normalized = scaler.fit_transform(X_train)\nX_test_normalized = scaler.transform(X_test)\n\n# Áp dụng PCA\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-06-17T19:52:47.043028Z","iopub.execute_input":"2024-06-17T19:52:47.043407Z","iopub.status.idle":"2024-06-17T19:52:48.924338Z","shell.execute_reply.started":"2024-06-17T19:52:47.043375Z","shell.execute_reply":"2024-06-17T19:52:48.922199Z"},"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,  # Không gian tìm kiếm siêu tham số\n)\nGS.fit(X_train_pca, y_train)","metadata":{"execution":{"iopub.status.busy":"2024-06-17T19:52:48.926309Z","iopub.execute_input":"2024-06-17T19:52:48.927128Z","iopub.status.idle":"2024-06-17T19:52:53.318500Z","shell.execute_reply.started":"2024-06-17T19:52:48.927082Z","shell.execute_reply":"2024-06-17T19:52:53.316815Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"best_params = GS.best_estimator_\nbest_params","metadata":{"execution":{"iopub.status.busy":"2024-06-17T19:52:53.327941Z","iopub.execute_input":"2024-06-17T19:52:53.329181Z","iopub.status.idle":"2024-06-17T19:52:53.358256Z","shell.execute_reply.started":"2024-06-17T19:52:53.329102Z","shell.execute_reply":"2024-06-17T19:52:53.356507Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.metrics import accuracy_score, classification_report, confusion_matrix\nlo_r = LogisticRegression(C=20, 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-06-17T20:32:13.052158Z","iopub.execute_input":"2024-06-17T20:32:13.052585Z","iopub.status.idle":"2024-06-17T20:32:13.325129Z","shell.execute_reply.started":"2024-06-17T20:32:13.052552Z","shell.execute_reply":"2024-06-17T20:32:13.323480Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.svm import SVC\nsvm = SVC()\n\n# Định nghĩa phạm vi các tham số cần tìm kiếm\nparam_grid = {\n    'C': [0.1, 1, 10],  # Tham số điều chỉnh độ ổn định của ranh giới quyết định\n    'kernel': ['rbf'],  # Hạt nhân của SVM\n}\n\n# Sử dụng GridSearchCV để tìm kiếm tham số tốt nhất\ngrid_search = GridSearchCV(svm, param_grid, cv=5, n_jobs=-1, verbose=1)\ngrid_search.fit(X_train_pca, y_train)\n\n# In ra các tham số tốt nhất\nprint(f\"Best parameters found: {grid_search.best_params_}\")\n\n# Sử dụng các tham số tốt nhất để huấn luyện và đánh giá mô hình\nbest_svm = grid_search.best_estimator_\ny_pred = best_svm.predict(X_test_pca)\n\n# In ra báo cáo phân loại\nprint(classification_report(y_test, y_pred))","metadata":{"execution":{"iopub.status.busy":"2024-06-17T19:52:53.702125Z","iopub.execute_input":"2024-06-17T19:52:53.708385Z","iopub.status.idle":"2024-06-17T20:04:52.845984Z","shell.execute_reply.started":"2024-06-17T19:52:53.708299Z","shell.execute_reply":"2024-06-17T20:04:52.844553Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.svm import SVC\nsvm = SVC()\n\n# Định nghĩa phạm vi các tham số cần tìm kiếm\nparam_grid = {\n    'C': [1],  # Tham số điều chỉnh độ ổn định của ranh giới quyết định\n    'kernel': ['linear', 'rbf', 'poly'],  # Hạt nhân của SVM\n}\n\n# Sử dụng GridSearchCV để tìm kiếm tham số tốt nhất\ngrid_search = GridSearchCV(svm, param_grid, cv=5, n_jobs=-1, verbose=1)\ngrid_search.fit(X_train_pca, y_train)\n\n# In ra các tham số tốt nhất\nprint(f\"Best parameters found: {grid_search.best_params_}\")\n\n# Sử dụng các tham số tốt nhất để huấn luyện và đánh giá mô hình\nbest_svm = grid_search.best_estimator_\ny_pred = best_svm.predict(X_test_pca)\n\n# In ra báo cáo phân loại\nprint(classification_report(y_test, y_pred))","metadata":{"execution":{"iopub.status.busy":"2024-06-17T20:04:52.847860Z","iopub.execute_input":"2024-06-17T20:04:52.848294Z","iopub.status.idle":"2024-06-17T20:27:12.905095Z","shell.execute_reply.started":"2024-06-17T20:04:52.848252Z","shell.execute_reply":"2024-06-17T20:27:12.903751Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"from sklearn.neighbors import KNeighborsClassifier\n# Thiết lập K-NN và GridSearchCV để tìm kiếm tham số tốt nhất\nknn = KNeighborsClassifier()\n\n# Định nghĩa phạm vi các tham số cần tìm kiếm\nparam_grid = {\n    'n_neighbors': [10],\n    'weights': ['uniform', 'distance'],\n    'metric': ['euclidean', 'manhattan', 'minkowski']\n}\n\n# Sử dụng GridSearchCV để tìm kiếm tham số tốt nhất\ngrid_search = GridSearchCV(knn, param_grid, cv=5, n_jobs=-1, verbose=1)\ngrid_search.fit(X_train_pca, y_train)\n\n# In ra các tham số tốt nhất\nprint(f\"Best parameters found: {grid_search.best_params_}\")\n\n# Sử dụng các tham số tốt nhất để huấn luyện và đánh giá mô hình\nbest_knn = grid_search.best_estimator_\ny_pred = best_knn.predict(X_test_pca)\n\n# In ra báo cáo phân loại\nprint(classification_report(y_test, y_pred))","metadata":{"execution":{"iopub.status.busy":"2024-06-17T20:27:12.906602Z","iopub.execute_input":"2024-06-17T20:27:12.906931Z","iopub.status.idle":"2024-06-17T20:28:02.763635Z","shell.execute_reply.started":"2024-06-17T20:27:12.906902Z","shell.execute_reply":"2024-06-17T20:28:02.761995Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# Thiết lập K-NN và GridSearchCV để tìm kiếm tham số tốt nhất\nknn = KNeighborsClassifier()\n\n# Định nghĩa phạm vi các tham số cần tìm kiếm\nparam_grid = {\n    'n_neighbors': list(range(1,100)),\n    'weights': ['uniform'],\n    'metric': ['euclidean']\n}\n\n# Sử dụng GridSearchCV để tìm kiếm tham số tốt nhất\ngrid_search = GridSearchCV(knn, param_grid, cv=5, n_jobs=-1, verbose=1)\ngrid_search.fit(X_train_pca, y_train)\n\n# In ra các tham số tốt nhất\nprint(f\"Best parameters found: {grid_search.best_params_}\")\n\n# Sử dụng các tham số tốt nhất để huấn luyện và đánh giá mô hình\nbest_knn = grid_search.best_estimator_\ny_pred = best_knn.predict(X_test_pca)\n\n# In ra báo cáo phân loại\nprint(classification_report(y_test, y_pred))","metadata":{"execution":{"iopub.status.busy":"2024-06-17T20:28:02.765683Z","iopub.execute_input":"2024-06-17T20:28:02.766120Z","iopub.status.idle":"2024-06-17T20:31:45.282694Z","shell.execute_reply.started":"2024-06-17T20:28:02.766077Z","shell.execute_reply":"2024-06-17T20:31:45.281397Z"},"trusted":true},"execution_count":null,"outputs":[]}]}