Training Machine Learning model using Tree-based model

Overview

Teaching: 20 min
Exercises: 0 min
Questions
  • How to train a Machine Learning model using Tree-based model

Objectives
  • Learn to use different Tree-based algorithm for Machine Learning training

Supervised Learning training

Train model using Decision Tree

Spliting algorithm

Pros & Cons

image

Implementation

Here we will use iris data

library(caret)
data(iris)
set.seed(123)
indT <- createDataPartition(y=iris$Species,p=0.6,list=FALSE)
training <- iris[indT,]
testing  <- iris[-indT,]

Next we will train using method="rpart" with gini splitting algorithm:

ModFit_rpart <- train(Species~.,data=training,method="rpart",
                      parms = list(split = "gini"))
# gini can be replaced by chisquare, entropy, information

#fancier plot
library(rattle)
fancyRpartPlot(ModFit_rpart$finalModel)

image Apply decision tree model to predict output of testing data

predict_rpart <- predict(ModFit_rpart,testing)
confusionMatrix(predict_rpart, testing$Species)

testing$PredRight <- predict_rpart==testing$Species
ggplot(testing,aes(x=Petal.Width,y=Petal.Length))+
  geom_point(aes(col=PredRight))

image

Train model using Random Forest

image

Pros & Cons of Random Forest

image

Implementation of Random Forest

ModFit_rf <- train(Species~.,data=training,method="rf",prox=TRUE)

predict_rf <- predict(ModFit_rf,testing)
confusionMatrix(predict_rf, testing$Species)

testing$PredRight <- predict_rf==testing$Species
ggplot(testing,aes(x=Petal.Width,y=Petal.Length))+
  geom_point(aes(col=PredRight))

image

We can see that Random Forest result has better prediction than Decision Tree

Key Points

  • Decision Tree, Random Forest