## Load data
data(iris)
set.seed(123)
## seprate into training and test samples
idxs <- sample(1:nrow(iris),as.integer(0.7*nrow(iris)))
trainIris <- iris[idxs,]
testIris <- iris[-idxs,]
library(e1071)
nb_default <- naiveBayes(Species~., data=trainIris)
default_pred <- predict(nb_default, testIris, type="class")
table(default_pred, testIris$Species,dnn=c("Prediction","Actual"))
nb_laplace1 <- naiveBayes(Species~., data=trainIris, laplace=1)
laplace1_pred <- predict(nb_laplace1, testIris, type="class")
table(laplace1_pred, testIris$Species,dnn=c("Prediction","Actual"))
library(MASS)
lda_model <- lda(Species ~ ., # training model
trainIris,
prior = c(1,1,1)/3)
plda = predict(object = lda_model, newdata = testIris,)# predictions
## The resulting confusion matrix
table(testIris[,'Species'],plda$class)
library(caret) ## can use 'knn' function in package 'class' and 'train' function in package 'caret'
## train a model with different ks, need a lot of time ...
knn_fit <- train(Species ~ ., data = trainIris, method = "knn",
preProcess = c("center", "scale"),
tuneLength = 10)
knn_fit
plot(knn_fit)
test_pred <- predict(knn_fit, newdata = testIris)
## The resulting confusion matrix
table(testIris[,'Species'],test_pred)