Giter VIP home page Giter VIP logo

winvector / vtreat Goto Github PK

View Code? Open in Web Editor NEW
283.0 22.0 45.0 176.47 MB

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.

Home Page: https://winvector.github.io/vtreat/

License: Other

R 35.69% HTML 64.17% TeX 0.14%
r categorical-variables prepare-data machine-learning-algorithms nested-models

vtreat's Introduction

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.5'
citation('vtreat')
 #  To cite package 'vtreat' in publications use:
 #  
 #    Mount J, Zumel N (2024). _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 = {2024},
 #      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
# 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_catP y
-0.2666667 0.5000000 1 0 0 1 0.6 0
-0.5000000 0.0000000 2 0 0 1 0.5 0
-0.0666667 0.5000000 3 0 0 1 0.6 0
-0.5000000 0.0000000 4 0 0 1 0.5 1
0.4000000 0.7071068 5 0 0 0 0.2 0
-0.4000000 0.7071068 3 1 0 0 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
0.5000 -0.25 0.5000000 10.000000 0 0 1
0.2500 0.00 0.7071068 20.000000 0 0 0
0.0625 0.00 0.7071068 30.000000 0 0 0
0.2500 0.50 0.0000000 3.666667 1 1 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.

vtreat's People

Contributors

johnmount avatar khotilov avatar lawwu avatar nfultz avatar ninazumel avatar peterhurford avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

vtreat's Issues

[New Feature]: Increase the possibilities of "designTreatmentsZ()".

Hello John,

Thanks for the new vtreatversion.
Perhaps I did not realize the existente of designTreamentsZ() function in the previous version. But now that I know it I see more possibilities that can enrich it to treat categorical variables in particular.

Now, for categorical variables (I am thinking more on variables with high-cardinality) I have already tested in same data competitions that using just the count of each category performs better than its frequencies, as it works now (I know this as Hot Encoding).

This also opens new possibilities in the way that you can also consider interactions of variables. With two categorical variables you can paste each row and apply again the hot-encoding to the resulting variable designTreatmentsZ() could include the possibility to define the kind of resulting output could be, if hot_encoding or frequencies, and also provide a set of variables to get the cross-interaction. Again, I have tested this approach with success in some data competitions.

I thought that these were the most interesting feature engineering approaches until I read this yesterday:

https://www.linkedin.com/pulse/feature-engineering-data-scientists-secret-sauce-ashish-kumar

which opens new coding possbilities for categorical as well as numeric variables that would be very interesting to see implemented in vtreat. These are featuring engineering transformation that as you can read in the post are in the day to day data scientist arsenal.

Thanks,
Carlos Ortega

Package site

At this point, to understand the motivations, background information and usage of vtreat, requires going through a couple of papers, few blog posts, and vignettes. As such having a small website with all of these consolidated at a single source is a nice thing to have. And you can keep updating the site with the latest information regarding this package.

It is very easy to create a doc site for a package using github-pages. Not that you need it, since you guys have a full-fledged site at http://www.win-vector.com/site/.

Vtreat newvars Doesn't Take `make.names` into account

When giving variables to vtreat that are not valid R variable names, the vnames function no longer returns a translation from the original non-valid R variable names to the new valid R variable names.

As an example, if I rename the first column of the iris dataframe to: "mis be hav (%)"

And use vtreat on it like so:

p <- designTreatmentsZ(iris, names(iris))

When I use prepare, I get the following:

> names(prepare(p, iris))[1]
[1] "mis.be.hav...."

When I inspect the vorig and vnames of this treatment, I see the following:

> vorig(p$treatments[[1]])
[1] "mis be hav (%)"
> vnames(p$treatments[[1]])
[1] "mis be hav (%)"

When what I expect to see is:

> vorig(p$treatments[[1]])
[1] "mis be hav (%)"
> vnames(p$treatments[[1]])
[1] "mis.be.hav...."

How to backtransform predictors?

Hello, I used mkCrossFrameCExperiment and prepare to create the design matrix, and now I want to explain my model using it's original scale (for X). And I didn't quite find how the scaling and centering was done, therefore cannot backtransform the data. Could you please point me where to look for it?

vtreat 1.3.0

mkCrossFrameMExperiment output:

Column names of y-dependent treatments in cross_frame data frame differ from those obtained with prepare function.

cross_frame names start with the class label

<class_label>.X<class_label>_varName

while prepare gives

X<class_label>_varName

which are similar with the score_frame varNames

vtreat mkCrossFrameNExperiment efficiency

Hello,

Do you have a rough estimate of how much time it takes to run the design treatments? I have a data frame of about 400K rows x 25 cols and it takes almost an hour to run the cross frame experiment and I want to know if that's the normal time of treating a data frame of this size. If this is normal then could there be ways to improve the run time?

Thanks,

Ethan

Error in example

In the example, the command
unpack[
transform = treatments,
d_prepared = crossFrame
] <- vtreat::mkCrossFrameCExperiment( ………..)

produces error saying 'treatments' is missing. This may be rectified.

Error when preparing data with parallelCluster feature

My code:

parallelCluster <- parallel::makeCluster(ncores) in_data$bst_pred <- predict(bst_xgb, as.matrix(prepare(treatmentsZ, in_data, parallelCluster = parallelCluster))) parallel::stopCluster(parallelCluster)

and I got error

`Error in checkForRemoteErrors(val) :
10 nodes produced errors; first error: could not find function ".cleanColumn"
Calls: source ... clusterApplyLB -> dynamicClusterApply -> checkForRemoteErrors
In addition: Warning message:
In prepare(treatmentsZ_svsd, in_vh_data, parallelCluster = parallelCluster) :
treatments desined with vtreat version 0.5.32 and preparing data.frame with vtreat version 1.0.1
Execution halted

Any idea how to fix this? Thanks in advance.

Serialization/Deserialization of treatmentplan object

I am interested in serializing a treatmentplan object to JSON, store it and later deserialize it and use it to prepare a new observation. I am using jsonlite for this but I am unable to prepare a new observation with the deserialized object.

library("vtreat")
library("jsonlite")

load("test.RData")
class(treatmentDesign) <- "treatmentplan" #I had saved it as a list

treatmentDesignDeserialized <- unserializeJSON(serializeJSON(treatmentDesign, digits = 12))

Things start to get weird already, as the deserialized object almost doubled in size:

> object.size(treatmentDesign)
1791328 bytes
> object.size(treatmentDesignDeserialized)
3143408 bytes

But if I check for equality ...

> all.equal(treatmentDesign,
+           treatmentDesignDeserialized,
+           check.attributes = TRUE,
+           check.names = TRUE)
[1] TRUE

When I check for structure equality

> serializedeserialize <- capture.output(str(treatmentDesignDeserialized))
> originalfile <- capture.output(str(treatmentDesign))
> identical(originalfile, serializedeserialize)
[1] TRUE

Now, the prepare function works with the original loaded treatmentplan, but after serialization/deserialization it returns an error

> load("newObservationExample.RData")
> prepNewObs <- prepare(treatmentDesign, newObs, pruneSig = 0.1)
> 
> prepare(treatmentDesignDeserialized, newObs, pruneSig = 0.1)
 Error in vtreat$f(xcol, vtreat$args, doCollar) : 
  could not find function ".preProcCat" 

This looks a whole lot like this, but the quick fix doesn't seem to work. I tried adding
attr(treatmentDesignDeserialized$treatments, ".Environment") <- .GlobalEnv

Any suggestions, have you done similar operations? There were no answers to the issue opened in jsonlite, hence reaching out for advice here.

There is an horrible workaround, which consists in exporting all hidden functions, but I'd really rather run away from this 'solution':

> # get all the function names
> r <- unclass(lsf.str(envir = asNamespace("vtreat"), all = TRUE))
> # create functions in the Global Env. with the same name
> for(name in r) eval(parse(text=paste0(name, '<-vtreat:::', name)))
> 
> prepNew <- prepare(treatmentDesignDeserialized, newObs, pruneSig = 0.1)
> 
> all.equal(prepNewObs, prepNew, tolerance = 10-8)
[1] TRUE

Thanks.

xframe and prepare() give different catB for high-cardinality predictor when NAs present

In certain situations a catB encoded high-cardinality predictor is significantly different between training data (from the crossframe) and testing data (from prepare).

I encountered this problem "in the wild", but the following example reproduces it. It seems like the crossvalidation folds are lumping the level into "rare" in the crossframe, but not the treatment itself. This only seems to happen for sufficiently large cardinality and missingness and for level counts near the rareCount value, but I haven't been able to determine exactly what triggers it.

library(vtreat)
#> Loading required package: wrapr

set.seed(2311)
nsim <- 10000 # nrow of traning data
rareCount <- 180 # passed to mcCrossFrameCExperiment()
nlvl1 <- 200 # This many occurances of "lvl1" factor level
p1 <- 0.9 # outcome prob when predvar == "lvl1"
p2 <- 0.5 # outcome prob when predvar != "lvl1"
n_na <- 800 # This many missing values in predictor
otherlevels <- paste0("lvl", 2:50)

traindf <- data.frame(
  outcome = c(
    sample(c("Y", "N"), nlvl1, replace = TRUE, prob = c(p1, 1 - p1)),
    sample(c("Y", "N"), nsim, replace = TRUE, prob = c(p2, 1 - p2))
    ),
  predvar = c(
    rep("lvl1", nlvl1), 
    rep(NA_character_, n_na),
    sample(otherlevels, nsim - n_na, replace = TRUE)
))
testdf <- data.frame(predvar = "lvl1")

xf <- mkCrossFrameCExperiment(traindf, "predvar", "outcome", "Y", 
                              rareCount = rareCount)
#> [1] "vtreat 1.6.2 start initial treatment design Wed Mar  3 17:06:29 2021"
#> [1] " start cross frame work Wed Mar  3 17:06:30 2021"
#> [1] " vtreat::mkCrossFrameCExperiment done Wed Mar  3 17:06:31 2021"

unique(xf$crossFrame$predvar_catB[1:(nlvl1)])
#> [1] 0.008405523 0.021683092 0.006087083
prepare(xf$treatments, testdf)$predvar_catB # much different from training value
#> [1] 2.028887

Created on 2021-03-03 by the reprex package (v0.3.0)

multi-class classification

Hello, I wonder when it would be possible to use vtreat for multi-class / multi-label classification data.
Thank you!

Warning on new levels of factor variables

A nice feature to have for the prepare function is that when a new level of a factor/character variable was read in, the function should be able to give a warning and an option to error out. In some cases, we probably don't intend to let the model to predict on some data that it never saw during the model training. I read the documentation, but didn't find how this is handled explicitly. But base on the usage, it seems the function just ignore the new level, and basically include it in the 'reference' level.

Thanks.

Variable Importance

Which would be the correct aggregation statistic for treated variable importance when aggregated by their old names (e.g. outputs from caret::varImp() or randomForest::importance)?

For example:
aggregate(list('oldVar_catB', 'oldVar_poolC', 'oldVar_lev'), by = grep('oldVar', …), FUN = ?, ...)

Cross-validated training is not scaled

When using mkCrossFrameCExperiment with catScaling = T, the training set is not scaled

prep  = mkCrossFrameCExperiment(
dframe = newTrain,
varlist = allVars,
outcomename = "RESULT",
ncross = 10,
verbose = T,
outcometarget = "Realizada",
catScaling = T,
rareCount = round(min(table(newTrain$RESULT)) * 0.01)

)
treatments <- prep$treatments

#Variable Screaning
pruneSig <- 1 / length(allVars)
vf = value_variables_C(
dframe = prep$crossFrame,
varlist = treatments$scoreFrame$varName,
outcomename = "RESULT",
outcometarget = "Realizada",
ncross = 10,
verbose = T,
catScaling = T,
rareCount = round(min(table(newTrain$RESULT)) *
                    0.01)
)
newvars <- vf$var[vf$sig <= pruneSig]

dTrainTreated <- prep$crossFrame
dTestTreated <- vtreat::prepare(treatments,
                              testData,
                              pruneSig = c(), catScaling = T,
                              varRestriction = newvars)

Installation failed on Windows 10 (R version 3.4.0)

Hello,
I'm trying to install the package on windows 10 machine. I get the following error:

'D:\Program' is not recognized as an internal or external command,
operable program or batch file.
Warning in install.packages :
  running command '"D:/Program Files/R/R-3.4.0/bin/x64/R" CMD INSTALL -l "D:\Program Files\R\R-3.4.0\library" C:\Users\Hisham\AppData\Local\Temp\Rtmp4kenP6/downloaded_packages/vtreat_0.5.32.tar.gz' had status 1
Warning in install.packages :
  installation of package ‘vtreat’ had non-zero exit status

The downloaded source packages are in
	‘C:\Users\Hisham\AppData\Local\Temp\Rtmp4kenP6\downloaded_packages’

Bottleknecks In Parallel Computation

Hi -

Thanks for all the work and documentation on this package. I've been doing some testing to see if vtreat (version 1.0.1) could be applied to large datasets ( > 2 million rows and > 100 columns). To start, I've just been asking the package to provide a treatment plan for 5 variables, only one of which is categorical over the full 2+ million record dataset.

I've noticed that when calling the designTreatment*() function on this dataset with parallelCluster set to a cluster object instantiated from the parallel package, that all the cores are fired through the creation of the treatment plan (have treatment plan...). But then when it moves into the rescoring complex variables ..., the process drops down to one core and I have not been able to finish the process on this size of dataset.

I admittedly haven't looked through the source code to see if this was expected behavior, but I was curious if there was some intuition for what's going on at this step and why it isn't being parallelized at this point?

Here are the specs of the machine:
Processors: Intel(R) Xeon(R) CPU E5-2690 v3 @ 2.60 GHz
No. of Processors: 6
RAM: 56GB
OS: Windows Server 2012

Thanks,
Patrick

Unable to create "rare" level for categorical variable if rareCount exceeds a latent threshold

I am trying to create a "rare" level dummy from a two-level factor variable that has a rare level with low frequency.
In the test/holdout data I expect to see a potential third level (also rare) that I would like to bundle with the rare level in the train data after applying the treatment.

Example below:

library(vtreat)

set.seed(1133)
N = 10000
p0_y = 0.5
p0_x = 0.999

df = data.frame(y = sample(c(0, 1), size = N, prob = c(p0_y, 1 - p0_y), replace = TRUE),
                x = as.factor(sample(c(0, 1), size = N, prob = c(p0_x, 1 - p0_x), replace = TRUE)))

print(summary(df))

#       y          x       
# Min.   :0.0000   0:9987  
# 1st Qu.:0.0000   1:  13  
# Median :1.0000           
# Mean   :0.5034           
# 3rd Qu.:1.0000           
# Max.   :1.0000 

treatmentsC = designTreatmentsC(dframe = df,
                                varlist = c("x"),
                                outcomename = "y",
                                outcometarget = 1,
                                minFraction = 0.0,
                                rareCount = 50)

[1] "vtreat 1.2.1 inspecting inputs Tue Jul 03 19:02:23 2018"
[1] "designing treatments Tue Jul 03 19:02:23 2018"
[1] " have initial level statistics Tue Jul 03 19:02:23 2018"
Error in .designTreatmentsXS(dframe, varlist, outcomename, zoY, zC, zTarget,  : 
  no usable vars

I would expect the get back variables x_lev_x_0 and x_lev_rare.
Then if the test/holdout data has factor level 2 it could be bundled with x_lev_rare.

However, if I set rareCount = 0 (or anything less than the frequency of the rare level) I get x_lev_x_0 and x_lev_x_1 as expected but then I can't bundle the novel level from the test/holdout without manually inspecting novel_level_summary().

Question: High-cardinality factor impact coding

I'm trying to understand the definition of the catB impact code. In the basic version described on the blog, I understood that the formula used there is equivalent to the empirical bayes based equation from the Micci-Barreca paper (eq. 3) for the weighting lambda(ni) = ni / (ni +1).

What is the motivation for this weight? The formula seem familiar and it seems better than the weights listed in the paper itself. I haven't managed to derive this weight, though..

The second question is: what is the relation of this original weight to the current implementation? From the code I see that now a smoothing factor (e.g. probT*smFactor) is added (and the result is log-ed). Is there a reference for this approach, where I could learn more?

Thank you very much!

More helpful error message in mkCrossFrameNExperiment

It would be great if a more helpful error message were thrown when running mkCrossFrameNExperiment on a data frame where the outcome variable has NA values.

Right now the error message is:
Error in if (min(ycol) >= max(ycol)) { : missing value where TRUE/FALSE needed

Something like:
Error: There are missing values in the predictor column. Cannot run the experiment.

I may do a pull request but just wanted to throw this out there.

Factor treatment designTreatmentsC

Thank you for the nice package!
I've just went through the initial tutorial and noticed (and fully reproduced) an odd result in:

https://winvector.github.io/vtreathtml/vtreat.html

After applying the treatment from designTreatmentsC, we test

  1. mean of all predictors is 0
  2. slope of lin. fit is 1

Neither of these is true for x_lev_x.b:
mean is 3.333333e-01
slope is -1.442222e-16

For all the other variables as well as for everything in designTreatmenN example it all seems OK.

Is this an expected behavior?
Oddly the x_lev_x.b is coded with 0s and 1s, while other variables are fractional.

Thank you very much!

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.