Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
196 lines (163 sloc) 8.8 KB
title: "ExampleRun"
author: "Win-Vector LLC"
date: "June 1, 2016"
variant: markdown_github
This article is a demonstration the use of the [R]( [vtreat]( variable preparation package followed by [caret]( controlled training.
For discussion on this article please see [here]( Note we have since swithced to `xgboost` in this demonstration inspired by this [nice article](
In previous writings we have gone to great lengths to [document, explain and motivate `vtreat`]( That necessarily gets long and unnecessarily feels complicated.
In this example we are going to show what building a predictive model using `vtreat` best practices
looks like assuming you were somehow already in the habit of using vtreat for your data preparation step. We are deliberately not going to explain any steps, but just show the small number of steps we advise routinely using. This is a simple schematic, but not a guide. Of course we do not advise use without understanding (and we work hard to teach the concepts in our writing), but want what small effort is required to add `vtreat` to your predictive modeling practice.
First we set things up: load libraries, initialize parallel processing.
```{r setup, message=FALSE,warning=FALSE,results=FALSE}
library('WVPlots') # see
# parallel for vtreat
ncores <- parallel::detectCores()
parallelCluster <- parallel::makeCluster(ncores)
# parallel for caret
The we load our data for analysis. We are going to build a model predicting an income level from other demographic features. The data is taken from [here]( and you can perform all of the demonstrated steps if you download the contents of the [example git directory]( Obviously this has a lot of moving parts (R, R Markdown, Github, R packages, devtools)- but is very easy to do a second time (first time can be a bit of learning and preparation).
```{r loaddata}
# load data
# data from:
colnames <-
dTrain <- read.table(
header = FALSE,
sep = ',',
strip.white = TRUE,
stringsAsFactors = FALSE,
na.strings = c('NA', '?', '')
colnames(dTrain) <- colnames
dTest <- read.table(
skip = 1,
header = FALSE,
sep = ',',
strip.white = TRUE,
stringsAsFactors = FALSE,
na.strings = c('NA', '?', '')
colnames(dTest) <- colnames
Now we use `vtreat` to prepare the data for analysis. The goal of vtreat is to ensure a ready-to-dance data frame in a statistically valid manner. We are respecting the test/train split and building our data preparation plan only on the training data (though we do apply it to the test data). This step helps with a huge number of potential problems through automated repairs:
* re-encoding missing values
* dealing with large cardinality categorical variables
* dealing with novel levels
* fixing variable/column names to be "R safe"
* looking for strange column types
```{r model, cache=TRUE}
# define problem
yName <- 'class'
yTarget <- '>50K'
varNames <- setdiff(colnames,yName)
# build variable encoding plan and prepare simulated out of sample
# training fame (cross-frame)
cd <- vtreat::mkCrossFrameCExperiment(dTrain,varNames,yName,yTarget,
scoreFrame <- cd$treatments$scoreFrame
dTrainTreated <- cd$crossFrame
# pick our variables
newVars <- scoreFrame$varName[scoreFrame$sig<1/nrow(scoreFrame)]
dTestTreated <- vtreat::prepare(cd$treatments,dTest,
Now we train our model. In this case we are using the caret package to tune parameters.
```{r train, cache=TRUE}
# train our model using caret
# work around "levels must be valid R variable names issue"
dTrainTreated$yLogical = as.factor(paste0('v',as.character(dTrainTreated[[yName]]==yTarget)))
# from:
# could use accuracy as the tuning metric, but going to demonstrate using AUC
ctrl <- trainControl(method = "cv",
number = 5,
summaryFunction=twoClassSummary, # Use AUC to pick the best model
allowParallel = TRUE)
model <- train(x=dTrainTreated[,newVars],
dTest$pred <- predict(model,newdata=dTestTreated[,newVars],type='prob')[,'vTRUE']
Finally we take a look at the results on the held-out test data.
```{r score}
WVPlots::ROCPlot(dTest,'pred',yName,'predictions on test')
WVPlots::DoubleDensityPlot(dTest,'pred',yName,'predictions on test')
confusionMatrix <- table(truth=dTest[[yName]],pred=dTest$pred>=0.5)
testAccuarcy <- (confusionMatrix[1,1]+confusionMatrix[2,2])/sum(confusionMatrix)
Notice the achieved test accuracy is in the ballpark of what was reported for this dataset.
(From )
Error Accuracy reported as follows, after removal of unknowns from
| train/test sets):
| C4.5 : 84.46+-0.30
| Naive-Bayes: 83.88+-0.30
| NBTree : 85.90+-0.28
We can also compare accuracy on the "complete cases":
```{r completecases}
dTestComplete <- dTest[complete.cases(dTest[,varNames]),]
confusionMatrixComplete <- table(truth=dTestComplete[[yName]],
testAccuarcyComplete <- (confusionMatrixComplete[1,1]+confusionMatrixComplete[2,2])/
```{r cleanup}
# clean up
These two scores are [within noise bounds of each other](, but it is
our experience that missingness is often actually informative, so in addition to
imputing missing values you would like to preserve some notation indicating the missingness (which
`vtreat` does in fact do).
And that is all there is to this example. I'd like to emphasize that vtreat steps were only a few
lines in one of the blocks of code. `vtreat` treatment can take some time, but it is usually bearable. By design it is easy to add vtreat to your predictive analytics projects.
The point is: we got competitive results on real world data, in a single try (using vtreat to prepare data and caret to tune parameters). The job of the data scientist is to actually work longer on a problem and do better. But having a good start helps.
The theory behind vtreat is fairly important to the correctness of our implementation, and we would love for you to read through some of it:
* [vtreat: designing a package for variable treatment](
* [vtreat Cross Frames](
* [On Nested Models](
* [vtreat manuals](
* [Preparing data for analysis using R](
* [More on preparing data](
* [vtreat on Cran](
* [vtreat on Github](
But operationally, please think of `vtreat` as just adding a couple of lines to your analysis scripts. Again, the raw R markdown source can be found [here]( and a rendered copy (with results and graphs) [here](
You can’t perform that action at this time.