mtcars - Model Creation

khsarma
31-July-2018

Shiny App creation

mtcars Shiny app has sidebar layout with following inputs

  • Train control number - It's slider input and has values ranging from 1 to 3 and default being 2. This will be used in setting the train control parameters.
  • Algorithm Selection - User can select among 2 available algorithms - Random Forest (rf) and CART (using rpart).
  • Submit button - This is to prevent reactive statements.

Random Forest model creation

Consider User inputs provided in the following way: Train control number = 2 and Algorithm = rf Model will be created with cross-validation as “cv” as follows:

tctrl <- trainControl(method = "cv", number = 2)
trrf <- train(mpg~., data = mtcars, method = "rf", trControl = tctrl)
trrf$finalModel

Call:
 randomForest(x = x, y = y, mtry = param$mtry) 
               Type of random forest: regression
                     Number of trees: 500
No. of variables tried at each split: 6

          Mean of squared residuals: 5.437517
                    % Var explained: 84.55

CART model creation

Consider User inputs provided in the following way: Train control number = 3 and Algorithm = rpart Model will be created with cross-validation as “cv” as follows:

tctrl <- trainControl(method = "cv", number = 3)
trrpart <- train(mpg~., data = mtcars, method = "rpart", trControl = tctrl)
trrpart$finalModel
n= 32 

node), split, n, deviance, yval
      * denotes terminal node

1) root 32 1126.0470 20.09062  
  2) cyl>=5 21  198.4724 16.64762 *
  3) cyl< 5 11  203.3855 26.66364 *

Errors in Models

We can check errors in the models as given below:

trrf$results[,1:4] # Random forest errors
  mtry     RMSE  Rsquared      MAE
1    2 2.580062 0.8691189 2.055521
2    6 2.437052 0.8839377 1.953236
3   10 2.457468 0.8798759 1.997302
trrpart$results[,1:4] # rpart errors
          cp     RMSE  Rsquared      MAE
1 0.00000000 4.753113 0.4100473 3.854203
2 0.09748407 4.753113 0.4100473 3.854203
3 0.64312523 4.945888 0.4798589 4.352255