Principled way of collapsing categorical variables with many levels? - Cross Validated most recent 30 from stats.stackexchange.com 2019-08-20T01:30:21Z https://stats.stackexchange.com/feeds/question/146907 http://www.creativecommons.org/licenses/by-sa/3.0/rdf https://stats.stackexchange.com/q/146907 57 Principled way of collapsing categorical variables with many levels? shadowtalker https://stats.stackexchange.com/users/36229 2015-04-17T13:31:28Z 2019-06-29T12:48:05Z <p><strong>What techniques are available for collapsing (or pooling) many categories to a few, for the purpose of using them as an input (predictor) in a statistical model?</strong></p> <hr> <p>Consider a variable like <a href="https://en.wikipedia.org/wiki/Major_(academic)" rel="noreferrer">college student major</a> (discipline chosen by an undergraduate student). It is unordered and categorical, but it can potentially have dozens of distinct levels. Let's say I want to use major as a predictor in a regression model.</p> <p>Using these levels as-is for modeling leads to all sorts of issues because there are just so many. A lot of statistical precision would be thrown away to use them, and the results are hard to interpret. We're rarely interested in specific majors -- we're much more likely to be interested in broad categories (subgroups) of majors. But it isn't always clear how to divide up the levels into such higher-level categories, or even how many higher-level categories to use.</p> <p>For typical data I would be happy to use factor analysis, matrix factorization, or a discrete latent modeling technique. But majors are mutually exclusive categories, so I'm hesitant to exploit their covariance for anything.</p> <p>Furthermore I don't care about the major categories on their own. I care about producing higher-level categories that are coherent <em>with respect to my regression outcome</em>. In the binary outcome case, that suggests to me something like linear discriminant analysis (LDA) to generate higher-level categories that maximize discriminative performance. But LDA is a limited technique and that feels like dirty data dredging to me. Moreover any continuous solution will be hard to interpret.</p> <p>Meanwhile something based on covariances, like multiple correspondence analysis (MCA), seems suspect to me in this case because of the inherent dependence among mutually exclusive dummy variables -- they're better suited for studying multiple categorical variables, rather than multiple categories of the same variable.</p> <p><strong>edit</strong>: to be clear, this is about <em>collapsing</em> categories (not selecting them), and the categories are predictors or independent variables. In hindsight, this problem seems like an appropriate time to "regularize 'em all and let God sort 'em out". Glad to see this question is interesting to so many people!</p> https://stats.stackexchange.com/questions/146907/-/237000#237000 41 Answer by amoeba for Principled way of collapsing categorical variables with many levels? amoeba https://stats.stackexchange.com/users/28666 2016-09-26T15:24:52Z 2016-09-26T23:36:13Z <p>If I understood correctly, you imagine a linear model where one of the predictors is categorical (e.g. college major); and you expect that for some subgroups of its levels (subgroups of categories) the coefficients might be exactly the same. So perhaps the regression coefficients for Maths and Physics are the same, but different from those for Chemistry and Biology.</p> <p>In a simplest case, you would have a "one way ANOVA" linear model with a single categorical predictor: $$y_{ij} = \mu + \alpha_i + \epsilon_{ij},$$ where $i$ encodes the level of the categorical variable (the category). But you might prefer a solution that collapses some levels (categories) together, e.g. $$\begin{cases}\alpha_1=\alpha_2, \\ \alpha_3=\alpha_4=\alpha_5.\end{cases}$$</p> <p>This suggests that one can try to use a regularization penalty that would penalize solutions with differing alphas. One penalty term that immediately comes to mind is $$L=\omega \sum_{i&lt;j}|\alpha_i-\alpha_j|.$$ This resembles lasso and should enforce sparsity of the $\alpha_i-\alpha_j$ differences, which is exactly what you want: you want many of them to be zero. Regularization parameter $\omega$ should be selected with cross-validation.</p> <hr> <p>I have never dealt with models like that and the above is the first thing that came to my mind. Then I decided to see if there is something like that implemented. I made some google searches and soon realized that this is called <em>fusion</em> of categories; searching for <a href="https://www.google.pt/webhp?sourceid=chrome-instant&amp;ion=1&amp;espv=2&amp;ie=UTF-8&amp;client=ubuntu#q=lasso+fusion+categorical"><code>lasso fusion categorical</code></a> will give you a lot of references to read. Here are a few that I briefly looked at:</p> <ul> <li><p>Gerhard Tutz, Regression for Categorical Data, see <a href="https://books.google.pt/books?id=hvxuqoxD00kC&amp;lpg=PA174&amp;ots=OYxYm9G-Eo&amp;dq=lasso%20fuse%20categories&amp;pg=PA174#v=onepage&amp;q=lasso%20fuse%20categories&amp;f=false">pp. 175-175 in Google Books</a>. Tutz mentions the following four papers:</p></li> <li><p><a href="http://cetus.stat.cmu.edu/tr/tr656/tr656.ps">Land and Friedman, 1997, Variable fusion: a new adaptive signal regression method</a></p></li> <li><p><a href="http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.482.6017&amp;rep=rep1&amp;type=pdf">Bondell and Reich, 2009, Simultaneous factor selection and collapsing levels in ANOVA</a></p></li> <li><p><strong><a href="http://projecteuclid.org/euclid.aoas/1294167814">Gertheiss and Tutz, 2010, Sparse modeling of categorial explanatory variables</a></strong></p></li> <li><p><a href="http://dept.stat.lsa.umich.edu/~jizhu/pubs/Tibs-JRSSB05.pdf">Tibshirani et al. 2005, Sparsity and smoothness via the fused lasso</a> is somewhat relevant even if not exactly the same (it is about ordinal variables)</p></li> </ul> <p>Gertheiss and Tutz 2010, published in the Annals of Applied Statistics, looks like a recent and very readable paper that contains other references. Here is its abstract:</p> <blockquote> <p>Shrinking methods in regression analysis are usually designed for metric predictors. In this article, however, shrinkage methods for categorial predictors are proposed. As an application we consider data from the Munich rent standard, where, for example, urban districts are treated as a categorial predictor. If independent variables are categorial, some modifications to usual shrinking procedures are necessary. Two $L_1$-penalty based methods for factor selection and clustering of categories are presented and investigated. The first approach is designed for nominal scale levels, the second one for ordinal predictors. Besides applying them to the Munich rent standard, methods are illustrated and compared in simulation studies.</p> </blockquote> <p>I like their Lasso-like solution paths that show how levels of two categorical variables get merged together when regularization strength increases:</p> <p><a href="https://i.stack.imgur.com/3ibkh.png"><img src="https://i.stack.imgur.com/3ibkh.png" alt="Gertheiss and Tutz 2010"></a></p> https://stats.stackexchange.com/questions/146907/-/260958#260958 10 Answer by Wayne for Principled way of collapsing categorical variables with many levels? Wayne https://stats.stackexchange.com/users/1764 2017-02-09T17:27:42Z 2017-02-09T17:27:42Z <p>I've wrestled with this on a project I've been working on, and at this point I've decided there really isn't a good way to fuse categories and so I'm trying a <a href="http://www.stat.columbia.edu/~gelman/research/published/multi2.pdf" rel="noreferrer">hierarchical/mixed-effects</a> model where my equivalent of your <em>major</em> is a random effect.</p> <p>Also, in situations like this there seem to actually be two fusing decisions to make: 1) how to fuse the categories you have when you fit the model, and 2) what fused category becomes "other" where you will by default include any new majors that someone dreams up after you fit your model. (A random effect can handle this second case automatically.)</p> <p>When the fusing has any judgement involved (as opposed to totally automated procedures), I'm skeptical of the "other" category which is often a grab bag of the categories with few things in them rather than any kind of principled grouping.</p> <p>A random effect handles a lot of levels, dynamically pools ("draws strength from") different levels, can predict previously-unseen levels, etc. One downside might be that the distribution of the levels is almost always assumed to be normal.</p> https://stats.stackexchange.com/questions/146907/-/298951#298951 7 Answer by shadowtalker for Principled way of collapsing categorical variables with many levels? shadowtalker https://stats.stackexchange.com/users/36229 2017-08-21T02:10:23Z 2018-11-28T13:05:07Z <p>One way to handle this situation is to recode the categorical variable into a continuous one, using what is known as "target coding" (aka "impact coding") . Let <span class="math-container">$Z$</span> be an input variable with categorical levels <span class="math-container">${z^1, ..., z^K }$</span>, and let <span class="math-container">$Y$</span> be the output/target/response variable. Replace <span class="math-container">$Z$</span> with <span class="math-container">$\operatorname{Impact}\left(Z\right)$</span>, where</p> <p><span class="math-container">$$\operatorname{Impact}\left(z^k\right) = \operatorname{E}\left(Y\ |\ Z = z^k\right) - \operatorname{E}\left(Y\right)$$</span></p> <p>for a continuous-valued <span class="math-container">$Y$</span>. For binary-valued <span class="math-container">$Y$</span>, use <span class="math-container">$\operatorname{logit} \circ \operatorname{E}$</span> instead of just <span class="math-container">$\operatorname{E}$</span>.</p> <p>There is a Python implementation in the <a href="http://contrib.scikit-learn.org/categorical-encoding/targetencoder.html#id1" rel="nofollow noreferrer">category_encoders</a> library .</p> <p>A variant called "impact coding" has been implemented in the R package <a href="https://cran.r-project.org/package=vtreat" rel="nofollow noreferrer">Vtreat</a> . The package (and impact coding itself) is described in an <a href="https://arxiv.org/abs/1611.09477" rel="nofollow noreferrer">article</a> by those authors from 2016 , and in several blog posts . Note that the current R implementation does not handle multinomial (categorical with more than 2 categories) or multivariate (vector-valued) responses.</p> <ol> <li>Daniele Micci-Barreca (2001). A Preprocessing Scheme for High-Cardinality Categorical Attributes in Classification and Prediction Problems. <em>ACM SIGKDD Explorations Newsletter</em>, Volume 3, Issue 1, July 2001, Pages 27-32. <a href="https://doi.org/10.1145/507533.507538" rel="nofollow noreferrer">https://doi.org/10.1145/507533.507538</a></li> <li>Category Encoders. <a href="http://contrib.scikit-learn.org/categorical-encoding/index.html" rel="nofollow noreferrer">http://contrib.scikit-learn.org/categorical-encoding/index.html</a></li> <li>John Mount and Nina Zumel (2017). vtreat: A Statistically Sound 'data.frame' Processor/Conditioner. R package version 0.5.32. <a href="https://CRAN.R-project.org/package=vtreat" rel="nofollow noreferrer">https://CRAN.R-project.org/package=vtreat</a></li> <li>Win-Vector (2017). vtreat. GitHub repository at <a href="https://github.com/WinVector/vtreat" rel="nofollow noreferrer">https://github.com/WinVector/vtreat</a></li> <li>Zumel, Nina and Mount, John (2016). vtreat: a data.frame Processor for Predictive Modeling. 1611.09477v3, <em>ArXiv e-prints</em>. Available at <a href="https://arxiv.org/abs/1611.09477v3" rel="nofollow noreferrer">https://arxiv.org/abs/1611.09477v3</a>.</li> <li><a href="http://www.win-vector.com/blog/tag/vtreat/" rel="nofollow noreferrer">http://www.win-vector.com/blog/tag/vtreat/</a></li> </ol> https://stats.stackexchange.com/questions/146907/-/384952#384952 2 Answer by Sealander for Principled way of collapsing categorical variables with many levels? Sealander https://stats.stackexchange.com/users/77505 2018-12-30T09:50:31Z 2018-12-30T09:50:31Z <p>The paper "<a href="https://dl.acm.org/citation.cfm?id=507538" rel="nofollow noreferrer">A preprocessing scheme for high-cardinality categorical attributes in classification and prediction problems</a>" leverages hierarchical structure in the category attributes in a nested 'empirical Bayes' scheme at every pool/level to map the categorical variable into a posterior class probability, which can be used directly or as an input into other models. </p> https://stats.stackexchange.com/questions/146907/-/384971#384971 5 Answer by Frank Harrell for Principled way of collapsing categorical variables with many levels? Frank Harrell https://stats.stackexchange.com/users/4253 2018-12-30T13:17:09Z 2018-12-30T13:17:09Z <p>If you have an auxiliary independent variable that is logical to use as an anchor for the categorical predictor, consider the use of Fisher's optimum scoring algorithm, which is related to his linear discriminant analysis. Suppose that you wanted to map the college major into a single continuous metric, and suppose that a proper anchor is a pre-admission SAT quantitative test score. Compute the mean quantitative score for each major and replace the major with that mean. You can readily extend this to multiple anchors, creating more than one degree of freedom with which to summarize major. </p> <p>Note that unlike some of the earlier suggestions, optimum scoring represents an unsupervised learning approach, so the degrees of freedom (number of parameters estimated against Y) are few and well defined, resulted in proper statistical inference (if frequentist, accurate standard errors, confidence (compatibility) intervals, and p-values).</p> <p>I do very much like the penalization suggestion by <a href="https://stats.stackexchange.com/users/28666/amoeba">https://stats.stackexchange.com/users/28666/amoeba</a> @amoeba.</p> https://stats.stackexchange.com/questions/146907/-/415304#415304 0 Answer by kjetil b halvorsen for Principled way of collapsing categorical variables with many levels? kjetil b halvorsen https://stats.stackexchange.com/users/11887 2019-06-29T12:48:05Z 2019-06-29T12:48:05Z <p>There are multiple questions here, and some of them are asked &amp; answered earlier. If the problem is computation taking a long time: There are multiple methods to deal with that, see <a href="https://stackoverflow.com/questions/3169371/large-scale-regression-in-r-with-a-sparse-feature-matrix">large scale regression with sparse feature matrix</a> and the paper <a href="https://www.r-project.org/conferences/useR-2010/abstracts/Maechler+Bates.pdf" rel="nofollow noreferrer">by Maechler and Bates</a>. </p> <p>But it might well be that the problem is with modeling, I am not so sure that the usual methods of treating categorical predictor variables really give sufficient guidance when having categorical variables with very many levels, see this site for the tag <code>[many-categories]</code>. There are certainly many ways one could try, one could be (if this is a good idea for your example I cannot know, you didn't tell us your specific application) a kind of hierarchical categorical variable(s), that is, inspired by the system used in biological classification, see <a href="https://en.wikipedia.org/wiki/Taxonomy_(biology)" rel="nofollow noreferrer">https://en.wikipedia.org/wiki/Taxonomy_(biology)</a>. There an individual (plant or animal) is classified first to Domain, then Kingdom, Phylum, Class, Order, Family, Genus and finally Species. So for each level in the classification you could create a factor variable. If your levels, are, say, products sold in a supermarket, you could create a hierarchical classification starting with [foodstuff, kitchenware, other], then foodstuff could be classified as [meat, fish, vegetables, cereals, ...] and so on. Just a possibility, which gives a prior hierarchy, not specifically related to the outcome.</p> <p>But you said: </p> <blockquote> <p>I care about producing higher-level categories that are coherent with respect to my regression outcome.</p> </blockquote> <p>Then you could try <em>fused lasso</em>, see other answers in this thread, which could be seen as a way of collapsing the levels into larger groups, entirely based on the data, not a prior organization of the levels as implied by my proposal of a hierarchical organization of the levels. </p>