Skip to content

Instantly share code, notes, and snippets.

@ranjiGT
Last active April 4, 2021 17:10
Show Gist options
  • Save ranjiGT/54085d71a8e612b88cd58fcbdbaebcf5 to your computer and use it in GitHub Desktop.
Save ranjiGT/54085d71a8e612b88cd58fcbdbaebcf5 to your computer and use it in GitHub Desktop.
KNN classifier in action
library(caret)
# Create training and test sets
set.seed(123)
trainIndex <- sample(c(FALSE,TRUE), size = nrow(dat), prob = c(.25,.75), replace = TRUE)
train_set <- dat[trainIndex, ]
test_set <- dat[!trainIndex, ]
# Learn KNN classifier
fit <- knn3Train(train_set %>% select(-y), test_set %>% select(-y), cl = train_set$y,
k = 3, prob = F)
tab <- table(actual = as.character(test_set$y), predicted = fit)
cm <- confusionMatrix(tab)
cm
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment