A Statistically Sound 'data.frame' Processor/Conditioner

A 'data.frame' processor/conditioner that prepares real-world data for predictive modeling in a statistically sound manner. 'vtreat' prepares variables so that data has fewer exceptional cases, making it easier to safely use models in production. Common problems 'vtreat' defends against: 'Inf', 'NA', too many categorical levels, rare categorical levels, and new categorical levels (levels seen during application, but not during training). Reference: "'vtreat': a data.frame Processor for Predictive Modeling", Zumel, Mount, 2016, .

DOI DOI CRAN_Status_Badge

vtreat is an R data.frame processor/conditioner that prepares real-world data for predictive modeling in a statistically sound manner.

For more detail please see here: arXiv:1611.09477 stat.AP . There is also a series of articles recording the evolution of vtreat including some tutorials here.

(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:

  • Treatment of missing values through safe replacement plus indicator column (a simple but very powerful method when combined with downstream machine learning algorithms).
  • Treatment of novel levels (new values of categorical variable seen during test or application, but not seen during training) through sub-models (or impact/effects coding of pooled rare events).
  • Explicit coding of categorical variable levels as new indicator variables (with optional suppression of non-significant indicators).
  • Treatment of categorical variables with very large numbers of levels through sub-models (again impact/effects coding).
  • (optional) User specified significance pruning on levels coded into effects/impact sub-models.
  • Correct treatment of nested models or sub-models through data split (see here) or through the generation of "cross validated" data frames (see here); these are issues similar to what is required to build statistically efficient stacked models or super-learners).
  • Safe processing of "wide data" (data with very many variables, often driving common machine learning algorithms to over-fit) through out of sample per-variable significance estimates and user controllable pruning (something we have lectured on previously here and here).
  • Collaring/Winsorizing of unexpected out of range numeric inputs.
  • (optional) Conversion of all variables into effects (or "y-scale") units (through the optional scale argument to vtreat::prepare(), using some of the ideas discussed here). This allows correct/sensible application of principal component analysis pre-processing in a machine learning context.
  • Joining in additional training distribution data (which can be useful in analysis, called "catP" and "catD").

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.

'vtreat' is supplied by Win-Vector LLC under a GPL-3 license, without warranty.

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:

  • Categorical variables with very many levels.

    We re-encode such variables as a family of indicator or dummy variables for common levels plus an additional impact code (also called "effects coded" in Jacob Cohen, Patricia Cohen, Applied Multiple Regression/Correlation Analysis for the Behavioral Sciences, 2nd edition, 1983). This allows principled use (including smoothing) of huge categorical variables (like zip-codes) when building models. This is critical for some libraries (such as 'randomForest', which has hard limits on the number of allowed levels).

  • Rare categorical levels.

    Levels that do not occur often during training tend not to have reliable effect estimates and contribute to over-fit. vtreat helps with 2 precautions in this case. First the 'rareLevel' argument suppresses levels with this count our below from modeling, except possibly through a grouped contribution. Also with enough data vtreat attempts to estimate out of sample performance of derived variables. Finally we suggest users reserve a portion of data for vtreat design, separate from any data used in additional training, calibration, or testing.

  • Novel categorical levels.

    A common problem in deploying a classifier to production is: new levels (levels not seen during training) encountered during model application. We deal with this by encoding categorical variables in a possibly redundant manner: reserving a dummy variable for all levels (not the more common all but a reference level scheme). This is in fact the correct representation for regularized modeling techniques and lets us code novel levels as all dummies simultaneously zero (which is a reasonable thing to try). This encoding while limited is cheaper than the fully Bayesian solution of computing a weighted sum over previously seen levels during model application.

  • Missing/invalid values NA, NaN, +-Inf.

    Variables with these issues are re-coded as two columns. The first column is clean copy of the variable (with missing/invalid values replaced with either zero or the grand mean, depending on the user chose of the 'scale' parameter). The second column is a dummy or indicator that marks if the replacement has been performed. This is simpler than imputation of missing values, and allows the downstream model to attempt to use missingness as a useful signal (which it often is in industrial data).

  • Extreme values.

    Variables can be restricted to stay in ranges seen during training. This can defend against some run-away classifier issues during model application.

  • Constant and near-constant variables.

    Variables that "don't vary" or "nearly don't vary" are suppressed.

  • Need for estimated single-variable model effect sizes and significances.

    It is a dirty secret that even popular machine learning techniques need some variable pruning (when exposed to very wide data frames, see here and here). We make the necessary effect size estimates and significances easily available and supply initial variable pruning.

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 idea is: 'data.frame's 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:

  • Out of sample scoring.
  • Ability to use 'parallel'.
  • More general calculation of effect sizes and significances.

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:

 #  To cite package 'vtreat' in publications use:
 #    John Mount and Nina Zumel (2019). vtreat: A Statistically Sound
 #    'data.frame' Processor/Conditioner.
 #    https://github.com/WinVector/vtreat/,
 #    https://winvector.github.io/vtreat/.
 #  A BibTeX entry for LaTeX users is
 #    @Manual{,
 #      title = {vtreat: A Statistically Sound 'data.frame' Processor/Conditioner},
 #      author = {John Mount and Nina Zumel},
 #      year = {2019},
 #      note = {https://github.com/WinVector/vtreat/https://winvector.github.io/vtreat/},
 #    }
# categorical example
dTrainC <- data.frame(x=c('a','a','a','b','b',NA,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 0.059315943 0.45141252                 2
 #  2        x    x_catB  catB 0.029824903 0.59334713                 2
 #  3        z         z clean 0.237601767 0.13176020                 0
 #  4        z   z_isBAD isBAD 0.296065432 0.09248399                 0
 #  5        x  x_lev_NA   lev 0.296065432 0.09248399                 0
 #  6        x x_lev_x_a   lev 0.130005705 0.26490379                 0
 #  7        x x_lev_x_b   lev 0.006067337 0.80967242                 0
# help("prepare")
dTrainCTreated <- prepare(treatmentsC,dTrainC,pruneSig=1.0,scale=TRUE)
varsC <- setdiff(colnames(dTrainCTreated),'y')
# all input variables should be mean 0
 #         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 
 #  0.23254609 0.05841932 0.16062145 0.03162633 0.03162633 0.23254609 
 #   x_lev_x_b 
 #  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),
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.352941e-02 0.5159425                 2
 #  2        x    x_catN  catN 1.678556e-03 0.9232668                 2
 #  3        x    x_catD  catD 3.614228e-01 0.1149323                 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)
varsN <- setdiff(colnames(dTrainNTreated),'y')
# all input variables should be mean 0
 #         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 
 #          1         1         1         1         1         1         1 
 #  x_lev_x_b 
 #          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),]

Related work:


To install, from inside R please run:



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


vtreat 1.4.0 2019/05/05

  • Fancy level and variable names.
  • More tests on odd level names (and collisions).

vtreat 1.3.8 2019/03/31

  • Remove spline from default value variables.
  • Fix ggplot2 vignette dependence issue.
  • Make treatment plans pipeable targets.

vtreat 1.3.7 2019/02/20

  • Fix design_missingness_treatment() prepare.
  • Move to wrapr test runner.

vtreat 1.3.6 2019/02/09

  • Add patch_columns_into_frame().
  • Fix column name munging.
  • Start switching to RUnit tests.

vtreat 1.3.5 2019/01/27

  • Make categorical scoring default TRUE.
  • logit-ize custom coders.
  • spline custom coder.
  • Get stricter about row ordering in building custom coders.
  • neaten up printing a bit.
  • Collar spline and lower its complexity.

vtreat 1.3.4 2019/01/02

  • Accept pre-built approximation tables from numeric custom coders.
  • Fix .customCodeNum() extrapolation, down-sampling, and remote numeric ".center" option.
  • More docs.

vtreat 1.3.3 2018/12/17

  • remove _clean suffix.
  • Fix non-scalar comparisions (mostly form class vectors).
  • add segmented variable calculation.
  • add pre-computed split plan.
  • bump dependencies.
  • Example higher order coders.

vtreat 1.3.2 2018/11/05

  • force parent.frame
  • add a drop columns option to design_missingness_treatment()
  • Doc fixes

vtreat 1.3.1 2018/09/10

  • Fix variable naming in multi class case.
  • Some doc fixes.
  • Start on NaN and Infinity on databases.
  • More tests.

vtreat 1.3.0 2018/07/20

  • Fix z-split annotation issue.
  • Change designTreatmentsZ() defaults.
  • Documentation fixes.
  • Multiclass treatments.
  • Simple treatments.
  • Fix CRAN Note on pre 3.5.0 R parallel usage.

vtreat 1.2.3 2018/07/11

  • Smooth catP novel levels scoring a bit.
  • Fix check error on parallel::getDefaultCluster()

vtreat 1.2.2 2018/07/04

  • Fix issue 19.
  • Do not use NULL to signal when parallelism is desired.

vtreat 1.2.1 2018/06/26

  • default data.table merging on (may be a performance regression to not set this).
  • rqdatatable treatment path.
  • better formatting.
  • add extracols argument to prepare().
  • Improve regexps.

vtreat 1.2.0 2018/06/19

  • Translate treatment plans to rquery.
  • Minor documentation improvements.
  • Improve error messages on argument checking.
  • Improve name generation (remove dots).
  • Remove dplyr dependence.

vtreat 1.0.4 2018/05/05

  • Add data.table as an optional row-binder.
  • Declare an R version.

vtreat 1.0.3 2018/03/10

  • parallel indicator calculation.
  • add optional warning on encountering novel levels in prepare.

vtreat 1.0.2 2018/01/20

  • bind options.
  • fix deps.
  • restore parallel test.
  • kWayStratifiedY performance fix from @khotilov Vadim Khotilovich.

vtreat 1.0.1 2017/10/16

  • Minor documentation fixes.
  • rm data.table (possibly related to issues 2413 or 2418).

vtreat 1.0.0 2017/10/04

  • Minor documentation fixes.
  • More work on novel values for non-centered custom coders.
  • Numeric custom coders.
  • Isotone examples.

vtreat 0.6.0 2017/09/20

  • Add codeRestriction option to design steps.
  • Prepare for custom models.
  • Prefer data.table::rbindlist() for assembling frames.
  • Add forceSplit mode.

vtreat 0.5.32 2017/06/13

  • Add codeRestriction option to prepare().

vtreat 0.5.31 2017/04/13

  • make prueSig an optional argument in prepare, and force by-name access.
  • Remove left.op=TRUE from findInterval in "vtreat Rare Levels" vignette (seems to be a new addition to findInterval, so fails CRAN check r-oldrel-windows-ix86+x86_64).

vtreat 0.5.30 2017/01/21

  • General improvements in documentation and vignettes.
  • Document saving/loading treatment plans.

vtreat 0.5.29 2016/10/27

  • Add 'rsq' column to scoreFrame (rsq- for numeric targets, pseudo-rsq for categorical targets).

vtreat 0.5.28 2016/10/24

  • Fix treatment of constant columns in cross-partitions.
  • Switch doCollar default to FALSE.
  • Return indicators on designTreatmentsZ.
  • Fix extraDegreesOfFreedom calculation.
  • Allow repeated application rows in cross frames.
  • Remove lsig and csig from scoreFrame.
  • Add meanY to treatmentplan.
  • Documentation fixes.

vtreat 0.5.27 2016/08/16


  • Change catB variables to delta-logit score.
  • Fix passing of arguments to parallel prepare, and reduce size of data passed.
  • Ensure set of variables consistency in mkCross* methods.
  • More parallelization of level significance calculations, and cheaper chi-square test where appropriate.

vtreat 0.5.26 2016/07/10

  • Facilities for y-stratified and grouped splitting (useful for unbalanced classes).
  • catScaling=TRUE mode uses logistic regression for y-aware variable scaling.
  • Fix erroneous bad type warning on date columns.

vtreat 0.5.25 2016/05/02

  • Fix bug that caused catB variables to be scored as "insignificant".
  • Add test to check for above bug.
  • Expose cross validation controls.
  • More guards on significance calculations.

vtreat 0.5.23 2016/04/28

  • Fix issue of non-significant variables not being scaled.
  • Documentation fixes, document variable types, improve vignettes.
  • Minor performance fixes on result accumulation.
  • Add optional use of dplyr for row binding (of score report frames).

vtreat 0.5.22 2016/01/07

  • Calculations of non catX significances are now deterministic
  • Catch mis-naming or non-varying y earlier
  • Expose buildEvalSets as a public function
  • More tests

vtreat 0.5.21 2015/11/23

  • Isolated "cross" or "out of sample" frame generation into mkCrossFrameCExperiment() and mkCrossFrameNExperiment()
  • Many small bug fixes and corner cases patched

vtreat 0.5.20 2015/11/05

  • Simplified out of sample frame generation
  • Added "no-Y" treatment option
  • Minor documentation fixes

vtreat 0.5.18 2015/10/07

  • Fixed bugs in cross-validated mode
  • Force out of sample calculations in more situations
  • Fix vignette titles
  • Fix documentation
  • Do not allow small or insufficiently varying data frames (exact conditions in documentation)

vtreat 0.5.16 2015/09/12

  • Unified rare level treatment
  • Separate treatment of insignificant levels
  • Tests confirming compatibility with 'data.table'
  • More special case hardening
  • Over-fit vignette
  • Minor documentation fixes

vtreat 0.5.14 2015/09/06

  • First CRAN release

Reference manual

It appears you don't have a PDF plugin for this browser. You can click here to download the reference manual.


1.6.3 by John Mount, 7 months ago

https://github.com/WinVector/vtreat/, https://winvector.github.io/vtreat/

Report a bug at https://github.com/WinVector/vtreat/issues

Browse source code at https://github.com/cran/vtreat

Authors: John Mount [aut, cre] , Nina Zumel [aut] , Win-Vector LLC [cph]

Documentation:   PDF Manual  

GPL-2 | GPL-3 license

Imports stats, digest

Depends on wrapr

Suggests rquery, rqdatatable, data.table, isotone, lme4, knitr, rmarkdown, parallel, DBI, RSQLite, datasets, R.rsp, tinytest

Imported by crispRdesignR.

Suggested by mlr3pipelines.

See at CRAN