The Wayback Machine - https://web.archive.org/web/20240927015112/https://www.geeksforgeeks.org/k-nn-classifier-in-r-programming/
Open In App

KNN Classifier in R Programming

Last Updated : 20 Dec, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

K-Nearest Neighbor or KNN is a Supervised Non-linear classification algorithm. KNN in R Programming Language is a Non-parametric algorithm i.e. it doesn’t make any assumption about underlying data or its distribution.

KNN in R is one of the simplest and most widely used algorithms which depends on its k value(Neighbors) and finds its applications in many industries like the finance industry, healthcare industry, etc.

In KNN in R algorithm, K specifies the number of neighbors and its algorithm is as follows:

  • Choose the number K of the neighbor.
  • Take the K Nearest Neighbor of unknown data point according to distance.
  • Among the K-neighbors, Count the number of data points in each category.
  • Assign the new data point to a category, where you counted the most neighbors.

For the Nearest Neighbor classifier, the distance between two points is expressed in the form of

Euclidean Distance

Consider a dataset containing two features Red and Blue and we classify them. Here K is 5 i.e. we are considering 5 neighbors according to Euclidean distance.

So, when a new data point enters, out of 5 neighbors, 3 are Blue and 2 are Red. We assign the new data point to the category with most neighbors i.e Blue.

The Dataset

Iris dataset consists of 50 samples from each of 3 species of Iris(Iris setosa, Iris virginica, Iris versicolor) and a multivariate dataset introduced by British statistician and biologist Ronald Fisher in his 1936 paper The use of multiple measurements in taxonomic problems. Four features were measured from each sample i.e length and width of the sepals and petals and based on the combination of these four features, Fisher developed a linear discriminant model to distinguish the species from each other.

R




# Loading data
data(iris)
  
# Structure
str(iris)


Output:

'data.frame':    150 obs. of  5 variables:
$ Sepal.Length: num 5.1 4.9 4.7 4.6 5 5.4 4.6 5 4.4 4.9 ...
$ Sepal.Width : num 3.5 3 3.2 3.1 3.6 3.9 3.4 3.4 2.9 3.1 ...
$ Petal.Length: num 1.4 1.4 1.3 1.5 1.4 1.7 1.4 1.5 1.4 1.5 ...
$ Petal.Width : num 0.2 0.2 0.2 0.2 0.2 0.4 0.3 0.2 0.2 0.1 ...
$ Species : Factor w/ 3 levels "setosa","versicolor",..: 1 1 1 1 1 1 1 1 1 1 ...

Performing KNN in R

Using the KNN in R algorithm on the dataset which includes 11 persons and 6 variables or attributes.

R




# Installing Packages
install.packages("e1071")
install.packages("caTools")
install.packages("class")
   
# Loading package
library(e1071)
library(caTools)
library(class)
   
# Loading data
data(iris)
head(iris)


Output:

  Sepal.Length Sepal.Width Petal.Length Petal.Width Species
1 5.1 3.5 1.4 0.2 setosa
2 4.9 3.0 1.4 0.2 setosa
3 4.7 3.2 1.3 0.2 setosa
4 4.6 3.1 1.5 0.2 setosa
5 5.0 3.6 1.4 0.2 setosa
6 5.4 3.9 1.7 0.4 setosa

Splitting data into train and test data

R




# Splitting data into train and test data
split <- sample.split(iris, SplitRatio = 0.7)
train_cl <- subset(iris, split == "TRUE")
test_cl <- subset(iris, split == "FALSE")
 
# Feature Scaling
train_scale <- scale(train_cl[, 1:4])
test_scale <- scale(test_cl[, 1:4])
 
 
head(train_scale)
head(test_scale)


Output:

  Sepal.Length Sepal.Width Petal.Length Petal.Width
1 -0.9194427 0.98658863 -1.344451 -1.353762
2 -1.1631831 -0.14597485 -1.344451 -1.353762
4 -1.5287936 0.08053785 -1.287510 -1.353762
6 -0.5538322 1.89263942 -1.173627 -1.089470
7 -1.5287936 0.76007594 -1.344451 -1.221616
9 -1.7725339 -0.37248755 -1.344451 -1.353762

head(test_scale)

Sepal.Length Sepal.Width Petal.Length Petal.Width
3 -1.33191360 0.3559334 -1.367732 -1.240423
5 -0.97726205 1.2844553 -1.311982 -1.240423
8 -0.97726205 0.8201944 -1.256232 -1.240423
10 -1.09547923 0.1238029 -1.256232 -1.369410
13 -1.21369641 -0.1083276 -1.311982 -1.369410
15 -0.03152458 2.2129772 -1.423482 -1.240423

Fitting KNN Model

R




# Fitting KNN Model to training dataset
classifier_knn <- knn(train = train_scale,
                      test = test_scale,
                      cl = train_cl$Species,
                      k = 1)
classifier_knn


Output:

 [1] setosa     setosa     setosa     setosa     setosa     setosa    
[7] setosa setosa setosa setosa setosa setosa
[13] setosa setosa setosa setosa setosa setosa
[19] setosa setosa versicolor virginica versicolor versicolor
[25] versicolor versicolor versicolor versicolor virginica versicolor
[31] virginica versicolor versicolor versicolor versicolor versicolor
[37] versicolor versicolor versicolor versicolor virginica virginica
[43] virginica virginica virginica virginica virginica versicolor
[49] virginica virginica virginica virginica virginica versicolor
[55] virginica virginica virginica virginica virginica virginica
Levels: setosa versicolor virginica

Model classifier_knn(k=1): The KNN model is fitted with a train, test, and k value. Also, the Classifier Species feature is fitted in the model.

Confusiin Matrix

R




# Confusiin Matrix
cm <- table(test_cl$Species, classifier_knn)
cm


Output:

            classifier_knn
setosa versicolor virginica
setosa 20 0 0
versicolor 0 17 3
virginica 0 2 18

Confusion Matrix: So, 20 Setosa are correctly classified as Setosa. Out of 20 Versicolor, 17 Versicolor are correctly classified as Versicolor and 3 are classified as virginica. Out of 20 virginica, 17 virginica are correctly classified as virginica and 3 are classified as Versicolor.

Model Evaluation for different K values

R




# Model Evaluation - Choosing K
# Calculate out of Sample error
misClassError <- mean(classifier_knn != test_cl$Species)
print(paste('Accuracy =', 1-misClassError))
   
# K = 3
classifier_knn <- knn(train = train_scale,
                      test = test_scale,
                      cl = train_cl$Species,
                      k = 3)
misClassError <- mean(classifier_knn != test_cl$Species)
print(paste('Accuracy =', 1-misClassError))
   
# K = 5
classifier_knn <- knn(train = train_scale,
                      test = test_scale,
                      cl = train_cl$Species,
                      k = 5)
misClassError <- mean(classifier_knn != test_cl$Species)
print(paste('Accuracy =', 1-misClassError))
   
# K = 7
classifier_knn <- knn(train = train_scale,
                      test = test_scale,
                      cl = train_cl$Species,
                      k = 7)
misClassError <- mean(classifier_knn != test_cl$Species)
print(paste('Accuracy =', 1-misClassError))
   
# K = 15
classifier_knn <- knn(train = train_scale,
                      test = test_scale,
                      cl = train_cl$Species,
                      k = 15)
misClassError <- mean(classifier_knn != test_cl$Species)
print(paste('Accuracy =', 1-misClassError))
   
# K = 19
classifier_knn <- knn(train = train_scale,
                      test = test_scale,
                      cl = train_cl$Species,
                      k = 19)
misClassError <- mean(classifier_knn != test_cl$Species)
print(paste('Accuracy =', 1-misClassError))


Output:

[1] "Accuracy = 0.916666666666667"

K = 3

[1] "Accuracy = 0.966666666666667"

K = 5

[1] "Accuracy = 0.966666666666667"

K = 7

[1] "Accuracy = 0.966666666666667"

K = 15

[1] "Accuracy = 0.966666666666667"

K = 19

[1] "Accuracy = 0.966666666666667"

The model achieved 95% accuracy with k is 19 which is more than when k was 1, 3, 5, and 7. Its same accuracy when k was 15 which means now increasing k values doesn’t affect the accuracy.

So, K Nearest Neighbor is widely used in the industry.

R




library(ggplot2)
 
# Data preparation
k_values <- c(1, 3, 5, 7, 15, 19)
 
# Calculate accuracy for each k value
accuracy_values <- sapply(k_values, function(k) {
  classifier_knn <- knn(train = train_scale,
                        test = test_scale,
                        cl = train_cl$Species,
                        k = k)
  1 - mean(classifier_knn != test_cl$Species)
})
 
# Create a data frame for plotting
accuracy_data <- data.frame(K = k_values, Accuracy = accuracy_values)
 
# Plotting
ggplot(accuracy_data, aes(x = K, y = Accuracy)) +
  geom_line(color = "lightblue", size = 1) +
  geom_point(color = "lightgreen", size = 3) +
  labs(title = "Model Accuracy for Different K Values",
       x = "Number of Neighbors (K)",
       y = "Accuracy") +
  theme_minimal()


Output:

gh

KNN Classifier in R Programming

  1. Model Evaluation:(k=1) The model achieved 90% accuracy with k is 1.
  2. (K=3) The model achieved 88.33% accuracy with k is 3 which is lower than when k was 1.
  3. (K=5) The model achieved 91.66% accuracy with k is 5 which is more than when k was 1 and 3.
  4. (K=7) The model achieved 93.33% accuracy with k is 7 which is more than when k was 1, 3, and 5.
  5. (K=15) The model achieved 95% accuracy with k is 15 which is more than when k was 1, 3, 5, and 7.
  6. (K=19) The model achieved 95% accuracy with k is 19 which is more than when k was 1, 3, 5, and 7.

Its same accuracy when k was 15 which means now increasing k values doesn’t affect the accuracy. So, K Nearest Neighbor is widely used in the industry.



Previous Article
Next Article

Similar Reads

Naive Bayes Classifier in R Programming
Naive Bayes is a Supervised Non-linear classification algorithm in R Programming. Naive Bayes classifiers are a family of simple probabilistic classifiers based on applying Baye's theorem with strong(Naive) independence assumptions between the features or variables. The Naive Bayes algorithm is called "Naive" because it makes the assumption that th
3 min read
Predictions Multiple outcomes with KNN Model Using tidymodels
When dealing with classification problems that involve multiple classes or outcomes, it's essential to have a reliable method for making predictions. One popular algorithm for such tasks is k-Nearest Neighbors (k-NN). In this tutorial, we will walk you through the process of making predictions with multiple outcomes using a k-NN model in R, specifi
15+ min read
Support Vector Machine Classifier Implementation in R with Caret package
One of the most crucial aspects of machine learning that most data scientists run against in their careers is the classification problem. The goal of a classification algorithm is to foretell whether a particular activity will take place or not. Depending on the data available, classification algorithms strive to provide answers to questions like w
7 min read
What is the Relation Between R Programming and Hadoop Programming?
The relation between R programming and Hadoop revolves around integrating R with the Hadoop ecosystem to analyze large datasets that are stored in a Hadoop environment. R, primarily used for statistical analysis and data visualization, is not inherently built for handling big data. However, when combined with Hadoop, it can leverage Hadoop's distri
3 min read
Getting the Modulus of the Determinant of a Matrix in R Programming - determinant() Function
determinant() function in R Language is a generic function that returns separately the modulus of the determinant, optionally on the logarithm scale, and the sign of the determinant. Syntax: determinant(x, logarithm = TRUE, ...) Parameters: x: matrix logarithm: if TRUE (default) return the logarithm of the modulus of the determinant Example 1: # R
2 min read
tidyr Package in R Programming
Packages in the R language are a collection of R functions, compiled code, and sample data. They are stored under a directory called “library” in the R environment. By default, R installs a set of packages during installation. One of the most important packages in R is the tidyr package. The sole purpose of the tidyr package is to simplify the proc
14 min read
Get Exclusive Elements between Two Objects in R Programming - setdiff() Function
setdiff() function in R Programming Language is used to find the elements which are in the first Object but not in the second Object. Syntax: setdiff(x, y) Parameters: x and y: Objects with sequence of itemsR - setdiff() Function ExampleExample 1: Apply setdiff to Numeric Vectors in R Language C/C++ Code # R program to illustrate # the use of setdi
2 min read
Add Leading Zeros to the Elements of a Vector in R Programming - Using paste0() and sprintf() Function
paste0() and sprintf() functions in R Language can also be used to add leading zeros to each element of a vector passed to it as argument. Syntax: paste0("0", vec) or sprintf("%0d", vec)Parameters: paste0: It will add zeros to vector sprintf: To format a vector(adding zeros) vec: Original vector dataReturns: Vectors by addition of leading zeros Exa
1 min read
Clustering in R Programming
Clustering in R Programming Language is an unsupervised learning technique in which the data set is partitioned into several groups called clusters based on their similarity. Several clusters of data are produced after the segmentation of data. All the objects in a cluster share common characteristics. During data mining and analysis, clustering is
6 min read
Compute Variance and Standard Deviation of a value in R Programming - var() and sd() Function
var() function in R Language computes the sample variance of a vector. It is the measure of how much value is away from the mean value. Syntax: var(x) Parameters: x : numeric vector Example 1: Computing variance of a vector # R program to illustrate # variance of vector # Create example vector x <- c(1, 2, 3, 4, 5, 6, 7) # Apply var function in
1 min read
Compute Density of the Distribution Function in R Programming - dunif() Function
dunif() function in R Language is used to provide the density of the distribution function. Syntax: dunif(x, min = 0, max = 1, log = FALSE) Parameters: x: represents vector min, max: represents lower and upper limits of the distribution log: represents logical value for probabilities Example 1: # Create vector of random deviation u <- runif(20)
1 min read
Compute Randomly Drawn F Density in R Programming - rf() Function
rf() function in R Language is used to compute random density for F Distribution. Syntax: rf(N, df1, df2) Parameters: N: Sample Size df: Degree of Freedom Example 1: # R Program to compute random values # of F Density # Setting seed for # random number generation set.seed(1000) # Set sample size N <- 20 # Calling rf() Function y <- rf(N, df1
1 min read
Data Handling in R Programming
R Programming Language is used for statistics and data analytics purposes. Importing and exporting of data is often used in all these applications of R programming. R language has the ability to read different types of files such as comma-separated values (CSV) files, text files, excel sheets and files, SPSS files, SAS files, etc. R allows its user
5 min read
Return a Matrix with Lower Triangle as TRUE values in R Programming - lower.tri() Function
lower.tri() function in R Language is used to return a matrix of logical values with lower triangle as TRUE. Syntax: lower.tri(x, diag) Parameters: x: Matrix object diag: Boolean value to include diagonal Example 1: # R program to print the # lower triangle of a matrix # Creating a matrix mat <- matrix(c(1:9), 3, 3, byrow = T) # Calling lower.tr
1 min read
Print the Value of an Object in R Programming - identity() Function
identity() function in R Language is used to print the value of the object which is passed to it as argument. Syntax: identity(x) Parameters: x: An Object Example 1: # R program to print # the value of an object # Creating a vector x <- c(1, 2, 3, 4) # Creating a list list1 <- list(letters[1:6]) # Calling the identity function identity(x) ide
1 min read
Check if Two Objects are Equal in R Programming - setequal() Function
setequal() function in R Language is used to check if two objects are equal. This function takes two objects like Vectors, dataframes, etc. as arguments and results in TRUE or FALSE, if the Objects are equal or not. Syntax: setequal(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of setequal(
1 min read
Random Forest with Parallel Computing in R Programming
Random Forest in R Programming is basically a bagging technique. From the name we can clearly interpret that this algorithm basically creates the forest with a lot of trees. It is a supervised classification algorithm. In a general scenario, if we have a greater number of trees in a forest it gives the best aesthetic appeal to all and is counted as
4 min read
R - Object Oriented Programming
In this article, we will discuss Object-Oriented Programming (OOPs) in R Programming Language. We will discuss the S3 and S4 classes, the inheritance in these classes, and the methods provided by these classes. OOPs in R Programming Language:In R programming, OOPs in R provide classes and objects as its key tools to reduce and manage the complexity
7 min read
Check for Presence of Common Elements between Objects in R Programming - is.element() Function
is.element() function in R Language is used to check if elements of first Objects are present in second Object or not. It returns TRUE for each equal value. Syntax: is.element(x, y) Parameters: x and y: Objects with sequence of items Example 1: # R program to illustrate # the use of is.element() function # Vector 1 x1 <- c(1, 2, 3) # Vector 2 x2
1 min read
AB Testing With R Programming
Split testing is another name of A/B testing and it's a common or general methodology. It's used online when one wants to test a new feature or a product. The main agenda over here is to design an experiment that gives repeatable results and robust to make an informed decision to launch it or not. Generally, this test includes a comparison of two w
7 min read
Check if Elements of a Vector are non-empty Strings in R Programming - nzchar() Function
nzchar() function in R Language is used to test whether elements of a character vector are non-empty strings. Syntax: nzchar(x) Parameters: x: character vector Example 1: # R program to illustrate # nzchar function # Initializing a character vector x <- c("GFG", "gfg") y <- c("a", "b", "c") #
1 min read
Finding the length of string in R programming - nchar() method
nchar() method in R Programming Language is used to get the length of a character in a string object. Syntax: nchar(string) Where: String is object. Return: Returns the length of a string. R - length of string using nchar() ExampleExample 1: Find the length of the string in R In this example, we are going to see how to get the length of a string ob
2 min read
Data Reshaping in R Programming
Generally, in R Programming Language, data processing is done by taking data as input from a data frame where the data is organized into rows and columns. Data frames are mostly used since extracting data is much simpler and hence easier. But sometimes we need to reshape the format of the data frame from the one we receive. Hence, in R, we can spli
5 min read
Plotting Graphs using Two Dimensional List in R Programming
List is a type of an object in R programming. Lists can contain heterogeneous elements like strings, numeric, matrices, or even lists. A list is a generic vector containing other objects. Two-dimensional list can be created in R programming by creating more lists in a list or simply, we can say nested lists. The list() function in R programming is
2 min read
Make Elements of a Vector Unique in R Programming - make.unique() Function
make.unique() function in R Language is used to return elements of a vector with unique names by appending sequence numbers to duplicates. Syntax: make.unique(names, sep)Parameters: names: Character vector with duplicate names sep: Separator to be used Example 1: C/C++ Code # R program to make unique vectors # Calling make.unique() Function make.un
1 min read
Get or Set Levels of a Factor in R Programming - levels() Function
levels() function in R Language is used to get or set the levels of a factor. Syntax: levels(x) Parameters: x: Factor Object Example 1: # R program to get levels of a factor # Creating a factor gender <- factor(c("female", "male", "male", "female")); gender # Calling levels() function # to get the levels l
1 min read
Compute the gamma value of a Non-negative Numeric Vector in R Programming - gamma() Function
gamma() function in R Language is used to compute the gamma value of a numeric vector using the gamma function. Gamma function is basically, gamma(x) = factorial(x - 1) Syntax: gamma(x) Parameters: x: Non-negative Numeric Vector Example 1: # R program to calculate the gamma value # Calling gamma Function gamma(2) gamma(3) gamma(5) Output: [1] 1 [1]
1 min read
Compute Choleski factorization of a Matrix in R Programming - chol() Function
chol() function in R Language is used to compute the Choleski factorization of a real symmetric positive-definite square matrix. Syntax: chol(x, ...)Parameters: x: an object for which a method exists. The default method applies to real symmetric, positive-definite matrices Example 1: C/C++ Code # R program to illustrate # chol function # Initializi
2 min read
Classes in R Programming
Classes and Objects are basic concepts of Object-Oriented Programming that revolve around the real-life entities. Everything in R is an object. An object is simply a data structure that has some methods and attributes. A class is just a blueprint or a sketch of these objects. It represents the set of properties or methods that are common to all obj
4 min read
Array Operations in R Programming
Arrays are the R data objects which store the data in more than two dimensions. Arrays are n-dimensional data structures. For example, if we create an array of dimensions (2, 3, 3) then it creates 3 rectangular matrices each with 2 rows and 3 columns. They are homogeneous data structures. Now, let’s see how to create arrays in R. To create an array
4 min read