# Applying machine learning algorithms – exercises: solutions

Below are the solutions to these exercises on applying machine learning to your dataset.

#################### # # # Exercise 1 # # # #################### install.packages("caret") library(caret) data(iris) validation <- createDataPartition(iris$Species, p=0.80, list=FALSE) validation20 <- iris[-validation,] iris <- iris[validation,] library(caret) control <- trainControl(method="cv", number=10) #################### # # # Exercise 2 # # # #################### library(caret) control <- trainControl(method="cv", number=10) metric <- "Accuracy" #################### # # # Exercise 3 # # # #################### install.packages("rpart") install.packages("kernlab") install.packages("e1071") install.packages("randomForest") library(caret) library(rpart) library(kernlab) library(e1071) library(randomForest) # a) linear algorithms set.seed(7) fit.lda <- train(Species~., data=iris, method="lda", metric=metric, trControl=control) # b) nonlinear algorithms # CART set.seed(7) fit.cart <- train(Species~., data=iris, method="rpart", metric=metric, trControl=control) # kNN set.seed(7) fit.knn <- train(Species~., data=iris, method="knn", metric=metric, trControl=control) # c) advanced algorithms # SVM set.seed(7) fit.svm <- train(Species~., data=iris, method="svmRadial", metric=metric, trControl=control) # Random Forest set.seed(7) fit.rf <- train(Species~., data=iris, method="rf", metric=metric, trControl=control) #################### # # # Exercise 4 # # # #################### library(caret) library(rpart) library(kernlab) library(e1071) library(randomForest) results <- resamples(list(lda=fit.lda, cart=fit.cart, knn=fit.knn, svm=fit.svm, rf=fit.rf)) #################### # # # Exercise 5 # # # #################### library(caret) library(rpart) library(kernlab) library(e1071) library(randomForest) results <- resamples(list(lda=fit.lda, cart=fit.cart, knn=fit.knn, svm=fit.svm, rf=fit.rf)) summary(results) #################### # # # Exercise 6 # # # #################### library(caret) library(rpart) library(kernlab) library(e1071) library(randomForest) dotplot(results) #################### # # # Exercise 7 # # # #################### #LDA #################### # # # Exercise 8 # # # #################### library(caret) library(rpart) library(kernlab) library(e1071) library(randomForest) print(fit.lda) #################### # # # Exercise 9 # # # #################### library(caret) library(rpart) library(kernlab) library(e1071) library(randomForest) predictions <- predict(fit.lda, validation20) #################### # # # Exercise 10 # # # #################### library(caret) library(rpart) library(kernlab) library(e1071) library(randomForest) predictions <- predict(fit.lda, validation20) confusionMatrix(predictions, validation20$Species)