DOI DOI CRAN_Status_Badge status

vtreat is a data.frame processor/conditioner (available for R, and for Python) that prepares real-world data for supervised machine learning or predictive modeling in a statistically sound manner.

vtreat takes an input data.frame that has a specified column called “the outcome variable” (or “y”) that is the quantity to be predicted (and must not have missing values). Other input columns are possible explanatory variables (typically numeric or categorical/string-valued, these columns may have missing values) that the user later wants to use to predict “y”. In practice such an input data.frame may not be immediately suitable for machine learning procedures that often expect only numeric explanatory variables, and may not tolerate missing values.

To solve this, vtreat builds a transformed data.frame where all explanatory variable columns have been transformed into a number of numeric explanatory variable columns, without missing values. The vtreat implementation produces derived numeric columns that capture most of the information relating the explanatory columns to the specified “y” or dependent/outcome column through a number of numeric transforms (indicator variables, impact codes, prevalence codes, and more). This transformed data.frame is suitable for a wide range of supervised learning methods from linear regression, through gradient boosted machines.

The idea is: you can take a data.frame of messy real world data and easily, faithfully, reliably, and repeatably prepare it for machine learning using documented methods using vtreat. Incorporating vtreat into your machine learning workflow lets you quickly work with very diverse structured data.

In all cases (classification, regression, unsupervised, and multinomial classification) the intent is that vtreat transforms are essentially one liners.

The preparation commands are organized as follows:

In all cases: variable preperation is intended to be a “one liner.”

These current revisions of the examples are designed to be small, yet complete. So as a set they have some overlap, but the user can rely mostly on a single example for a single task type.

For more detail please see here: arXiv:1611.09477 stat.AP (the documentation describes the R version, however all of the examples can be found worked in Python here).

vtreat is available as an R package, and also as a Python/Pandas package.

(logo: Julie Mount, source: “The Harvest” by Boris Kustodiev 1914)

Even with modern machine learning techniques (random forests, support vector machines, neural nets, gradient boosted trees, and so on) or standard statistical methods (regression, generalized regression, generalized additive models) there are common data issues that can cause modeling to fail. vtreat deals with a number of these in a principled and automated fashion.

In particular vtreat emphasizes a concept called “y-aware pre-processing” and implements:

The idea is: even with a sophisticated machine learning algorithm there are many ways messy real world data can defeat the modeling process, and vtreat helps with at least ten of them. We emphasize: these problems are already in your data, you simply build better and more reliable models if you attempt to mitigate them. Automated processing is no substitute for actually looking at the data, but vtreat supplies efficient, reliable, documented, and tested implementations of many of the commonly needed transforms.

To help explain the methods we have prepared some documentation:

Data treatments are “y-aware” (use distribution relations between independent variables and the dependent variable). For binary classification use designTreatmentsC() and for numeric regression use designTreatmentsN().

After the design step, prepare() should be used as you would use model.matrix. prepare() treated variables are all numeric and never take the value NA or +-Inf (so are very safe to use in modeling).

In application we suggest splitting your data into three sets: one for building vtreat encodings, one for training models using these encodings, and one for test and model evaluation.

The purpose of vtreat library is to reliably prepare data for supervised machine learning. We try to leave as much as possible to the machine learning algorithms themselves, but cover most of the truly necessary typically ignored precautions. The library is designed to produce a data.frame that is entirely numeric and takes common precautions to guard against the following real world data issues:

The above are all awful things that often lurk in real world data. Automating these steps ensures they are easy enough that you actually perform them and leaves the analyst time to look for additional data issues. For example this allowed us to essentially automate a number of the steps taught in chapters 4 and 6 of Practical Data Science with R (Zumel, Mount; Manning 2014) into a very short worksheet (though we think for understanding it is essential to work all the steps by hand as we did in the book). The 2nd edition of Practical Data Science with R covers using vtreat in R in chapter 8 “Advanced Data Preparation.”

The idea is: data.frames prepared with the vtreat library are somewhat safe to train on as some precaution has been taken against all of the above issues. Also of interest are the vtreat variable significances (help in initial variable pruning, a necessity when there are a large number of columns) and vtreat::prepare(scale=TRUE) which re-encodes all variables into effect units making them suitable for y-aware dimension reduction (variable clustering, or principal component analysis) and for geometry sensitive machine learning techniques (k-means, knn, linear SVM, and more). You may want to do more than the vtreat library does (such as Bayesian imputation, variable clustering, and more) but you certainly do not want to do less.

There have been a number of recent substantial improvements to the library, including:

Some of our related articles (which should make clear some of our motivations, and design decisions):

Examples of current best practice using vtreat (variable coding, train, test split) can be found here and here.

Trivial example:

 #  [1] '1.5.1'
 #  To cite package 'vtreat' in publications use:
 #    John Mount and Nina Zumel (2020). vtreat: A Statistically Sound
 #    'data.frame' Processor/Conditioner.
 #  A BibTeX entry for LaTeX users is
 #    @Manual{,
 #      title = {vtreat: A Statistically Sound 'data.frame' Processor/Conditioner},
 #      author = {John Mount and Nina Zumel},
 #      year = {2020},
 #      note = {,},
 #    }

# categorical example
dTrainC <- data.frame(x=c('a', 'a', 'a', 'b', 'b', NA, NA),
   z=c(1, 2, 3, 4, NA, 6, NA),
dTestC <- data.frame(x=c('a', 'b', 'c', NA), z=c(10, 20, 30, NA))

# help("designTreatmentsC")

treatmentsC <- designTreatmentsC(dTrainC, colnames(dTrainC), 'y', TRUE,
print(treatmentsC$scoreFrame[, c('origName', 'varName', 'code', 'rsq', 'sig', 'extraModelDegrees')])
 #    origName   varName  code          rsq        sig extraModelDegrees
 #  1        x    x_catP  catP 1.559780e-01 0.22202097                 2
 #  2        x    x_catB  catB 1.142159e-05 0.99166241                 2
 #  3        z         z clean 2.376018e-01 0.13176020                 0
 #  4        z   z_isBAD isBAD 2.960654e-01 0.09248399                 0
 #  5        x  x_lev_NA   lev 2.960654e-01 0.09248399                 0
 #  6        x x_lev_x_a   lev 1.300057e-01 0.26490379                 0
 #  7        x x_lev_x_b   lev 6.067337e-03 0.80967242                 0

# help("prepare")

dTrainCTreated <- prepare(treatmentsC, dTrainC, pruneSig=1.0, scale=TRUE)
 #  Warning in prepare.treatmentplan(treatmentsC, dTrainC, pruneSig = 1, scale =
 #  TRUE): possibly called prepare() on same data frame as designTreatments*()/
 #  mkCrossFrame*Experiment(), this can lead to over-fit. To avoid this, please use
 #  mkCrossFrame*Experiment$crossFrame.
varsC <- setdiff(colnames(dTrainCTreated), 'y')
# all input variables should be mean 0
sapply(dTrainCTreated[, varsC, drop=FALSE], mean)
 #         x_catP        x_catB             z       z_isBAD      x_lev_NA 
 #   2.537498e-16 -1.268826e-16  6.336166e-17  2.536414e-16 -2.537653e-16 
 #      x_lev_x_a     x_lev_x_b 
 #  -6.345680e-17  1.189718e-17
# all non NA slopes should be 1
sapply(varsC, function(c) { lm(paste('y', c, sep='~'),
 #      x_catP     x_catB          z    z_isBAD   x_lev_NA  x_lev_x_a  x_lev_x_b 
 #  0.23254609 0.05841932 0.16062145 0.03162633 0.03162633 0.23254609 0.24663035
dTestCTreated <- prepare(treatmentsC, dTestC, pruneSig=c(), scale=TRUE)
 #        x_catP    x_catB         z   z_isBAD  x_lev_NA  x_lev_x_a  x_lev_x_b
 #  1 -1.0238626 -3.248380  7.437329 -5.420438 -5.420438 -1.0238626  0.1158472
 #  2  0.7678969 -2.550396 18.374578 -5.420438 -5.420438  0.7678969 -0.2896179
 #  3  3.4555361 -2.260694 29.311827 -5.420438 -5.420438  0.7678969  0.1158472
 #  4  0.7678969  7.422967  0.000000 13.551095 13.551095  0.7678969  0.1158472
# numeric example
dTrainN <- data.frame(x=c('a', 'a', 'a', 'a', 'b', 'b', NA, NA),
   z=c(1, 2, 3, 4, 5, NA, 7, NA), y=c(0, 0, 0, 1, 0, 1, 1, 1))
dTestN <- data.frame(x=c('a', 'b', 'c', NA), z=c(10, 20, 30, NA))
# help("designTreatmentsN")
treatmentsN = designTreatmentsN(dTrainN, colnames(dTrainN), 'y',
print(treatmentsN$scoreFrame[, c('origName', 'varName', 'code', 'rsq', 'sig', 'extraModelDegrees')])
 #    origName   varName  code          rsq       sig extraModelDegrees
 #  1        x    x_catP  catP 7.174888e-02 0.5212691                 2
 #  2        x    x_catN  catN 1.950163e-03 0.9173064                 2
 #  3        x    x_catD  catD 3.743113e-01 0.1069707                 2
 #  4        z         z clean 2.880952e-01 0.1701892                 0
 #  5        z   z_isBAD isBAD 3.333333e-01 0.1339746                 0
 #  6        x  x_lev_NA   lev 3.333333e-01 0.1339746                 0
 #  7        x x_lev_x_a   lev 2.500000e-01 0.2070312                 0
 #  8        x x_lev_x_b   lev 1.110223e-16 1.0000000                 0
dTrainNTreated <- prepare(treatmentsN, dTrainN, pruneSig=1.0, scale=TRUE)
 #  Warning in prepare.treatmentplan(treatmentsN, dTrainN, pruneSig = 1, scale =
 #  TRUE): possibly called prepare() on same data frame as designTreatments*()/
 #  mkCrossFrame*Experiment(), this can lead to over-fit. To avoid this, please use
 #  mkCrossFrame*Experiment$crossFrame.
varsN <- setdiff(colnames(dTrainNTreated), 'y')
# all input variables should be mean 0
sapply(dTrainNTreated[, varsN, drop=FALSE], mean) 
 #         x_catP        x_catN        x_catD             z       z_isBAD 
 #   2.775558e-17  0.000000e+00 -2.775558e-17  4.857226e-17  6.938894e-18 
 #       x_lev_NA     x_lev_x_a     x_lev_x_b 
 #   6.938894e-18  0.000000e+00  7.703720e-34
# all non NA slopes should be 1
sapply(varsN, function(c) { lm(paste('y', c, sep='~'),
 #     x_catP    x_catN    x_catD         z   z_isBAD  x_lev_NA x_lev_x_a x_lev_x_b 
 #          1         1         1         1         1         1         1         1
dTestNTreated <- prepare(treatmentsN, dTestN, pruneSig=c(), scale=TRUE)
 #    x_catP x_catN      x_catD         z    z_isBAD   x_lev_NA x_lev_x_a
 #  1 -0.250  -0.25 -0.06743804 0.9952381 -0.1666667 -0.1666667     -0.25
 #  2  0.250   0.00 -0.25818161 2.5666667 -0.1666667 -0.1666667      0.25
 #  3  0.625   0.00 -0.25818161 4.1380952 -0.1666667 -0.1666667      0.25
 #  4  0.250   0.50  0.39305768 0.0000000  0.5000000  0.5000000      0.25
 #        x_lev_x_b
 #  1 -2.266233e-17
 #  2  6.798700e-17
 #  3 -2.266233e-17
 #  4 -2.266233e-17

# for large data sets you can consider designing the treatments on 
# a subset like: d[sample(1:dim(d)[[1]], 1000), ]

# One can also use treatment plans as pipe targets.
dTrainN %.>% 
  treatmentsN %.>% 
 #  Warning in prepare.treatmentplan(pipe_right_arg, pipe_left_arg):
 #  possibly called prepare() on same data frame as designTreatments*()/
 #  mkCrossFrame*Experiment(), this can lead to over-fit. To avoid this, please use
 #  mkCrossFrame*Experiment$crossFrame.
x_catP x_catN x_catD z z_isBAD x_lev_NA x_lev_x_a x_lev_x_b y
0.50 -0.25 0.5000000 1.000000 0 0 1 0 0
0.50 -0.25 0.5000000 2.000000 0 0 1 0 0
0.50 -0.25 0.5000000 3.000000 0 0 1 0 0
0.50 -0.25 0.5000000 4.000000 0 0 1 0 1
0.25 0.00 0.7071068 5.000000 0 0 0 1 0
0.25 0.00 0.7071068 3.666667 1 0 0 1 1
0.25 0.50 0.0000000 7.000000 0 1 0 0 1
0.25 0.50 0.0000000 3.666667 1 1 0 0 1

Related work:


To install, from inside R please run:



Notes on controlling vtreat’s cross-validation plans can be found here.

Note: vtreat is meant only for “tame names”, that is: variables and column names that are also valid simple (without quotes) R variables names.