{"id":4789,"date":"2026-10-15T10:39:53","date_gmt":"2026-10-15T10:39:53","guid":{"rendered":"https:\/\/prwatech.in\/blog\/?p=4789"},"modified":"2026-10-16T15:50:58","modified_gmt":"2026-10-16T15:50:58","slug":"k-nearest-neighbors-algorithm-tutorial","status":"publish","type":"post","link":"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/","title":{"rendered":"k-Nearest Neighbors Algorithm Tutorial"},"content":{"rendered":"<h1><strong><b>K Nearest Neighbors Algorithm Tutorial<\/b><\/strong><\/h1>\n<p>When you move to a new city and look for a good restaurant, you do not study cuisine theory. You ask the people who live closest to you what they like. If most of your neighbours recommend the same place, you go there. The k nearest neighbors algorithm, usually shortened to KNN, makes predictions in exactly this way.<\/p>\n<p>KNN is one of the simplest algorithms in machine learning. It has no training phase in the usual sense. It stores the data, and when a new point arrives, it finds the k closest points in the stored data and lets them decide. For classification, the neighbours vote for a class. For regression, their values are averaged. Because of this, KNN is called a lazy learner: it does no work until it has to predict.<\/p>\n<p>In this tutorial, we explain how KNN works with a small picture example, then look at the three common ways of measuring distance, which are Euclidean, Manhattan and Hamming. We then cover the most important choice in KNN, the value of k, and why feature scaling can decide whether the algorithm works at all. A complete Python program follows, with output from a real run. We end with strengths, limitations, common mistakes and a short FAQ.<\/p>\n<h2><strong><b>What is the K Nearest Neighbors Algorithm?<\/b><\/strong><\/h2>\n<p>KNN is a supervised learning algorithm that predicts the label of a new point from the labels of its closest points in the training data. It makes no assumption about the shape of the data, which is why it is called non parametric. It has been used since the early days of pattern recognition and is still a handy first model, especially as a baseline.<\/p>\n<p>The k in the name is the number of neighbours that get a vote. Its value is the main setting you control.<\/p>\n<h2><strong><b>How does KNN Work?<\/b><\/strong><\/h2>\n<p>Consider a plot with two groups of points, red stars and blue squares, and a new green circle whose class we do not know.<\/p>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4790\" src=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN1.png\" alt=\"k-nearest neighbors Algorithm Tutorial\" width=\"850\" height=\"619\" srcset=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN1.png 350w, https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN1-300x219.png 300w\" sizes=\"auto, (max-width: 850px) 100vw, 850px\" \/><\/p>\n<p>&nbsp;<\/p>\n<ol>\n<li><b><\/b><strong><b>Choose k. <\/b><\/strong>Say k is 3.<\/li>\n<li><b><\/b><strong><b>Measure the distance<\/b><\/strong>from the green circle to every point in the data.<\/li>\n<li><b><\/b><strong><b>Pick the 3 nearest points.<\/b><\/strong><\/li>\n<li><b><\/b><strong><b>Let them vote.<\/b><\/strong>If two of the three are red stars and one is a blue square, the circle is classified as a red star.<\/li>\n<\/ol>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4791\" src=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN2.png\" alt=\"k-nearest neighbors Algorithm Tutorial\" width=\"850\" height=\"655\" srcset=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN2.png 348w, https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN2-300x231.png 300w\" sizes=\"auto, (max-width: 850px) 100vw, 850px\" \/><\/p>\n<p>&nbsp;<\/p>\n<p>For regression, the last step changes. Instead of voting, the algorithm takes the average of the neighbours&#8217; values.<\/p>\n<h2><strong><b>Distance Measures Used in KNN<\/b><\/strong><\/h2>\n<p>Everything in KNN depends on how distance is measured. Three measures are most common.<\/p>\n<h3><strong><b>Euclidean Distance<\/b><\/strong><\/h3>\n<p>This is the straight line distance between two points, the one you would measure with a ruler. It is calculated by squaring the difference in each feature, adding the squares and taking the square root. It is the default for continuous numbers such as height, weight or temperature.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4792\" src=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN3.png\" alt=\"Euclidian Distance\" width=\"850\" height=\"386\" \/><\/p>\n<p>&nbsp;<\/p>\n<h3><strong><b>Manhattan Distance<\/b><\/strong><\/h3>\n<p>This is the distance you would travel in a city laid out in blocks, moving only along the grid. It adds up the absolute difference in each feature, without squaring. It is less affected by one very large difference, so it can work better when the data has outliers or many features.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4793\" src=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN4.png\" alt=\"Manhattan Distance\" width=\"850\" height=\"479\" \/><\/p>\n<p>&nbsp;<\/p>\n<h3><strong><b>Hamming Distance<\/b><\/strong><\/h3>\n<p>This is used for categorical data, such as colour or yes and no answers. It simply counts the number of features where the two points differ. If a feature matches, it adds 0. If it does not, it adds 1. For example, two records that agree on three of four categories have a Hamming distance of 1.<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4794\" src=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN5.png\" alt=\"Hamming Distance\" width=\"850\" height=\"748\" \/><\/p>\n<p>&nbsp;<\/p>\n<div style=\"border: 1px solid #d9e0ea; border-radius: 8px; overflow-x: auto; margin: 20px 0; -webkit-overflow-scrolling: touch;\">\n<table style=\"width: 100%; min-width: 720px; border-collapse: collapse; font-family: Arial,Helvetica,sans-serif; font-size: 16px; line-height: 1.6; color: #1f2937;\">\n<caption style=\"caption-side: top; text-align: left; padding: 14px 16px; font-weight: bold; font-size: 17px; color: #0f2a4a;\">Distance measures for KNN<\/caption>\n<thead>\n<tr>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38; width: 160px;\" scope=\"col\">Distance<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">Best for<\/th>\n<th style=\"background: #0f2a4a; color: #ffffff; text-align: left; padding: 12px 16px; border-bottom: 2px solid #0b1f38;\" scope=\"col\">Watch out for<\/th>\n<\/tr>\n<\/thead>\n<tbody>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; white-space: nowrap;\" scope=\"row\">Euclidean<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Continuous numbers on the same scale<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Large values dominate, so scale first<\/td>\n<\/tr>\n<tr style=\"background: #f5f8fc;\">\n<th style=\"text-align: left; padding: 12px 16px; border-bottom: 1px solid #e5e9f0; color: #0f2a4a; white-space: nowrap;\" scope=\"row\">Manhattan<\/th>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Many features, or data with outliers<\/td>\n<td style=\"padding: 12px 16px; border-bottom: 1px solid #e5e9f0;\">Less natural for real world straight line distance<\/td>\n<\/tr>\n<tr style=\"background: #ffffff;\">\n<th style=\"text-align: left; padding: 12px 16px; color: #0f2a4a; white-space: nowrap;\" scope=\"row\">Hamming<\/th>\n<td style=\"padding: 12px 16px;\">Categorical features<\/td>\n<td style=\"padding: 12px 16px;\">Ignores how different the categories are<\/td>\n<\/tr>\n<\/tbody>\n<\/table>\n<\/div>\n<h2><strong><b>How to Choose the Value of K?<\/b><\/strong><\/h2>\n<p>The value of k changes the result more than anything else.<\/p>\n<ul>\n<li><b><\/b><strong><b>A small k<\/b><\/strong>, such as 1, follows the data very closely. It reacts to every noisy point, so it overfits. The decision boundary becomes jagged.<\/li>\n<li><b><\/b><strong><b>A large k<\/b><\/strong>smooths the boundary. If it is too large, it blurs real differences between classes and underfits.<\/li>\n<\/ul>\n<p>A few practical rules help. For two class problems, choose an odd k, so votes cannot tie. Do not guess. Try a range of values and pick the one with the best score on data the model has not trained on. The usual tool is cross validation, which repeats the test on several splits so one lucky split does not decide.<\/p>\n<p>The classic way to see this is the elbow method. Plot the error rate for each k. The error often drops fast, then flattens. The point where it stops improving much is a good choice.<\/p>\n<p>&nbsp;<\/p>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4795\" src=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN6.png\" alt=\"How to decide K value?\" width=\"850\" height=\"519\" srcset=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN6.png 581w, https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN6-300x183.png 300w\" sizes=\"auto, (max-width: 850px) 100vw, 850px\" \/><\/p>\n<p>&nbsp;<\/p>\n<h2><strong><b>Why Feature Scaling Matters So Much?<\/b><\/strong><\/h2>\n<p>Because KNN is based on distance, features with big numbers dominate. If one feature is income in rupees and another is age in years, a difference of 10,000 in income swamps a difference of 20 in age, and age is effectively ignored. Scaling puts every feature on a comparable range before distances are calculated. In the program below, the same model scores 0.722 without scaling and 0.963 with it, which is a very large jump from one line of preparation.<\/p>\n<p>One more point is easy to get wrong. Fit the scaler on the training data only, and then apply it to the test data. If you fit the scaler on the test data as well, information from the test set leaks into the model, and your score becomes too optimistic.<\/p>\n<p>&nbsp;<\/p>\n<h2><strong><b>KNN in Python With scikit learn<\/b><\/strong><\/h2>\n<p>This program uses the Wine dataset that comes with scikit learn, which has 178 wines described by 13 chemical measurements and labelled with one of three types. It has three parts: a test of scaling, a search for the best k using cross validation, and a grid search over k, the distance measure and the voting style.<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #0f2a4a; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">python<\/div>\n<pre style=\"margin: 0; padding: 16px; background: #f5f8fc; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre;\">from sklearn.datasets import load_wine\r\nfrom sklearn.model_selection import train_test_split, GridSearchCV, cross_val_score\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nfrom sklearn.pipeline import make_pipeline\r\nfrom sklearn.preprocessing import StandardScaler\r\n\r\nX, y = load_wine(return_X_y=True)\r\nX_train, X_test, y_train, y_test = train_test_split(\r\n    X, y, test_size=0.3, random_state=0, stratify=y\r\n)\r\n\r\n# Part 1: why scaling matters\r\nraw = KNeighborsClassifier(n_neighbors=5).fit(X_train, y_train)\r\nscaled = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=5)).fit(X_train, y_train)\r\nprint(\"Without scaling:\", round(raw.score(X_test, y_test), 3))\r\nprint(\"With scaling:   \", round(scaled.score(X_test, y_test), 3))\r\n\r\n# Part 2: choosing k with cross validation on the training set\r\nprint(\"k  cv accuracy\")\r\nbest_k, best = 1, 0\r\nfor k in range(1, 22, 2):\r\n    model = make_pipeline(StandardScaler(), KNeighborsClassifier(n_neighbors=k))\r\n    score = cross_val_score(model, X_train, y_train, cv=5).mean()\r\n    print(k, round(score, 3))\r\n    if score &gt; best:\r\n        best_k, best = k, score\r\nprint(\"Best k:\", best_k)\r\n\r\n# Part 3: grid search over k, distance metric and weighting\r\npipe = make_pipeline(StandardScaler(), KNeighborsClassifier())\r\ngrid = GridSearchCV(pipe, {\r\n    \"kneighborsclassifier__n_neighbors\": [1, 3, 5, 7, 9, 11],\r\n    \"kneighborsclassifier__metric\": [\"euclidean\", \"manhattan\"],\r\n    \"kneighborsclassifier__weights\": [\"uniform\", \"distance\"],\r\n}, cv=5)\r\ngrid.fit(X_train, y_train)\r\nprint(\"Best settings:\", grid.best_params_)\r\nprint(\"Best cv accuracy:\", round(grid.best_score_, 3))\r\nprint(\"Test accuracy:\", round(grid.score(X_test, y_test), 3))<\/pre>\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; background: #ffffff; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre;\">Without scaling: 0.722\r\nWith scaling:    0.963\r\nk  cv accuracy\r\n1 0.92\r\n3 0.928\r\n5 0.944\r\n7 0.944\r\n9 0.952\r\n11 0.96\r\n13 0.944\r\n15 0.944\r\n17 0.96\r\n19 0.96\r\n21 0.968\r\nBest k: 21\r\nBest settings: {'kneighborsclassifier__metric': 'manhattan', 'kneighborsclassifier__n_neighbors': 9, 'kneighborsclassifier__weights': 'distance'}\r\nBest cv accuracy: 0.968\r\nTest accuracy: 0.981<\/pre>\n<\/div>\n<h3><strong><b>Part 1: The Effect of Scaling<\/b><\/strong><\/h3>\n<p>When I ran the program, the first part printed:<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; background: #ffffff; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre;\">Without scaling: 0.722\r\nWith scaling:    0.963<\/pre>\n<\/div>\n<p>The test set has 54 wines, so that is 39 correct against 52 correct. The Wine data is a good example because one measurement, proline, runs into the hundreds while others are below 1. Without scaling, proline decides almost everything.<\/p>\n<h3><strong><b>Part 2: Choosing k With Cross Validation<\/b><\/strong><\/h3>\n<p>The second part tried the odd values of k from 1 to 21 using 5 fold cross validation on the training set:<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; background: #ffffff; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre;\">k   cv accuracy\r\n1   0.92\r\n3   0.928\r\n5   0.944\r\n7   0.944\r\n9   0.952\r\n11  0.96\r\n13  0.944\r\n15  0.944\r\n17  0.96\r\n19  0.96\r\n21  0.968\r\n\r\nBest k: 21<\/pre>\n<\/div>\n<p><img loading=\"lazy\" decoding=\"async\" class=\"aligncenter wp-image-4908\" src=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN6-1.png\" alt=\"knn implementation in python\" width=\"850\" height=\"519\" srcset=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN6-1.png 581w, https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN6-1-300x183.png 300w\" sizes=\"auto, (max-width: 850px) 100vw, 850px\" \/><\/p>\n<ul>\n<li><b><\/b><strong><b>Very small k does worse.<\/b><\/strong>With k equal to 1 the score is 0.92, the lowest on the list, because one noisy neighbour decides.<\/li>\n<li><b><\/b><strong><b>The scores then plateau.<\/b><\/strong>From k of 5 onward, results sit between 0.944 and 0.968.<\/li>\n<li><b><\/b><strong><b>Do not over read the winner.<\/b><\/strong>The training set has only 124 wines, and the gap between k of 11 and k of 21 is about one wine. The best k landed on the edge of the range I tried, so a wider search could pick a different value. Treat k as anywhere on the plateau, not as a precise answer.<\/li>\n<\/ul>\n<h3><strong><b>Part 3: Grid Search<\/b><\/strong><\/h3>\n<p>The last part searched k, the distance measure and the weighting together. The weights setting decides whether every neighbour counts equally or closer neighbours count more:<\/p>\n<div style=\"margin: 20px 0; border: 1px solid #d9e0ea; border-radius: 8px; overflow: hidden;\">\n<div style=\"background: #1f2937; color: #ffffff; font-family: Arial,Helvetica,sans-serif; font-size: 14px; font-weight: bold; padding: 8px 16px;\">output<\/div>\n<pre style=\"margin: 0; padding: 16px; background: #ffffff; color: #1f2937; font-family: 'Courier New',Courier,monospace; font-size: 14px; line-height: 1.7; overflow-x: auto; white-space: pre;\">Best settings: {'kneighborsclassifier__metric': 'manhattan', 'kneighborsclassifier__n_neighbors': 9, 'kneighborsclassifier__weights': 'distance'}\r\nBest cv accuracy: 0.968\r\nTest accuracy: 0.981<\/pre>\n<\/div>\n<p>The grid search chose Manhattan distance, 9 neighbours and distance weighting, and scored 0.981 on the test set, or 53 of 54 wines. That is one wine better than the plain scaled model, so it is a small gain. It is a useful example of the method, and not proof that Manhattan beats Euclidean in general.<\/p>\n<h2><strong><b>KNN for Regression<\/b><\/strong><\/h2>\n<p>The original page uses a regression version, so here is how it differs. Use KNeighborsRegressor, which predicts the average of the k nearest values. Judge it with an error measure such as RMSE, the square root of the average squared error, and not with accuracy. The rules about scaling, choosing k and fitting the scaler on training data only stay exactly the same.<\/p>\n<p>One caution applies to grid search. GridSearchCV uses the model&#8217;s default score, which for a regressor is R squared, not RMSE. If you want to choose k by RMSE, set the scoring option to neg_root_mean_squared_error. Otherwise the two methods can pick different values of k.<\/p>\n<h2><strong><b>Strengths and Limitations of KNN<\/b><\/strong><\/h2>\n<h3><strong><b>Strengths<\/b><\/strong><\/h3>\n<ul>\n<li>Easy to understand and explain.<\/li>\n<li>No training step, so new data can be added at any time.<\/li>\n<li>Works for both classification and regression.<\/li>\n<li>Makes no assumption about the shape of the data.<\/li>\n<li>A strong baseline to beat with more complex models.<\/li>\n<\/ul>\n<h3><strong><b>Limitations<\/b><\/strong><\/h3>\n<ul>\n<li><b><\/b><strong><b>Slow predictions on large data. <\/b><\/strong>Every prediction compares the new point with all stored points.<\/li>\n<li><b><\/b><strong><b>Needs memory. <\/b><\/strong>The whole training set must be kept.<\/li>\n<li><b><\/b><strong><b>Sensitive to scale. <\/b><\/strong>Unscaled features can ruin results.<\/li>\n<li><b><\/b><strong><b>Struggles with many features. <\/b><\/strong>In very high dimensions, points all look about equally far apart, so neighbours stop meaning much. This is called the curse of dimensionality.<\/li>\n<li><b><\/b><strong><b>Affected by noise and imbalanced classes. <\/b><\/strong>A common class can drown out a rare one.<\/li>\n<\/ul>\n<h2><strong><b>Where KNN is Used?<\/b><\/strong><\/h2>\n<ul>\n<li><b><\/b><strong><b>Recommendation systems. <\/b><\/strong>Suggesting products based on what similar customers bought.<\/li>\n<li><b><\/b><strong><b>Document and text search. <\/b><\/strong>Finding documents closest to a query.<\/li>\n<li><b><\/b><strong><b>Image recognition. <\/b><\/strong>Matching small images to known examples.<\/li>\n<li><b><\/b><strong><b>Credit and risk scoring. <\/b><\/strong>Comparing an applicant to similar past cases.<\/li>\n<li><b><\/b><strong><b>Missing value filling. <\/b><\/strong>Replacing a gap with the typical value among the nearest records.<\/li>\n<\/ul>\n<h2><strong><b>Common Mistakes to Avoid<\/b><\/strong><\/h2>\n<ul>\n<li><b><\/b><strong><b>Forgetting to scale. <\/b><\/strong>This is the number one KNN mistake, and the example above shows the cost.<\/li>\n<li><b><\/b><strong><b>Fitting the scaler on the test data. <\/b><\/strong>It leaks information and inflates your score.<\/li>\n<li><b><\/b><strong><b>Picking k by guess. <\/b><\/strong>Test a range with cross validation.<\/li>\n<li><b><\/b><strong><b>Using an even k on a two class problem. <\/b><\/strong>Votes can tie.<\/li>\n<li><b><\/b><strong><b>Using too many features. <\/b><\/strong>Remove features that carry no information.<\/li>\n<li><b><\/b><strong><b>Using KNN on very large data without a plan. <\/b><\/strong>Prediction time will grow quickly.<\/li>\n<\/ul>\n<p>KNN is simple, honest and easy to explain. It asks one question: who are your closest neighbours? Run the program above on your own data, scale before you measure distance, and choose k with cross validation. If predictions turn out too slow or accuracy plateaus, that is the time to look at models such as SVM or random forest.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>K Nearest Neighbors Algorithm Tutorial When you move to a new city and look for a good restaurant, you do not study cuisine theory. You ask the people who live closest to you what they like. If most of your neighbours recommend the same place, you go there. The k nearest neighbors algorithm, usually shortened [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[32,1696],"tags":[436,433,432,434,435],"class_list":["post-4789","post","type-post","status-publish","format-standard","hentry","category-machine-learning","category-machine-learning-modules","tag-benefits-of-knn","tag-how-knn-algorithm-works","tag-k-nearest-neighbors-algorithm-tutorial","tag-knn-algorithm-introduction","tag-knn-implementation-in-python"],"acf":[],"yoast_head":"<!-- This site is optimized with the Yoast SEO plugin v25.7 - https:\/\/yoast.com\/wordpress\/plugins\/seo\/ -->\n<title>K Nearest Neighbors Algorithm Tutorial With Python | Prwatech<\/title>\n<meta name=\"description\" content=\"Learn how KNN classifies data, how Euclidean, Manhattan and Hamming distances work, how to choose k, and run a tested Python example with scikit learn.\" \/>\n<meta name=\"robots\" content=\"index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1\" \/>\n<link rel=\"canonical\" href=\"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/\" \/>\n<meta property=\"og:locale\" content=\"en_US\" \/>\n<meta property=\"og:type\" content=\"article\" \/>\n<meta property=\"og:title\" content=\"K Nearest Neighbors Algorithm Tutorial With Python | Prwatech\" \/>\n<meta property=\"og:description\" content=\"Learn how KNN classifies data, how Euclidean, Manhattan and Hamming distances work, how to choose k, and run a tested Python example with scikit learn.\" \/>\n<meta property=\"og:url\" content=\"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/\" \/>\n<meta property=\"og:site_name\" content=\"Prwatech\" \/>\n<meta property=\"article:publisher\" content=\"https:\/\/www.facebook.com\/prwatech.in\/\" \/>\n<meta property=\"article:published_time\" content=\"2026-10-15T10:39:53+00:00\" \/>\n<meta property=\"article:modified_time\" content=\"2026-10-16T15:50:58+00:00\" \/>\n<meta property=\"og:image\" content=\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN1.png\" \/>\n\t<meta property=\"og:image:width\" content=\"350\" \/>\n\t<meta property=\"og:image:height\" content=\"255\" \/>\n\t<meta property=\"og:image:type\" content=\"image\/png\" \/>\n<meta name=\"author\" content=\"Prwatech\" \/>\n<meta name=\"twitter:card\" content=\"summary_large_image\" \/>\n<meta name=\"twitter:creator\" content=\"@Eduprwatech\" \/>\n<meta name=\"twitter:site\" content=\"@Eduprwatech\" \/>\n<meta name=\"twitter:label1\" content=\"Written by\" \/>\n\t<meta name=\"twitter:data1\" content=\"Prwatech\" \/>\n\t<meta name=\"twitter:label2\" content=\"Est. reading time\" \/>\n\t<meta name=\"twitter:data2\" content=\"9 minutes\" \/>\n<script type=\"application\/ld+json\" class=\"yoast-schema-graph\">{\"@context\":\"https:\/\/schema.org\",\"@graph\":[{\"@type\":\"WebPage\",\"@id\":\"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/\",\"url\":\"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/\",\"name\":\"K Nearest Neighbors Algorithm Tutorial With Python | Prwatech\",\"isPartOf\":{\"@id\":\"https:\/\/prwatech.in\/blog\/#website\"},\"primaryImageOfPage\":{\"@id\":\"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/#primaryimage\"},\"image\":{\"@id\":\"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/#primaryimage\"},\"thumbnailUrl\":\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN1.png\",\"datePublished\":\"2026-10-15T10:39:53+00:00\",\"dateModified\":\"2026-10-16T15:50:58+00:00\",\"author\":{\"@id\":\"https:\/\/prwatech.in\/blog\/#\/schema\/person\/db90baff7744090b2288bbc98fea87f3\"},\"description\":\"Learn how KNN classifies data, how Euclidean, Manhattan and Hamming distances work, how to choose k, and run a tested Python example with scikit learn.\",\"breadcrumb\":{\"@id\":\"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/#breadcrumb\"},\"inLanguage\":\"en-US\",\"potentialAction\":[{\"@type\":\"ReadAction\",\"target\":[\"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/\"]}]},{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/#primaryimage\",\"url\":\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN1.png\",\"contentUrl\":\"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN1.png\",\"width\":350,\"height\":255},{\"@type\":\"BreadcrumbList\",\"@id\":\"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/#breadcrumb\",\"itemListElement\":[{\"@type\":\"ListItem\",\"position\":1,\"name\":\"Home\",\"item\":\"https:\/\/prwatech.in\/blog\/\"},{\"@type\":\"ListItem\",\"position\":2,\"name\":\"k-Nearest Neighbors Algorithm Tutorial\"}]},{\"@type\":\"WebSite\",\"@id\":\"https:\/\/prwatech.in\/blog\/#website\",\"url\":\"https:\/\/prwatech.in\/blog\/\",\"name\":\"Prwatech\",\"description\":\"Share Ideas, Start Something Good.\",\"potentialAction\":[{\"@type\":\"SearchAction\",\"target\":{\"@type\":\"EntryPoint\",\"urlTemplate\":\"https:\/\/prwatech.in\/blog\/?s={search_term_string}\"},\"query-input\":{\"@type\":\"PropertyValueSpecification\",\"valueRequired\":true,\"valueName\":\"search_term_string\"}}],\"inLanguage\":\"en-US\"},{\"@type\":\"Person\",\"@id\":\"https:\/\/prwatech.in\/blog\/#\/schema\/person\/db90baff7744090b2288bbc98fea87f3\",\"name\":\"Prwatech\",\"image\":{\"@type\":\"ImageObject\",\"inLanguage\":\"en-US\",\"@id\":\"https:\/\/prwatech.in\/blog\/#\/schema\/person\/image\/\",\"url\":\"https:\/\/secure.gravatar.com\/avatar\/c00bafc1b04045f31eda917de39891456c44fa47c092b9bb6be0f860a3a30a2f?s=96&d=mm&r=g\",\"contentUrl\":\"https:\/\/secure.gravatar.com\/avatar\/c00bafc1b04045f31eda917de39891456c44fa47c092b9bb6be0f860a3a30a2f?s=96&d=mm&r=g\",\"caption\":\"Prwatech\"},\"url\":\"https:\/\/prwatech.in\/blog\/author\/prwatech123\/\"}]}<\/script>\n<!-- \/ Yoast SEO plugin. -->","yoast_head_json":{"title":"K Nearest Neighbors Algorithm Tutorial With Python | Prwatech","description":"Learn how KNN classifies data, how Euclidean, Manhattan and Hamming distances work, how to choose k, and run a tested Python example with scikit learn.","robots":{"index":"index","follow":"follow","max-snippet":"max-snippet:-1","max-image-preview":"max-image-preview:large","max-video-preview":"max-video-preview:-1"},"canonical":"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/","og_locale":"en_US","og_type":"article","og_title":"K Nearest Neighbors Algorithm Tutorial With Python | Prwatech","og_description":"Learn how KNN classifies data, how Euclidean, Manhattan and Hamming distances work, how to choose k, and run a tested Python example with scikit learn.","og_url":"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/","og_site_name":"Prwatech","article_publisher":"https:\/\/www.facebook.com\/prwatech.in\/","article_published_time":"2026-10-15T10:39:53+00:00","article_modified_time":"2026-10-16T15:50:58+00:00","og_image":[{"width":350,"height":255,"url":"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN1.png","type":"image\/png"}],"author":"Prwatech","twitter_card":"summary_large_image","twitter_creator":"@Eduprwatech","twitter_site":"@Eduprwatech","twitter_misc":{"Written by":"Prwatech","Est. reading time":"9 minutes"},"schema":{"@context":"https:\/\/schema.org","@graph":[{"@type":"WebPage","@id":"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/","url":"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/","name":"K Nearest Neighbors Algorithm Tutorial With Python | Prwatech","isPartOf":{"@id":"https:\/\/prwatech.in\/blog\/#website"},"primaryImageOfPage":{"@id":"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/#primaryimage"},"image":{"@id":"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/#primaryimage"},"thumbnailUrl":"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN1.png","datePublished":"2026-10-15T10:39:53+00:00","dateModified":"2026-10-16T15:50:58+00:00","author":{"@id":"https:\/\/prwatech.in\/blog\/#\/schema\/person\/db90baff7744090b2288bbc98fea87f3"},"description":"Learn how KNN classifies data, how Euclidean, Manhattan and Hamming distances work, how to choose k, and run a tested Python example with scikit learn.","breadcrumb":{"@id":"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/#breadcrumb"},"inLanguage":"en-US","potentialAction":[{"@type":"ReadAction","target":["https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/"]}]},{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/#primaryimage","url":"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN1.png","contentUrl":"https:\/\/prwatech.in\/blog\/wp-content\/uploads\/2020\/02\/KNN1.png","width":350,"height":255},{"@type":"BreadcrumbList","@id":"https:\/\/prwatech.in\/blog\/machine-learning\/machine-learning-modules\/k-nearest-neighbors-algorithm-tutorial\/#breadcrumb","itemListElement":[{"@type":"ListItem","position":1,"name":"Home","item":"https:\/\/prwatech.in\/blog\/"},{"@type":"ListItem","position":2,"name":"k-Nearest Neighbors Algorithm Tutorial"}]},{"@type":"WebSite","@id":"https:\/\/prwatech.in\/blog\/#website","url":"https:\/\/prwatech.in\/blog\/","name":"Prwatech","description":"Share Ideas, Start Something Good.","potentialAction":[{"@type":"SearchAction","target":{"@type":"EntryPoint","urlTemplate":"https:\/\/prwatech.in\/blog\/?s={search_term_string}"},"query-input":{"@type":"PropertyValueSpecification","valueRequired":true,"valueName":"search_term_string"}}],"inLanguage":"en-US"},{"@type":"Person","@id":"https:\/\/prwatech.in\/blog\/#\/schema\/person\/db90baff7744090b2288bbc98fea87f3","name":"Prwatech","image":{"@type":"ImageObject","inLanguage":"en-US","@id":"https:\/\/prwatech.in\/blog\/#\/schema\/person\/image\/","url":"https:\/\/secure.gravatar.com\/avatar\/c00bafc1b04045f31eda917de39891456c44fa47c092b9bb6be0f860a3a30a2f?s=96&d=mm&r=g","contentUrl":"https:\/\/secure.gravatar.com\/avatar\/c00bafc1b04045f31eda917de39891456c44fa47c092b9bb6be0f860a3a30a2f?s=96&d=mm&r=g","caption":"Prwatech"},"url":"https:\/\/prwatech.in\/blog\/author\/prwatech123\/"}]}},"_links":{"self":[{"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/posts\/4789","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/comments?post=4789"}],"version-history":[{"count":14,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/posts\/4789\/revisions"}],"predecessor-version":[{"id":12013,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/posts\/4789\/revisions\/12013"}],"wp:attachment":[{"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/media?parent=4789"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/categories?post=4789"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/prwatech.in\/blog\/wp-json\/wp\/v2\/tags?post=4789"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}