KNN is a supervised learning algorithm that can be used for both classification and regression problems. The main idea behind KNN is to find the k-nearest data points to a given test data point and use these nearest neighbors to make a prediction. The value of k is a hyperparameter that needs to be tuned, and it represents the number of neighbors to consider.
For classification problems, the KNN algorithm assigns the test data point to the class that appears most frequently among the k-nearest neighbors. In other words, the class with the highest number of neighbors is the predicted class.
For regression problems, the KNN algorithm assigns the test data point the average of the k-nearest neighbors” values.
The distance metric used to measure the similarity between two data points is an essential factor that affects the KNN algorithm”s performance. The most commonly used distance metrics are Euclidean distance, Manhattan distance, and Minkowski distance.
Working of KNN Algorithm
The KNN algorithm can be summarized in the following steps −
-
Load the data − The first step is to load the dataset into memory. This can be done using various libraries such as pandas or numpy.
-
Split the data − The next step is to split the data into training and test sets. The training set is used to train the KNN algorithm, while the test set is used to evaluate its performance.
-
Normalize the data − Before training the KNN algorithm, it is essential to normalize the data to ensure that each feature contributes equally to the distance metric calculation.
-
Calculate distances − Once the data is normalized, the KNN algorithm calculates the distances between the test data point and each data point in the training set.
-
Select k-nearest neighbors − The KNN algorithm selects the k-nearest neighbors based on the distances calculated in the previous step.
-
Make a prediction − For classification problems, the KNN algorithm assigns the test data point to the class that appears most frequently among the k-nearest neighbors. For regression problems, the KNN algorithm assigns the test data point the average of the k-nearest neighbors” values.
-
Evaluate performance − Finally, the KNN algorithm”s performance is evaluated using various metrics such as accuracy, precision, recall, and F1-score.
Implementation in Python
Now that we have discussed the KNN algorithm”s theory, let”s implement it in Python using scikit-learn. Scikit-learn is a popular library for Machine Learning in Python and provides various algorithms for classification and regression problems.
We will use the Iris dataset, which is a popular dataset in Machine Learning and contains information about three different species of Iris flowers. The dataset has four features, including the sepal length, sepal width, petal length, and petal width, and a target variable, which is the species of the flower.
To implement KNN in Python, we need to follow the steps mentioned earlier. Here”s the Python code for implementing KNN on the Iris dataset −
Example
# import libraries from sklearn.datasets import load_iris from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler from sklearn.neighbors import KNeighborsClassifier from sklearn.metrics import accuracy_score # load the Iris dataset iris = load_iris() #split the data into training and test sets X_train, X_test, y_train, y_test = train_test_split(iris.data, iris.target, test_size=0.35, random_state=42) #normalize the data scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) #initialize the KNN algorithm knn = KNeighborsClassifier(n_neighbors=5) #train the KNN algorithm knn.fit(X_train, y_train) #make predictions on the test set y_pred = knn.predict(X_test) #evaluate the performance of the KNN algorithm accuracy = accuracy_score(y_test, y_pred) print("Accuracy: {:.2f}%".format(accuracy*100))
Output
When you execute this code, it will produce the following output −
Accuracy: 98.11%