Skip to content

Instantly share code, notes, and snippets.

@alpo-p
Created December 6, 2016 08:12
Show Gist options
  • Select an option

  • Save alpo-p/8bb0fdf689b26e60103ab765a391e7ea to your computer and use it in GitHub Desktop.

Select an option

Save alpo-p/8bb0fdf689b26e60103ab765a391e7ea to your computer and use it in GitHub Desktop.
K nearest neighbours, test with Iris dataset
iris <- read.csv(url("http://archive.ics.uci.edu/ml/machine-learning-databases/iris/iris.data"), header = FALSE)
View(iris)
names(iris) <- c("Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width", "Species")
library(ggvis)
iris %>% ggvis(~Sepal.Length, ~Sepal.Width, fill = ~Species) %>% layer_points()
iris %>% ggvis(~Petal.Length, ~Petal.Width, fill = ~Species) %>% layer_points()
prop.table(table(iris$Species))
library(class)
normalize <- function(x) {
num <- x - min(x)
denom <- max(x) - min(x)
return (num/denom)
}
iris_norm <- as.data.frame(lapply(iris[1:4], normalize))
summary(iris_norm)
set.seed(1234)
ind <- sample(2, nrow(iris), replace=TRUE, prob=c(0.67, 0.33)) #randomizing the sample
iris.training <- iris[ind==1, 1:4]
iris.test <- iris[ind==2, 1:4]
iris.trainLabels <- iris[ind==1, 5]
iris.testLabels <- iris[ind==2, 5]
iris_pred <- knn(train = iris.training, test = iris.test, cl = iris.trainLabels, k = 3)
library(gmodels)
CrossTable(x = iris.testLabels, y= iris_pred, prop.chisq = FALSE) #checking the results here; works perfect
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment