• Stars
    star
    281
  • Rank 146,170 (Top 3 %)
  • Language
    HTML
  • License
    Other
  • Created about 10 years ago
  • Updated 3 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

vtreat is a data frame processor/conditioner that prepares real-world data for predictive modeling in a statistically sound manner. Distributed under choice of GPL-2 or GPL-3 license.

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.

A nice video lecture on what sorts of problems vtreat solves can be found here.

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

  • 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.

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”). 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 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:

  • 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.

Some small examples:

We attach our packages.

library("vtreat")
 #  Loading required package: wrapr
packageVersion("vtreat")
 #  [1] '1.6.1'
citation('vtreat')
 #  
 #  To cite package 'vtreat' in publications use:
 #  
 #    John Mount and Nina Zumel (2020). 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 = {2020},
 #      note = {https://github.com/WinVector/vtreat/, https://winvector.github.io/vtreat/},
 #    }

A small categorical example.

# categorical example
set.seed(23525)

# we set up our raw training and application data
dTrainC <- data.frame(
  x = c('a', 'a', 'a', 'b', 'b', NA, NA),
  z = c(1, 2, 3, 4, NA, 6, NA),
  y = c(FALSE, FALSE, TRUE, FALSE, TRUE, TRUE, TRUE))

dTestC <- data.frame(
  x = c('a', 'b', 'c', NA), 
  z = c(10, 20, 30, NA))

# we perform a vtreat cross frame experiment
# and unpack the results into treatmentsC
# and dTrainCTreated
unpack[
  treatmentsC = treatments,
  dTrainCTreated = crossFrame
  ] <- mkCrossFrameCExperiment(
  dframe = dTrainC,
  varlist = setdiff(colnames(dTrainC), 'y'),
  outcomename = 'y',
  outcometarget = TRUE,
  verbose = FALSE)

# the treatments include a score frame relating new
# derived variables to original columns
treatmentsC$scoreFrame[, c('origName', 'varName', 'code', 'rsq', 'sig', 'extraModelDegrees', 'recommended')] %.>%
  knitr::kable(.)
origName varName code rsq sig extraModelDegrees recommended
x x_catP catP 0.1669568 0.2064389 2 FALSE
x x_catB catB 0.2547883 0.1185814 2 TRUE
z z clean 0.2376018 0.1317602 0 TRUE
z z_isBAD isBAD 0.2960654 0.0924840 0 TRUE
x x_lev_NA lev 0.2960654 0.0924840 0 FALSE
x x_lev_x_a lev 0.1300057 0.2649038 0 FALSE
x x_lev_x_b lev 0.0060673 0.8096724 0 FALSE
# the treated frame is a "cross frame" which
# is a transform of the training data built 
# as if the treatment were learned on a different
# disjoint training set to avoid nested model
# bias and over-fit.
dTrainCTreated %.>%
  head(.) %.>%
  knitr::kable(.)
x_catP x_catB z z_isBAD x_lev_NA x_lev_x_a x_lev_x_b y
0.50 0.0000000 1 0 0 1 0 FALSE
0.40 -0.4054484 2 0 0 1 0 FALSE
0.40 -10.3089860 3 0 0 1 0 TRUE
0.20 8.8049919 4 0 0 0 1 FALSE
0.25 -9.2104404 3 1 0 0 1 TRUE
0.25 9.2104404 6 0 1 0 0 TRUE
# Any future application data is prepared with
# the prepare method.
dTestCTreated <- prepare(treatmentsC, dTestC, pruneSig=NULL)

dTestCTreated %.>%
  head(.) %.>%
  knitr::kable(.)
x_catP x_catB z z_isBAD x_lev_NA x_lev_x_a x_lev_x_b
0.4285714 -0.9807709 10.0 0 0 1 0
0.2857143 -0.2876737 20.0 0 0 0 1
0.0714286 0.0000000 30.0 0 0 0 0
0.2857143 9.6158638 3.2 1 1 0 0

A small numeric example.

# numeric example
set.seed(23525)

# we set up our raw training and application data
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))

# we perform a vtreat cross frame experiment
# and unpack the results into treatmentsN
# and dTrainNTreated
unpack[
  treatmentsN = treatments,
  dTrainNTreated = crossFrame
  ] <- mkCrossFrameNExperiment(
  dframe = dTrainN,
  varlist = setdiff(colnames(dTrainN), 'y'),
  outcomename = 'y',
  verbose = FALSE)

# the treatments include a score frame relating new
# derived variables to original columns
treatmentsN$scoreFrame[, c('origName', 'varName', 'code', 'rsq', 'sig', 'extraModelDegrees')] %.>%
  knitr::kable(.)
origName varName code rsq sig extraModelDegrees
x x_catP catP 0.4047085 0.0899406 2
x x_catN catN 0.2822908 0.1753958 2
x x_catD catD 0.0209693 0.7322571 2
z z clean 0.2880952 0.1701892 0
z z_isBAD isBAD 0.3333333 0.1339746 0
x x_lev_NA lev 0.3333333 0.1339746 0
x x_lev_x_a lev 0.2500000 0.2070312 0
x x_lev_x_b lev 0.0000000 1.0000000 0
# the treated frame is a "cross frame" which
# is a transform of the training data built 
# as if the treatment were learned on a different
# disjoint training set to avoid nested model
# bias and over-fit.
dTrainNTreated %.>%
  head(.) %.>%
  knitr::kable(.)
x_catN x_catD z z_isBAD x_lev_NA x_lev_x_a x_lev_x_b x_catP y
-0.2666667 0.5000000 1 0 0 1 0 0.6 0
-0.5000000 0.0000000 2 0 0 1 0 0.5 0
-0.0666667 0.5000000 3 0 0 1 0 0.6 0
-0.5000000 0.0000000 4 0 0 1 0 0.5 1
0.4000000 0.7071068 5 0 0 0 1 0.2 0
-0.4000000 0.7071068 3 1 0 0 1 0.2 1
# Any future application data is prepared with
# the prepare method.
dTestNTreated <- prepare(treatmentsN, dTestN, pruneSig=NULL)

dTestNTreated %.>%
  head(.) %.>%
  knitr::kable(.)
x_catP x_catN x_catD z z_isBAD x_lev_NA x_lev_x_a x_lev_x_b
0.5000 -0.25 0.5000000 10.000000 0 0 1 0
0.2500 0.00 0.7071068 20.000000 0 0 0 1
0.0625 0.00 0.7071068 30.000000 0 0 0 0
0.2500 0.50 0.0000000 3.666667 1 1 0 0

Related work:

Installation

To install, from inside R please run:

install.packages("vtreat")

Note

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.

More Repositories

1

zmPDSwR

Example R scripts and data for "Practical Data Science with R" 1st edition by Nina Zumel and John Mount (Manning Publications)
HTML
478
star
2

Examples

Various examples for different articles
HTML
148
star
3

wrapr

Wrap R for Sweet R Code
R
135
star
4

PDSwR2

Code, Data, and Examples for Practical Data Science with R 2nd edition (Nina Zumel and John Mount) https://github.com/WinVector/PDSwR2
HTML
131
star
5

pyvtreat

vtreat is a data frame processor/conditioner that prepares real-world data for predictive modeling in a statistically sound manner. Distributed under a BSD-3-Clause license.
Python
115
star
6

data_algebra

Codd method-chained SQL generator and Pandas data processing in Python.
Python
114
star
7

rquery

Data Wrangling and Query Generating Operators for R. Distributed under choice of GPL-2 or GPL-3 license.
HTML
109
star
8

WVPlots

Pre-packaged plots in R
R
84
star
9

replyr

Patches for using dplyr with Databases and Big Data
HTML
66
star
10

BigDataRStrata2017

All material for "Modeling big data with R, sparklyr, and Apache Spark" Strata Hadoop 2017.
HTML
62
star
11

seplyr

Improved Standard Evaluation Interfaces for Common Data Manipulation Tasks
R
48
star
12

cdata

Higher order fluid or coordinatized data transforms in R. Distributed under choice of GPL-2 or GPL-3 license.
R
44
star
13

CampaignPlanner

Example code for Lesson on Response Campaign planning
HTML
38
star
14

rqdatatable

Implement the rquery piped query algebra in R using data.table. Distributed under choice of GPL-2 or GPL-3 license.
R
37
star
15

Logistic

Experimental logistic regression code supporting multiple result categories, many levels of categorical modeling variables, good optimization, L2 regularization and more.
Java
35
star
16

AutoDiff

Example automatic differentiation code in Scala
Scala
30
star
17

sigr

Concise formatting of significances in R (GPL3 license).
HTML
27
star
18

ExploreModels

Code and data for "The Geometry of Classifiers"
R
26
star
19

WinVector.github.io

Viewable pages from WinVector LLC view at: http://winvector.github.io
HTML
23
star
20

NestedModelsTalk

Support materials for WinVector talk
19
star
21

CampaignPlanner_v3

Shiny demo of A/B test planning and evaluation (improved UI for A/B testing method taught in free video course)
R
17
star
22

WVLPSolver

Experimental pure Java revised simplex linear program solver (Apache 2.0 license)
Java
15
star
23

Locality-Sensitive-Hashing-Example

Simple example of Locality Sensitive Hashing
Java
14
star
24

RcppDynProg

Dynamic Programming implemented in Rcpp. Includes example partition and out of sample fitting applications.
C++
14
star
25

ODSCWest2017

Win-Vector LLC ODSC West 2017 presentation materials (will be populated by the day of the conference)
HTML
14
star
26

kcomp

Demonstration of parametric bootstrap to find k for kmeans
HTML
10
star
27

ValidatingModelsInR

Slides and code for "Validating Models in R" Strata 2016 RDay http://conferences.oreilly.com/strata/hadoop-big-data-ca/public/schedule/detail/48053
HTML
10
star
28

SQLScrewdriver

Iterate through database tables (by JDBC) and TSV(tab separated values)/CSV(comma separated values) and load/dump data.
Java
8
star
29

wvpy

Tools to convert from Jupyter notebooks to and from Python .py files, and render.
HTML
8
star
30

FastBaseR

Examples of fast grouped row-wise operations in R (no C, C++, data.table, or dplyr used).
R
6
star
31

VectorDemo

Tutorial on using vectors in data science projects.
Jupyter Notebook
3
star
32

OutOfCore

Example of out of core coding techniques
Java
2
star
33

Importance-Sampling

Importance Sampling Example
Java
2
star
34

ExampleRPackage

Example of how to build a simple R package
R
2
star
35

ClassifierMetrics

Some examples of measuring classifier performance in R
HTML
2
star
36

QSurvival

Quasi observation based survival package for R.
R
2
star
37

LStep

Trivial demonstration of a diverging Newton-Raphson step when solving a logistic regression
Java
2
star
38

JXREF

Java based XML tool to help check Manning Agile Author XML for cross reference problems (Java based, GPL3+ license)
Java
1
star
39

ExperimentInspector

Java code to build synthetic data sets that match reported summary totals. Helps explore possible range of variation.
Java
1
star
40

crosspca

Cross-validated PCA/PCR demonstration based on the work: http://www.win-vector.com/blog/2016/05/pcr_part2_yaware/
R
1
star
41

SessionExample

Example code for articles on sessionizing data.
1
star
42

daccum

Example library to accumulate data frame rows in R
R
1
star
43

YConditionalRegularizedModel

Example of a neural net model, with regularization on y-conditional activation patterns
Jupyter Notebook
1
star
44

ATasteOfDataScience

Working an example of supervised machine learning in Python
Jupyter Notebook
1
star
45

CVRTSEncoder

Spectral encoding of categorical variables using model residual trajectories
R
1
star
46

wvu

Win Vector LLC Python data science teaching tools (graphs and data manipulation)
HTML
1
star
47

BreakingNestedModelBias

Support materials for Win-Vector blog article
HTML
1
star