14.5 Model Building
20200607 We now build, fit, or train a model. R has most
machine learning algorithms available. We will begin with a simple
favourite—the decision tree algorithm— using
rpart::rpart(). We record this information using the generic
mdesc (human readable description of the model
mtype (type of the model).
<- "rpart" mtype <- "decision tree"mdesc
The model will be built using tidyselect::all_of()
the dplyr::select()’ed variables from the training
dplyr::slice() of the dataset. The training slice is
identified as the row numbers stored as
tr and the column
names stored as
vars. This training dataset is piped on to
rpart::rpart() together with a specification of the model to
be built as stored in
form. Using generic variables allows
us to change the formula, the dataset, the observations and the
variables used in building the model yet retain the same programming
code. The resulting model is saved into the variable
%>% ds select(all_of(vars)) %>% slice(tr) %>% rpart(form, .) -> model
To view the model simply reference the generic variable
model on the command line. This asks R to
base::print() the model.
## n= 134001 ## ## node), split, n, loss, yval, (yprob) ## * denotes terminal node ## ## 1) root 134001 28259 No (0.7891135 0.2108865) ## 2) humidity_3pm< 72.5 113994 16067 No (0.8590540 0.1409460) * ## 3) humidity_3pm>=72.5 20007 7815 Yes (0.3906133 0.6093867) ## 6) humidity_3pm< 82.5 10454 4894 No (0.5318538 0.4681462) ## 12) rainfall< 1.3 6211 2276 No (0.6335534 0.3664466) * ## 13) rainfall>=1.3 4243 1625 Yes (0.3829837 0.6170163) * ## 7) humidity_3pm>=82.5 9553 2255 Yes (0.2360515 0.7639485) *
This is our first predictive model. Be sure to spend some time to understand and reflect on the knowledge that the model is exposing.
Your donation will support ongoing development and give you access to the PDF version of this book. Desktop Survival Guides include Data Science, GNU/Linux, and MLHub. Books available on Amazon include Data Mining with Rattle and Essentials of Data Science. Popular open source software includes rattle, wajig, and mlhub. Hosted by Togaware, a pioneer of free and open source software since 1984.
Copyright © 1995-2021 Graham.Williams@togaware.com Creative Commons Attribution-ShareAlike 4.0.