---
title: "vtreat package"
author: "John Mount, Nina Zumel"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{vtreat package}
  %\VignetteEngine{knitr::rmarkdown}
  \usepackage[utf8]{inputenc}
---

'vtreat' is a data.frame processor/conditioner that prepares real-world data for predictive modeling in a statistically sound manner.  A formal article on the method can be found here: [arXiv:1611.09477 stat.AP](https://arxiv.org/abs/1611.09477).

A 'vtreat' clean data
frame:

- Only has numeric columns (other than the outcome).
- Has no Infinite/NA/NaN in the effective variable columns.


To achieve this a number of techniques are used.  Principally:

- [Impact coding](http://www.win-vector.com/blog/2012/07/modeling-trick-impact-coding-of-categorical-variables-with-many-levels/)
- [Encoding category levels as indicators](http://www.win-vector.com/blog/2014/12/a-comment-on-preparing-data-for-classifiers/)

For more details see: [the 'vtreat' article](http://www.win-vector.com/blog/2014/08/vtreat-designing-a-package-for-variable-treatment/) and [update](http://www.win-vector.com/blog/2015/05/what-is-new-in-the-vtreat-library/).

The use pattern is:

1. Use `designTreatmentsC()` or `designTreatmentsN()` to design a treatment plan 
2. Use the returned structure with `prepare()` to apply the plan to data frames.  

The main feature of 'vtreat' is that all data preparation is "y-aware": it uses the relations of effective variables to the dependent or outcome variable to encode the effective variables.

The structure returned from `designTreatmentsN()` or `designTreatmentsC()` includes a list of "treatments": objects that encapsulate the transformation process from the original variables to the new "clean" variables.

In addition to the treatment objects `designTreatmentsC()` and `designTreatmentsN()` also return a data frame named `scoreFrame` which contains columns:

- `varName`: name of new variable
- `origName`: name of original variable that the variable was derived from (can repeat).
- `code`: what time of treatment was performed to create the derived variable (useful for filtering).
- `varMoves`: logical TRUE if the variable varied during training; only variables that move will be in the treated frame.
- `sig`: linear significance of regressing derived variable against a 0/1 indicator target for numeric targets, logistic regression significance otherwise.
- `needsSplit`: is the variable a sub model and require out of sample scoring.


In all cases we have two undesirable upward biases on the scores:

- The treated variables view the training data during construction (for setting of NA values, missing values, levels, and more).  So this gives an upward bias when trying to measure treated variable utility on training data.  Until the data set is at least 1000 good rows we ignore this effect.  After 1000 rows we design variables on a pseudo-randomly chosen 80% of the rows and score on the complimentary 20% of the rows.
- The scoring procedure itself involves a fit (linear regression for regression or logistic regression for classification).  In each of these cases we would like the scoring itself to only be evaluated on variables constructed on held-out data.  This is simulated through a cross-validation procedure.

'vtreat' uses a number of cross-training and jackknife style procedures to try to mitigate these effects.  The suggested best practice (if you have enough data) is to split your data randomly into at least the following disjoint data sets:

- **Encoding Calibration** : a data set used for the `designTreatmentsC()` or `designTreatmentsN()` step and not used again for training or test.
- **Training** : a data set used (after `prepare()`) for training your model.
- **Test** : a data set used (after `prepare()`) for estimating your model's out of training performance.

Taking the extra step to perform the `designTreatmentsC()` or `designTreatmentsN()` on data disjoint from training makes the training data more exchangeable with test and avoids the issue that 'vtreat' may be hiding a large number of degrees of freedom in variables it derives from large categoricals.

Some trivial execution examples (not demonstrating any cal/train/test split) are given below.  Variables that do not move during hold-out testing are considered "not to move."

---------------------------

## A Categorical Outcome Example

```{r, tidy=FALSE}
library(vtreat)
dTrainC <- data.frame(x=c('a','a','a','b','b',NA),
   z=c(1,2,3,4,NA,6),y=c(FALSE,FALSE,TRUE,FALSE,TRUE,TRUE))
head(dTrainC)

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

treatmentsC <- designTreatmentsC(dTrainC,colnames(dTrainC),'y',TRUE)
print(treatmentsC)
print(treatmentsC$treatments[[1]])
```


Here we demonstrate the optional scaling feature of `prepare()`, which
scales and centers all significant variables to mean 0, and slope 1 with respect to y:
In other words, it re-scales the variables to "y-units". This is useful for downstream
principal components analysis.  Note: variables perfectly uncorrelated with y necessarily have slope 0
and can't be "scaled" to slope 1, however for the same reason these variables will be insignificant 
and can be pruned by pruneSig.

`scale=FALSE` by default.


```{r, tidy=FALSE}

dTrainCTreated <- prepare(treatmentsC,dTrainC,pruneSig=c(),scale=TRUE)
head(dTrainCTreated)

varsC <- setdiff(colnames(dTrainCTreated),'y')
# all input variables should be mean 0
sapply(dTrainCTreated[,varsC,drop=FALSE],mean)
# all slopes should be 1 for variables with dTrainCTreated$scoreFrame$sig<1
sapply(varsC,function(c) { glm(paste('y',c,sep='~'),family=binomial,
   data=dTrainCTreated)$coefficients[[2]]})

dTestCTreated <- prepare(treatmentsC,dTestC,pruneSig=c(),scale=TRUE)
head(dTestCTreated)
```

--------------------------------

## A Numeric Outcome Example

```{r, tidy=FALSE}

# numeric example
dTrainN <- data.frame(x=c('a','a','a','a','b','b',NA),
   z=c(1,2,3,4,5,NA,7),y=c(0,0,0,1,0,1,1))
head(dTrainN)

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

treatmentsN = designTreatmentsN(dTrainN,colnames(dTrainN),'y')
print(treatmentsN)

dTrainNTreated <- prepare(treatmentsN,dTrainN,
                          pruneSig=c(),scale=TRUE)
head(dTrainNTreated)

varsN <- setdiff(colnames(dTrainNTreated),'y')
# all input variables should be mean 0
sapply(dTrainNTreated[,varsN,drop=FALSE],mean) 
# all slopes should be 1 for variables with treatmentsN$scoreFrame$sig<1
sapply(varsN,function(c) { lm(paste('y',c,sep='~'),
   data=dTrainNTreated)$coefficients[[2]]}) 


# prepared frame
dTestNTreated <- prepare(treatmentsN,dTestN,
                         pruneSig=c())
head(dTestNTreated)

# scaled prepared frame
dTestNTreatedS <- prepare(treatmentsN,dTestN,
                         pruneSig=c(),scale=TRUE)
head(dTestNTreatedS)
```

Related work:

  * _Applied Multiple Regression/Correlation Analysis for the Behavioral Sciences_, 2nd edition, 1983, Jacob Cohen, Patricia Cohen (called the concept “effects coded variables”).
  * ["A preprocessing scheme for high-cardinality categorical attributes in classification and prediction problems"](http://dl.acm.org/citation.cfm?id=507538) Daniele Micci-Barreca, ACM SIGKDD Explorations, Volume 3 Issue 1, July 2001 Pages 27-32.
  * ["Modeling Trick: Impact Coding of Categorical Variables with Many Levels"](http://www.win-vector.com/blog/2012/07/modeling-trick-impact-coding-of-categorical-variables-with-many-levels/) Nina Zumel, Win-Vector blog, 2012.
  * "Big Learning Made Easy – with Counts!", Misha Bilenko, Cortana Intelligence and Machine Learning Blog, 2015.
