{"metadata":{"kernelspec":{"language":"python","display_name":"Python 3","name":"python3"},"language_info":{"pygments_lexer":"ipython3","nbconvert_exporter":"python","version":"3.6.4","file_extension":".py","codemirror_mode":{"name":"ipython","version":3},"name":"python","mimetype":"text/x-python"}},"nbformat_minor":4,"nbformat":4,"cells":[{"cell_type":"code","source":"# reference : https://www.kaggle.com/code/dimakyn/knn-image-classification\n!pip install imutils","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:29:26.124771Z","iopub.execute_input":"2023-01-17T00:29:26.125106Z","iopub.status.idle":"2023-01-17T00:29:40.074216Z","shell.execute_reply.started":"2023-01-17T00:29:26.125030Z","shell.execute_reply":"2023-01-17T00:29:40.073034Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# import the necessarry packages\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import train_test_split\nfrom imutils import paths\nimport pandas as pd\nimport numpy as np \nimport imutils\nimport cv2\nimport os\nprint('success')","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:29:40.077495Z","iopub.execute_input":"2023-01-17T00:29:40.077911Z","iopub.status.idle":"2023-01-17T00:29:40.818747Z","shell.execute_reply.started":"2023-01-17T00:29:40.077871Z","shell.execute_reply":"2023-01-17T00:29:40.817778Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def image_to_feature_vector(image, size=(32, 32)):\n    # resize the image to a fixed size, then flatten the image into a list of raw pixel intensities\n    return cv2.resize(image, size).flatten()","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:29:56.623440Z","iopub.execute_input":"2023-01-17T00:29:56.623809Z","iopub.status.idle":"2023-01-17T00:29:56.629187Z","shell.execute_reply.started":"2023-01-17T00:29:56.623777Z","shell.execute_reply":"2023-01-17T00:29:56.627940Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"def extract_color_histogram(image, bins=(8, 8, 8)):\n    # extract a 3D color histogram from the HSV color space using\n    # the supplied number of `bins` per channel\n    hsv = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\n    hist = cv2.calcHist([hsv], [0, 1, 2], None, bins,\n        [0, 180, 0, 256, 0, 256])\n    # handle normalizing the histogram if we are using OpenCV 2.4.X\n    if imutils.is_cv2():\n        hist = cv2.normalize(hist)\n    # otherwise, perform \"in place\" normalization in OpenCV 3 (I\n    # personally hate the way this is done\n    else:\n        cv2.normalize(hist, hist)\n    # return the flattened histogram as the feature vector\n    return hist.flatten()","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:30:00.832561Z","iopub.execute_input":"2023-01-17T00:30:00.833908Z","iopub.status.idle":"2023-01-17T00:30:00.841247Z","shell.execute_reply.started":"2023-01-17T00:30:00.833853Z","shell.execute_reply":"2023-01-17T00:30:00.840012Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip \"../input/dogs-vs-cats/train.zip\"","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:30:06.071506Z","iopub.execute_input":"2023-01-17T00:30:06.072206Z","iopub.status.idle":"2023-01-17T00:30:17.126899Z","shell.execute_reply.started":"2023-01-17T00:30:06.072168Z","shell.execute_reply":"2023-01-17T00:30:17.125497Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"!unzip \"../input/dogs-vs-cats/test1.zip\"","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:33:50.509422Z","iopub.execute_input":"2023-01-17T00:33:50.509809Z","iopub.status.idle":"2023-01-17T00:33:58.252430Z","shell.execute_reply.started":"2023-01-17T00:33:50.509776Z","shell.execute_reply":"2023-01-17T00:33:58.251187Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"dataset = \"/kaggle/working/train\"\nneighbors = 2\nprint('success')","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:31:33.393577Z","iopub.execute_input":"2023-01-17T00:31:33.394325Z","iopub.status.idle":"2023-01-17T00:31:33.399870Z","shell.execute_reply.started":"2023-01-17T00:31:33.394285Z","shell.execute_reply":"2023-01-17T00:31:33.398867Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# grab the list of images that we'll be describing\nprint(\"[INFO] describing images...\")\nimagePaths = list(paths.list_images(dataset))\nprint(\"[INFO] dataset has {} images\".format(len(imagePaths)))","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:31:37.823137Z","iopub.execute_input":"2023-01-17T00:31:37.823495Z","iopub.status.idle":"2023-01-17T00:31:37.901647Z","shell.execute_reply.started":"2023-01-17T00:31:37.823467Z","shell.execute_reply":"2023-01-17T00:31:37.900564Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# initialize the raw pixel intensities matrix, the features matrix, and labels list\nrawImages = []\nfeatures = []\nlabels = []\n\n# loop over the input images\nfor (i, imagePath) in enumerate(imagePaths):\n    # load the image and extract the class label (assuming that our\n    # path as the format: /path/to/dataset/{class}.{image_num}.jpg\n    image = cv2.imread(imagePath)\n    label = imagePath.split(os.path.sep)[-1].split(\".\")[0]\n    \n    # extract raw pixel intensity \"features\", followed by a color\n    # histogram to characterize the color distribution of the pixels\n    # in the image\n    pixels = image_to_feature_vector(image)\n    hist = extract_color_histogram(image)\n    \n    # update the raw images, features, and labels matricies, respectively\n    rawImages.append(pixels)\n    features.append(hist)\n    labels.append(label)\n    \n    # show an update every 1,000 images\n    if i > 0 and i % 1000 == 0:\n        print(\"[INFO] processed {}/{}\".format(i, len(imagePaths)))","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:31:54.201323Z","iopub.execute_input":"2023-01-17T00:31:54.201697Z","iopub.status.idle":"2023-01-17T00:33:25.353364Z","shell.execute_reply.started":"2023-01-17T00:31:54.201666Z","shell.execute_reply":"2023-01-17T00:33:25.352363Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# show some information on the memory consumed by the raw images matrix and features matrix\nrawImages = np.array(rawImages)\nfeatures = np.array(features)\nlabels = np.array(labels)\n\nprint('success to array')","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:34:17.682163Z","iopub.execute_input":"2023-01-17T00:34:17.683151Z","iopub.status.idle":"2023-01-17T00:34:17.830935Z","shell.execute_reply.started":"2023-01-17T00:34:17.683098Z","shell.execute_reply":"2023-01-17T00:34:17.829754Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# partition the data into training and testing splits, using 75%\n# of the data for training and the remaining 25% for testing\n(trainRI, testRI, trainRL, testRL) = train_test_split(\n    rawImages, labels, test_size=0.25, random_state=42)\n(trainFeat, testFeat, trainLabels, testLabels) = train_test_split(\n    features, labels, test_size=0.25, random_state=42)\nprint('success')","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:34:20.559484Z","iopub.execute_input":"2023-01-17T00:34:20.560547Z","iopub.status.idle":"2023-01-17T00:34:20.623197Z","shell.execute_reply.started":"2023-01-17T00:34:20.560503Z","shell.execute_reply":"2023-01-17T00:34:20.622160Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# train and evaluate a k-NN classifer on the raw pixel intensities\nprint(\"[INFO] evaluating raw pixel accuracy...\")\nmodel = KNeighborsClassifier(n_neighbors=neighbors,n_jobs=-1)\nmodel.fit(trainRI, trainRL)\nacc = model.score(testRI, testRL)\nprint(\"[INFO] raw pixel accuracy: {:.2f}%\".format(acc * 100))","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:34:23.223365Z","iopub.execute_input":"2023-01-17T00:34:23.223752Z","iopub.status.idle":"2023-01-17T00:34:38.397431Z","shell.execute_reply.started":"2023-01-17T00:34:23.223721Z","shell.execute_reply":"2023-01-17T00:34:38.396366Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"# train and evaluate a k-NN classifer on the raw pixel intensities\nprint(\"[INFO] evaluating raw pixel accuracy...\")\nmodel = KNeighborsClassifier(n_neighbors=neighbors,n_jobs=-1)\nmodel.fit(trainFeat, trainLabels)\nacc = model.score(testFeat, testLabels)\nprint(\"[INFO] raw pixel accuracy: {:.2f}%\".format(acc * 100))","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:34:40.894446Z","iopub.execute_input":"2023-01-17T00:34:40.897414Z","iopub.status.idle":"2023-01-17T00:34:45.360794Z","shell.execute_reply.started":"2023-01-17T00:34:40.897375Z","shell.execute_reply":"2023-01-17T00:34:45.359669Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"testDataset = \"../working/test1\"\n\n# initialize the raw pixel intensities matrix, the features matrix, and labels list\ntestPaths = list(paths.list_images(testDataset))\ntestImages = []\ntestFeatures = []\n\n# loop over the input images\nfor (i, imagePath) in enumerate(testPaths):\n    # load the image and extract the class label (assuming that our\n    # path as the format: /path/to/dataset/{class}.{image_num}.jpg\n    image = cv2.imread(imagePath)\n\n    \n    # extract raw pixel intensity \"features\", followed by a color\n    # histogram to characterize the color distribution of the pixels\n    # in the image\n    pixels = image_to_feature_vector(image)\n    hist = extract_color_histogram(image)\n    \n    # update the raw images, features, and labels matricies, respectively\n    testImages.append(pixels)\n    testFeatures.append(hist)\n    \n    # show an update every 1,000 images\n    if i > 0 and i % 1000 == 0:\n        print(\"[INFO] processed {}/{}\".format(i, len(testPaths)))","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:34:49.822237Z","iopub.execute_input":"2023-01-17T00:34:49.822595Z","iopub.status.idle":"2023-01-17T00:35:35.497657Z","shell.execute_reply.started":"2023-01-17T00:34:49.822565Z","shell.execute_reply":"2023-01-17T00:35:35.496655Z"},"trusted":true},"execution_count":null,"outputs":[]},{"cell_type":"code","source":"pred = model.predict(testFeatures)\npred = np.array([0 if x == \"dog\" else 1 for x in pred ])\n\n# 0 == dog and 1 == cat\n# print(pred)\n# print(len(pred))\n\nfor i in range(0,len(pred)):\n    result = 'dog' if pred[i]==0 else 'cat'\n    print('image tester-'+str(i)+' : ' +result)","metadata":{"execution":{"iopub.status.busy":"2023-01-17T00:35:43.308050Z","iopub.execute_input":"2023-01-17T00:35:43.308411Z","iopub.status.idle":"2023-01-17T00:35:52.332368Z","shell.execute_reply.started":"2023-01-17T00:35:43.308382Z","shell.execute_reply":"2023-01-17T00:35:52.326098Z"},"trusted":true},"execution_count":null,"outputs":[]}]}