K-Nearest Neighbors (KNN)
Algoritma ‘K-nearest neighbor (KNN)’ merupakan algoritma ‘supervised learning’ di mana hasil kalsifikasi data baru berdasar kepada kategori mayoritas tetangga terdekat ke-K. Tujuan dari algoritma ini adalah mengklasifikasikan objek baru berdasarkan atribut dan data training. Klasifikasi dilakukan tanpa menggunakan model namun hanya berdasarkan memori.
Data
Import Data from R Datasets
Dataset ‘iris’ memberikan pengukuran dalam sentimeter dari variabel panjang dan lebar sepal serta panjang dan lebar petal, secara berturut-turut, untuk 50 bunga dari masing-masing 3 spesies iris. Spesies tersebut adalah Iris setosa, versicolor, dan virginica.
Dataset ‘iris’ merupakan dataset yang menampilkan data observasi 3 spesies anggrek dengan jumlah observasi tiap spesiesnya sebanyak 50 observasi.
# The datasets package needs to be loaded to access our data
# For a full list of these datasets, type library(help = "datasets")
library(datasets)
data(iris)
summary(iris)
## Sepal.Length Sepal.Width Petal.Length Petal.Width
## Min. :4.300 Min. :2.000 Min. :1.000 Min. :0.100
## 1st Qu.:5.100 1st Qu.:2.800 1st Qu.:1.600 1st Qu.:0.300
## Median :5.800 Median :3.000 Median :4.350 Median :1.300
## Mean :5.843 Mean :3.057 Mean :3.758 Mean :1.199
## 3rd Qu.:6.400 3rd Qu.:3.300 3rd Qu.:5.100 3rd Qu.:1.800
## Max. :7.900 Max. :4.400 Max. :6.900 Max. :2.500
## Species
## setosa :50
## versicolor:50
## virginica :50
##
##
##
Deskripsi variabel pada data ‘iris’.
Eksplorasi Data
Berdasarkan plot di atas dapat diketahui bahwa data 80% variabel dalam data iris adalah data kontinyu sedangkan 20% lainnya adalah data kategorik. Plot di atas juga menunjukkan bahwa tidak terdapat missing value dalam data ini.
library(dplyr)
library(ggplot2)
plotdata <- iris %>%
count(Species) %>%
arrange(desc(Species)) %>%
mutate(prop = round(n*100/sum(n), 1),
lab.ypos = cumsum(prop) - 0.5*prop)
# Pie Chart
ggplot(plotdata, aes(x = "", y = prop, fill = Species)) +
geom_bar(width = 1, stat = "identity", color = "white") +
coord_polar("y", start = 0)+
geom_text(aes(y = lab.ypos, label = prop), color = "black")+
theme_void()+
labs(title = "Persentase Species")
Pie Chart di atas menunjukkan persentase species setosa, versicolor, dan virginica dalam data iris.
Splitting Data
Splitting data menjadi data latih (training) dan data uji (testing) bertujuan untuk mengevaluasi kinerja model yang telah dibuat. Dengan membagi data menjadi data latih dan data uji, dapat diukur seberapa baik model yang dibangun dapat memprediksi data baru yang tidak digunakan selama proses latih. Data latih digunakan untuk melatih model, sementara Data uji digunakan untuk menguji seberapa baik model tersebut dapat melakukan prediksi yang akurat pada data yang tidak digunakan selama pelatihan.
1. Metode Hold-out
# Set the proportion of data to be used for training
train_proportion <- 0.7
# Determine the number of samples for training
num_train_samples <- round(nrow(iris) * train_proportion)
# Randomly sample row indices for the training set
train_indices <- sample(seq_len(nrow(iris)), size = num_train_samples, replace = FALSE)
# Create the training set
train_set <- iris[train_indices, ]
# Create the testing set by excluding the training indices
test_set <- iris[-train_indices, ]
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 102 5.8 2.7 5.1 1.9 virginica
## 71 5.9 3.2 4.8 1.8 versicolor
## 4 4.6 3.1 1.5 0.2 setosa
## 37 5.5 3.5 1.3 0.2 setosa
## 118 7.7 3.8 6.7 2.2 virginica
## 69 6.2 2.2 4.5 1.5 versicolor
## Sepal.Length Sepal.Width Petal.Length Petal.Width Species
## 2 4.9 3.0 1.4 0.2 setosa
## 8 5.0 3.4 1.5 0.2 setosa
## 12 4.8 3.4 1.6 0.2 setosa
## 23 4.6 3.6 1.0 0.2 setosa
## 24 5.1 3.3 1.7 0.5 setosa
## 29 5.2 3.4 1.4 0.2 setosa
2. Metode Stratified Sampling
# Install and load the caret package if you haven't already
# install.packages("caret")
library(caret)
# Set the proportion of data to be used for training
train_proportion <- 0.7
# Create the train/test indices with stratified sampling
train_index <- createDataPartition(iris$Species, p = train_proportion, list = FALSE, times = 1)
# Split the data into training and testing sets
train_set1 <- iris[train_index, ]
test_set1 <- iris[-train_index, ]
KNN
Using initial ‘K’
#The initial value for k is generally chosen as the square root of the number of observations.
initial_k <- sqrt(NROW(iris))
initial_k
## [1] 12.24745
Karena nilai inisial K yang diperoleh sebesar 12.24745, sehingga nilai K yang akan digunakan adalah 12 dan 13. Dengan hasil pemodelan sebagai berikut:
library(class)
# run KNN with k=12 and k=13
knn.12 <- knn(train=train_set[,-5], test=test_set[,-5], cl=train_set$Species, k=floor(initial_k))
# use confusion matrix to calculate accuracy
cf.12 <- confusionMatrix(test_set$Species,knn.12) # k = 12
cf.12
## Confusion Matrix and Statistics
##
## Reference
## Prediction setosa versicolor virginica
## setosa 15 0 0
## versicolor 0 14 3
## virginica 0 0 13
##
## Overall Statistics
##
## Accuracy : 0.9333
## 95% CI : (0.8173, 0.986)
## No Information Rate : 0.3556
## P-Value [Acc > NIR] : 5.426e-16
##
## Kappa : 0.9003
##
## Mcnemar's Test P-Value : NA
##
## Statistics by Class:
##
## Class: setosa Class: versicolor Class: virginica
## Sensitivity 1.0000 1.0000 0.8125
## Specificity 1.0000 0.9032 1.0000
## Pos Pred Value 1.0000 0.8235 1.0000
## Neg Pred Value 1.0000 1.0000 0.9062
## Prevalence 0.3333 0.3111 0.3556
## Detection Rate 0.3333 0.3111 0.2889
## Detection Prevalence 0.3333 0.3778 0.2889
## Balanced Accuracy 1.0000 0.9516 0.9062
knn.13 <- knn(train=train_set[,-5], test=test_set[,-5], cl=train_set$Species, k=ceiling(initial_k))
# use confusion matrix to calculate accuracy
cf.13 <- confusionMatrix(test_set$Species,knn.13) # k = 13
cf.13
## Confusion Matrix and Statistics
##
## Reference
## Prediction setosa versicolor virginica
## setosa 15 0 0
## versicolor 0 14 3
## virginica 0 0 13
##
## Overall Statistics
##
## Accuracy : 0.9333
## 95% CI : (0.8173, 0.986)
## No Information Rate : 0.3556
## P-Value [Acc > NIR] : 5.426e-16
##
## Kappa : 0.9003
##
## Mcnemar's Test P-Value : NA
##
## Statistics by Class:
##
## Class: setosa Class: versicolor Class: virginica
## Sensitivity 1.0000 1.0000 0.8125
## Specificity 1.0000 0.9032 1.0000
## Pos Pred Value 1.0000 0.8235 1.0000
## Neg Pred Value 1.0000 1.0000 0.9062
## Prevalence 0.3333 0.3111 0.3556
## Detection Rate 0.3333 0.3111 0.2889
## Detection Prevalence 0.3333 0.3778 0.2889
## Balanced Accuracy 1.0000 0.9516 0.9062
Berdasarkan akurasi dari data testing terlihat bahwa Model KNN (K=12) memiliki akurasi yang lebih baik dibandingkan dengan Model KNN (K=13) dalam memodelkan data ‘iris’.