Polynomial Feature Expansion

Version 88 | Created: 2026-09-09 | Updated: 2026-11-07 13:46 UTC
- 1. Purpose
- 2. Summary
- 3. Objective
- 4. Mechanism
- 5. Caution
- 6. Further Work
- References
- Appendix A. Terminology
- Appendix B. Covariance
- Appendix C. Correlation Of A Variable And Its Square
- Appendix D. Term Count Derivation
- Appendix E. Ridge And Lasso On Expanded Columns
- Appendix F. Implementation
Polynomial feature expansion is the operation that builds both the powers of one variable and the products of distinct variables. This document covers modelling the non-linear behaviour of numeric tabular data with those two kinds of column.
- Problem Statement: Numeric tabular data has cases that are hard to express with a linear model.
-
Goal: To build a non-linear model by adding the power terms of the original variables (
$x^2$ ,$x^3$ ) and the interaction terms ($x_1 \ast x_2$ ). - Non-Goal: Derived variables are not covered, and the learning on the expanded data set is not covered.
An expansion computes products and powers from the columns already in the table and appends them as new columns, leaving the rows as they are and growing only the columns. A table with the columns
What it costs is the rising column count. Once the column count nears the row count the coefficients, the
To lessen that curse of dimensionality, the three below are set as the defaults. A default is what is kept until the data gives a reason to do otherwise, and together the three leave the column count well under the row count and keep those
- Degree 2 — The terms built are limited to the square of one variable and the product of two (section 5.1).
- Standardization — Each column is brought to mean 0 and standard deviation 1 before and after the expansion. Subtracting the mean lowers the correlation between the columns and leaves the coefficients readable; dividing by the standard deviation removes the differences in column size, so the penalty falls evenly (sections 4.2, 4.3 and 5.2).
-
Penalty — The expanded columns carry a ridge or a lasso. Ridge divides every
$\beta$ by the same factor without ever reaching zero, and lasso sets the small ones to exactly zero (section 5.2).
Standardization and the penalty are the two that get skipped. In uncentered physical units the correlation between
Where the expansion should not be used is equally clear. Past a few dozen variables the column count passes the sample count, a shape that bends several times inside one variable calls for a spline rather than a higher degree, and where prediction outside the training range is needed the way a polynomial diverges beyond that range, its extrapolation behaviour, is itself the risk.
An expansion is aimed at two things, a non-linear relationship inside one variable and an interaction between variables, neither of which a linear model expresses. The first is carried by a power term, the second by an interaction term, and both are put into the columns so that the model itself stays linear.
The non-linear relationship inside one variable is carried by the powers of that variable, its power terms. Adding
Linear here is about the coefficients
The interaction between variables is carried by the product of two distinct variables, an interaction term. Adding the product
The product term lets one variable change the slope of another. Differentiating equation (2) with respect to
Where
The columns an expansion makes are monomials, terms formed by multiplying powers of the raw variables. With
For
Bring each column to mean 0 and standard deviation 1 before expanding.
Definition: Standardization
Subtracting the mean from each column and dividing by its standard deviation, so that the column has mean 0 and standard deviation 1, is standardization.
Definition: Centering
The part of standardization that subtracts the mean alone is centering.
The two parts do different work. Subtracting the mean lowers the correlation between the columns and leaves the coefficients readable, which is the two paragraphs below; dividing by the standard deviation removes the differences in column size, and that part is sections 4.3 and 5.2.
The first reason to center is the drop in correlation. For two variables
Setting
Centering takes
The difference between the two equations is the ground for centering. Raise
The second reason to center is interpretation. On centered data
Centering lowers the correlation, though, without removing it. The collinearity an expansion manufactures is a property of the expansion rather than of the data, so a penalty is needed alongside it (section 5.2).
Conditioning is how sensitive solving the design matrix is to a small error in the input, and the number that measures it is the condition number.
The design matrix is the matrix whose rows are the observations and whose columns are the terms the model uses. The least squares of section 3.1 picks the
The definition is equation (11). For a linear system
A condition number is therefore not a ratio of input to output but a bound on how far a relative error grows. The values in this document are the condition number
What raises the condition number is the degree and the collinearity between the columns; what lowers it is standardization. Subtracting the mean cuts the overlap between the columns and dividing by the standard deviation removes the differences in their size, so both parts are needed to take the condition number lowest.
Keep a product term, and the main effects composing it stay as well. The rule is called heredity, and its ground is the coordinate system rather than statistics.
Substituting the shift
On the right of equation (13),
An expansion charges two prices.
- The column count — It grows fast, which invites overfitting, a model that fits the training data and misses new data, and raises the cost of the fit. The degree holds it down (section 5.1).
- Unsettled coefficients — The columns an expansion makes resemble one another, so the coefficients move far with the sample. A penalty holds them down (section 5.2).
The column count grows as the interaction_only, which keeps only products of distinct variables, has that of equation (15).
Both counts are derived from the set of equation (4) in Appendix D.
Table 1. Column count after expansion, original variables included and bias column excluded
|
|
|
|
|
|
|---|---|---|---|---|
| 2 | 5 | 3 | 9 | 3 |
| 5 | 20 | 15 | 55 | 25 |
| 10 | 65 | 55 | 285 | 175 |
| 100 | 5,150 | 5,050 | 176,850 | 166,750 |
What Table 1 says is that interaction_only saves little. At
What actually sets the column count is the degree. Raising
The degree is therefore chosen on the error over data kept out of the fit, the held-out error, rather than on theory, and the candidates are few. It is 2 in almost every practical case, data that needs 3 is rare, and a degree of 4 or more that appears to win is a sign that something other than an expansion should be used.
The expanded columns always carry a penalty, a term added to the fitting criterion that charges for the size of the coefficients. The expansion raises the column count and at the same time makes columns that resemble one another, and unpenalized least squares absorbs that resemblance into two large coefficients that cancel, which is why the fit moves far on a small disturbance of the data. Ridge answers it with a penalty proportional to the sum of the squared coefficients, which is what stops the two large coefficients from cancelling [3].
Ridge is the default of the two. It divides the coefficient among the columns that resemble one another and steadies the prediction, while lasso keeps one of them and drops the rest. Lasso on expanded columns can keep a product term while deleting its main effects, breaking the heredity of section 4.4, so it is used with a hierarchical constraint rather than on its own [6].
That ridge never drives a coefficient to zero means no column can be dropped with it. It is still the default because what a penalty buys on an expansion is not a smaller column count but a steadier prediction, and the size of that is the held-out RMSE of section 5.1 falling from 1.08 to 0.75 at degree 3. Where the column count itself has to come down, that is the work of lasso or elastic net.
The penalty acts on the size of a column, so it is applied after the expanded columns are standardized, which is what puts the second standardization into the pipeline of Appendix F. The objectives of the three penalties, and how far each of them moves a coefficient, are in Appendix E.
Fig 1 measures on one data set what the three sections before it state: (a) degree and extrapolation (section 5.1), (b) the condition number (section 4.3), and (c) the held-out error as the column count reaches the row count, with what a penalty buys (section 5.2).
Fig 1. Degree and extrapolation, conditioning, and the cost of expansion
Fig 1(a) is the reason to keep the degree low. Degrees 2, 5 and 9 are fitted to 60 samples; inside the training range (grey) degrees 5 and 9 are both plausible, and outside it the higher degree diverges first. The behaviour of a polynomial beyond its range is governed by its top term, so raising the degree where extrapolation is needed improves the fit inside the training range while the error outside it grows.
Fig 1(b) draws the condition numbers of section 4.3 against degree, and Fig 1(c) is the relation between the term count and the row count. On data with 5 variables, 60 rows and a true model holding one product term, the held-out RMSE, that error measured as the root of the mean squared error, falls from 1.34 at degree 1 to 0.34 at degree 2 and returns to 1.08 at degree 3. The 55 columns of degree 3 nearly reach the 60 rows. Ridge is at 0.75 in the same place, stopping close to half of that deterioration.
An expansion fails in six recognizable ways. Most arrive not as a model that fits badly but as coefficients or predictions that turn unstable.
Table 2. Failure modes of a polynomial expansion
| # | Symptom | Cause | Countermeasure |
|---|---|---|---|
| 1 | Held-out error worse at degree 2 than at degree 1 | Term count close to the row count | Ridge or lasso, interaction_only, selective expansion |
| 2 | Coefficient signs flipping across resamples | Collinearity manufactured by the expansion | Centering, a penalty, reading predictions instead of coefficients |
| 3 | Prediction diverging just outside the training range | Extrapolation behaviour of a polynomial | Spline, a range guard on the input, no extrapolation |
| 4 | A handful of rows dominating the fit | Squares amplifying leverage | Outlier handling before expansion, robust loss |
| 5 | Duplicate or all-zero columns | Dummy columns squared and crossed | interaction_only=True, expansion restricted to continuous columns |
| 6 | Imputed values amplified | Imputation error squared inside a product | Imputation before expansion, an indicator column for what was imputed |
Row 5 of Table 2, the duplicate and all-zero columns that come out of dummy columns, is written out separately because the expansion does not catch it on its own. A categorical variable is turned into numbers by giving each category a column that holds 1 where the row falls in that category and 0 otherwise, a dummy. A dummy squared is itself and becomes an exactly duplicated column, and the product of two dummies from the same categorical variable is always zero, since one row cannot fall in two categories at once. The expansion knows none of this, so columns coming from a categorical variable are either left out of the expansion or handled with interaction_only.
Whether an expansion helped is confirmed in four ways.
- The held-out error curve drawn while raising the degree from 1. Watch whether the minimum stays at 2 or below.
- The condition number of the expanded design matrix and the VIF (Variance Inflation Factor) of each column. The VIF of column
$j$ is$1 / (1 - R_j^2)$ on the$R_j^2$ of that column regressed on the rest, the factor by which the variance of$\hat{\beta}_j$ is inflated over the orthogonal case ($R_j^2 = 0.9$ gives 10). Where the condition number reads the whole matrix as one number, the VIF names the column that overlaps, and a large value after centering calls for a penalty. - The share of samples redrawn from the data with replacement, the bootstrap, in which a coefficient keeps its sign. A product term whose sign flips is not interpreted.
- The residual plotted against the product terms. Confirm that the structure left before the expansion is gone.
- Sparse polynomial chaos expansion — A way to cut a high-degree expansion down to a size that can be carried, by selecting terms sparsely over a basis of mutually orthogonal polynomials [10]. Selecting the terms by least angle regression has settled into a procedure, which makes keeping a few dozen out of several hundred candidates computationally practical. Starting needs a distributional assumption on the input variables (the basis follows that distribution) and a designed sample.
- Hierarchical interaction selection at scale — The lasso family that selects product terms with heredity imposed as a convex constraint [6]. Convex means the optimum found is the only one, and it solves up to several hundred variables, so the rule of section 4.4 can be enforced by the optimization rather than by a person. Starting needs a rule that narrows the candidate product terms in advance and a computational budget.
- Learned basis — A model that stacks one-dimensional functions learned from the data in place of a fixed monomial basis [11]. A spline-based implementation was released in 2024, which makes a direct comparison with an expansion plus ridge on the same data possible. Starting needs a held-out comparison procedure and a criterion for whether the learned basis is excessive for the sample count.
[1] Box, G. E. P. and Wilson, K. B. (1951). On the Experimental Attainment of Optimum Conditions. Journal of the Royal Statistical Society: Series B, 13(1), 1–38.
[2] Marquardt, D. W. (1980). Comment: You Should Standardize the Predictor Variables in Your Regression Models. Journal of the American Statistical Association, 75(369), 87–91.
[3] Hoerl, A. E. and Kennard, R. W. (1970). Ridge Regression: Biased Estimation for Nonorthogonal Problems. Technometrics, 12(1), 55–67.
[4] Nelder, J. A. (1998). The Selection of Terms in Response-Surface Models—How Strong is the Weak-Heredity Principle? The American Statistician, 52(4), 315–318.
[5] Chipman, H. (1996). Bayesian variable selection with related predictors. The Canadian Journal of Statistics, 24(1), 17–36.
[6] Bien, J., Taylor, J. and Tibshirani, R. (2013). A lasso for hierarchical interactions. The Annals of Statistics, 41(3), 1111–1141.
[7] Pedregosa, F., Varoquaux, G., Gramfort, A., Michel, V., Thirion, B., Grisel, O., Blondel, M., Prettenhofer, P., Weiss, R., Dubourg, V., Vanderplas, J., Passos, A., Cournapeau, D., Brucher, M., Perrot, M. and Duchesnay, É. (2011). Scikit-learn: Machine Learning in Python. Journal of Machine Learning Research, 12, 2825–2830.
[8] Rahimi, A. and Recht, B. (2007). Random Features for Large-Scale Kernel Machines. Advances in Neural Information Processing Systems, 20.
[9] Friedman, J. H. and Popescu, B. E. (2008). Predictive learning via rule ensembles. The Annals of Applied Statistics, 2(3), 916–954.
[10] Blatman, G. and Sudret, B. (2011). Adaptive sparse polynomial chaos expansion based on least angle regression. Journal of Computational Physics, 230(6), 2345–2367.
[11] Liu, Z., Wang, Y., Vaidya, S., Ruehle, F., Halverson, J., Soljačić, M., Hou, T. Y. and Tegmark, M. (2024). KAN: Kolmogorov-Arnold Networks. arXiv:2404.19756.
[12] Tibshirani, R. (1996). Regression Shrinkage and Selection via the Lasso. Journal of the Royal Statistical Society: Series B, 58(1), 267–288.
[13] Zou, H. and Hastie, T. (2005). Regularization and variable selection via the elastic net. Journal of the Royal Statistical Society: Series B, 67(2), 301–320.
- collinearity: The state in which two or more columns point in nearly the same direction, so that their coefficients cannot be estimated apart.
- condition number: The ratio of the largest singular value of a matrix to the smallest. It says how far a small error in the input is magnified in the solution.
- curse of dimensionality: The exponential growth, as the number of columns rises, in the number of observations needed to cover the space at one density.
-
degree: The highest degree of a monomial the expansion admits. The degree of
$X_1^2 X_2$ is 3. - derived variable: A variable built from two or more columns by domain knowledge, such as a ratio or a rate.
- design matrix: The matrix whose rows are the observations and whose columns are the terms the model uses. The coefficients come from solving it.
- dummy: A column holding 1 where a row falls in one category of a categorical variable and 0 otherwise.
- extrapolation: Prediction over an input range the training data does not cover.
- held-out: Data kept out of the fit and used only to measure the error of the fitted model.
- heredity: The rule that a product term put into a model brings the lower-degree terms composing it with it.
- imputation: Filling a missing value with another, such as the mean of that column or the prediction of a model.
- leverage: How strongly one observation pulls its own fitted value. It grows as the input sits further from the centre.
-
main effect: The first-order term of a single variable,
$\beta_i x_i$ . -
monomial: A term formed by multiplying powers of the variables.
$X_1^2 X_2$ is one. - overfitting: The state in which a model fits the training data while missing new data.
- penalty: A term added to the fitting criterion that charges for the size of the coefficients, as ridge and lasso do.
- RMSE: The square root of the mean squared error (Root Mean Squared Error).
- standardization: Subtracting from each column its own mean and dividing by its standard deviation, bringing it to mean 0 and standard deviation 1.
-
VIF: The variance inflation factor, computed from the
$R^2$ of one column regressed on the rest. It is$1/(1-R^2)$ .
A covariance measures how far two columns move together. Its definition on a population is equation (16), where
Multiplying out under the properties of the expectation gives equation (6), the form that is easier to compute and the one section 4.2 uses: the expected value of the product, less the product of the expected values.
Measured on a sample of
The sign, and the covariance of a variable with itself, say four things.
- At
$\mathrm{Cov}(X, Y) \gt 0$ ,$Y$ rises as$X$ rises. - At
$\mathrm{Cov}(X, Y) \lt 0$ ,$Y$ falls as$X$ rises. - At
$\mathrm{Cov}(X, Y) = 0$ there is no linear relation between the two. -
$\mathrm{Cov}(X, X)$ is the variance$\mathrm{Var}(X)$ .
Section 4.2 and the derivation in Appendix C use the mean divided by
Section 4.2 sets
The reason to divide is units. Scaling a column
The numerator comes first. Equation (6) at
Substituting
Putting equation (20) into equation (19) gives equation (21).
The
The two terms of equation (22) come from different places. The first,
What is left is the two standard deviations of the denominator.
The
Substituting the three, and taking the square root of equation (23) since a standard deviation is the root of a variance, writes the numerator and the two denominators as equation (24).
Put the three into equation (7) and
Both
Raise
Set notation comes first. A set is written either by listing its elements, as in
Equation (4), from section 4.1, is repeated here.
Equation (4) is dense in notation but simple to read. On the left,
With two variables and
Table 3. Exponent pairs admitted by equation (4) at two variables and degree 2
| Exponent of |
Exponent of |
Degree | Term |
|---|---|---|---|
| 1 | 0 | 1 | |
| 0 | 1 | 1 | |
| 2 | 0 | 2 | |
| 1 | 1 | 2 | |
| 0 | 2 | 2 |
The one pair left out is
Equation (4) defines the set of columns to be built without saying how large it is. That size is equation (14) and equation (15), derived below.
One monomial of degree exactly
The count itself is stars and bars. Take the degree
At
Summing the degrees from 0 to
The set of equation (4) excludes the constant term at
With interaction_only no variable is used twice, so a surviving term corresponds to one subset of the
The penalty on the expanded columns is one of three. Written as an objective, ridge is equation (28) and lasso is equation (29) [12], where
The shape of the penalty is the whole difference. Where the columns are standardized and orthogonal the two solutions close in equation (30): ridge divides every coefficient by the same factor and never reaches zero, while lasso sets to exactly zero every coefficient smaller in size than
Expanded columns are far from orthogonal (section 4.2) and come in groups that resemble one another. Ridge spreads one coefficient across such a group; lasso keeps one member and zeroes the rest, and which member survives changes with the sample, so the list of terms lasso returns is itself unstable. Elastic net, equation (31) [13], mixes the two by
Table 4. Penalties on expanded columns
| Penalty | Term added | A group of columns that resemble one another | Where it fits |
|---|---|---|---|
| Ridge | Sum of the squared coefficients | Coefficient shared across the group | The default on expanded columns |
| Lasso | Sum of the absolute coefficients | One kept, the rest at zero | A short term list, under a heredity constraint |
| Elastic net | Both, mixed by |
Kept or dropped together | Selection wanted with a list that holds |
RidgeCV, LassoCV and ElasticNetCV search over. The intercept is left out of the penalty: penalizing it pulls the fitted level toward zero and moves the model off the centre of the data.
A penalty does not buy a degree of 4. What it buys is the difference between a fit that survives a column count close to the row count and one that does not, and section 5.1 gives the size of that difference.
The expansion itself is one line of sklearn.preprocessing.PolynomialFeatures, and only four arguments have to be settled [7].
Table 5. PolynomialFeatures arguments
| Argument | Effect | Note |
|---|---|---|
degree |
Highest degree of the monomials | A (min, max) tuple for the lowest degree as well, so (2, 2) for second-order terms only |
interaction_only |
Products of distinct variables only | First-order terms kept, powers of a single variable dropped |
include_bias |
A constant column of ones | False where the estimator carries its own intercept |
order |
Memory layout of the output array | 'C' or 'F', a choice of layout rather than of content |
# Python
from sklearn.preprocessing import PolynomialFeatures
# interaction_only=True keeps X1*X2 and drops X1^2, X2^2
poly = PolynomialFeatures(degree=2, interaction_only=True, include_bias=False)
X_expanded = poly.fit_transform(X)
term_name = poly.get_feature_names_out()The names get_feature_names_out() returns are the only route from a coefficient back to its column. Lose them after the expansion and the coefficients remain while which product each belongs to cannot be said.
An expansion is not used alone but placed between standardization and the penalized fit. The order is standardize the raw variables, expand, standardize the expanded columns again, then fit with a penalty.
The first standardization removes the conditioning problem of section 4.3, and the second makes the penalty fall evenly across the columns. The variance of a product term is close to the product of the raw variances and so differs widely from column to column; without the second standardization a ridge penalty lands almost entirely on the columns with the largest variance.
# Python
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
pipeline = Pipeline([
('raw_scale', StandardScaler()),
('expand', PolynomialFeatures(include_bias=False)),
('term_scale', StandardScaler()),
('fit', Ridge()),
])
grid = {'expand__degree': [1, 2, 3], 'fit__alpha': [0.1, 1.0, 10.0, 100.0]}
search = GridSearchCV(pipeline, grid, scoring='neg_root_mean_squared_error', cv=5)
search.fit(X, y)Putting the expansion inside the pipeline is not a convenience. The expansion is row-wise and leaks nothing by itself, but the standardizations on either side of it must take their means and variances from the training part of each fold, the pieces cross-validation splits the data into. Choosing the degree and the penalty together also finishes in one search only inside the pipeline.
The cost of an expansion is linear in the column count, and that count grows by equation (14). At 100,000 rows, 100 variables and
The first is the kernel. The polynomial kernel of equation (32) computes the inner product of the expanded space without the expansion.
KernelRidge(kernel='poly') is that form, and since the cost falls on rows rather than on columns it suits data with many variables and few rows. What it costs is interpretation: no coefficient attaches to an individual monomial, so which product contributed cannot be read.
The second is approximation. PolynomialCountSketch compresses the terms a polynomial kernel uses into a fixed number of columns, a sketch, and Nystroem approximates the kernel matrix from a subset of the samples. Both belong to the family that approximates a kernel with a finite number of columns to keep the speed of a linear model [8], and both bound the column count at a value the user sets.
Sparse input is taken as it is. Feed in a CSR matrix, which stores only the non-zero values, and the expansion comes back in the same form, so data carrying many dummy columns does not inflate into a dense array.
Not every pair has to be built. Hand the expansion the columns to be crossed and the column count ends at the number chosen rather than at Table 1.
# Python
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import PolynomialFeatures
expand_column = ['temperature', 'pressure']
transformer = ColumnTransformer(
[('expand', PolynomialFeatures(degree=2, include_bias=False), expand_column)],
remainder='passthrough',
)There are three grounds for choosing: an interaction the process already knows, a residual that shows structure over a combination of two variables, and a tree ensemble, several trees combined into one model, run first to measure interaction strength so that only the leading pairs are kept [9]. With none of the three, a penalty on the full expansion is the better move. Choosing pairs without grounds lets the analyst rather than the data decide which interactions reach the model.
Version 91 | Created: 2026-09-07 | Updated: 2026-11-07 13:46 UTC
- 1. Purpose
- 2. Summary
- 3. Objective
- 4. Mechanism
- 5. Caution
- 6. Further Work
- References
- Appendix A. Terminology
- Appendix B. Covariance
- Appendix C. Correlation Of A Variable And Its Square
- Appendix D. Term Count Derivation
- Appendix E. Ridge And Lasso On Expanded Columns
- Appendix F. Implementation
Polynomial feature expansion 은 한 변수의 거듭제곱과 서로 다른 변수의 곱을 함께 만드는 연산이다. 이 문서는 그 두 가지 열로 numeric tabular data 의 non-linear behavior 를 model 에 담는 방법을 다룬다.
- Problem Statement: Numeric tabular data 에서 선형 model 로는 표현하기 힘든 경우가 있다.
-
Goal: Original variable 의 power term (
$x^2$ ,$x^3$ ) 와 interaction term ($x_1 \ast x_2$ ) 을 추가하여 비선형 model 을 만든다. - Non-Goal: Derived variable 은 다루지 않고, expanded data set 의 학습을 다루지 않는다.
Expansion 은 표에 이미 있는 열로 곱과 제곱을 계산해 새 열로 붙이는 연산이며, 행은 그대로 두고 열만 늘린다. 열이
대가는 열의 개수 증가이다. 열 수가 행 수에 근접하면 계수, 곧 각 열에 곱해지는
이 차원의 저주를 감소시키기 위해서, 아래 세 가지를 기본으로 둔다. 기본이란 자료에서 달리 할 근거가 나오기 전까지 그대로 쓰는 설정이라는 뜻이며, 셋을 함께 두면 열 수가 행 수보다 충분히 적게 남고 표본을 다시 뽑아도 그
- Degree 2 — 만들 항을 한 변수의 제곱과 두 변수의 곱까지로 제한한다 (5.1 절).
- Standardization — Expansion 앞뒤로 각 열을 평균 0, 표준편차 1 로 맞춘다. 평균을 빼면 열 사이의 상관이 낮아지고 계수를 읽을 수 있게 되며, 표준편차로 나누면 열마다 다른 크기가 없어져 penalty 가 공평하게 걸린다 (4.2, 4.3, 5.2 절).
-
Penalty — Expansion 이 만든 열에 ridge 나 lasso 를 건다. Ridge 는 모든
$\beta$ 를 같은 비율로 줄일 뿐 0 으로 만들지 않고, lasso 는 작은$\beta$ 를 정확히 0 으로 만든다 (5.2 절).
세 가지 가운데 자주 빠지는 것은 standardization 과 penalty 다. Centering 하지 않은 물리 단위에서
Expansion 을 쓰지 않아야 하는 자리도 분명하다. 변수가 수십 개를 넘으면 열 수가 표본 수를 넘고, 한 변수 안에서 여러 번 꺾이는 모양이 필요하면 degree 를 올리는 대신 spline 으로 가야 하며, 훈련 구간 밖을 예측해야 하면 그 구간 밖에서 다항식이 폭주하는 성질, 곧 extrapolation 이 그대로 위험이 된다.
Expansion 이 노리는 것은 두 가지다. 한 변수 안의 비선형 관계와 변수 사이의 상호작용이며, 선형 model 은 둘 다 표현하지 못한다. 앞의 것은 power term 이, 뒤의 것은 interaction term 이 맡으며, 둘 다 열로 만들어지므로 model 자체는 선형으로 남는다.
한 변수 안의 비선형 관계는 그 변수의 거듭제곱, 곧 power term 이 맡는다. 변수
여기서 선형이라는 말은
변수 사이의 상호작용은 서로 다른 두 변수의 곱, 곧 interaction term 이 맡는다. 변수
곱항은 한 변수의 기울기를 다른 변수가 바꾸도록 허용한다. 식 (2) 를
Expansion 이 만드는 열은 원 변수의 거듭제곱을 곱한 항, 곧 monomial 이다. 변수가
변수가
Expansion 전에 각 열을 평균 0, 표준편차 1 로 맞춘다.
Definition: Standardization
각 열에서 평균을 빼고 표준편차로 나누어 평균 0, 표준편차 1 로 맞추는 것을 standardization 이라 한다.
Definition: Centering
Standardization 가운데 평균을 빼는 부분만 따로 centering 이라 한다.
두 부분이 하는 일은 다르다. 평균을 빼면 열 사이의 상관이 낮아지고 계수를 읽을 수 있게 되며, 이것이 아래 두 문단이다. 표준편차로 나누면 열마다 다른 크기가 없어지고, 그 몫은 4.3 절과 5.2 절에 있다.
Centering 의 첫 번째 이유는 상관의 감소다. 두 변수
여기에
Centering 은
두 식의 차이가 centering 이 상관을 낮추는 근거다. 식 (8) 에서
Centering 의 두 번째 이유는 해석이다. Centering 한 자료에서
다만 centering 은 상관을 낮출 뿐 없애지 못한다. Expansion 이 만든 collinearity 는 자료의 성질이 아니라 expansion 자체의 성질이므로, penalty 가 함께 필요하다 (5.2 절).
Conditioning 은 design matrix 를 푸는 일이 입력의 작은 오차에 얼마나 민감한지를 말하며, 그것을 재는 값이 조건수 (condition number) 다.
Design matrix 는 행이 관측이고 열이 model 이 쓰는 항인 행렬이다. 3.1 절의 최소제곱은 잔차 제곱합을 가장 작게 하는
조건수의 정의는 식 (11) 이다. 연립방정식
곧 조건수는 입력과 출력의 비가 아니라 상대오차가 커지는 배수의 상한이다. 이 문서가 적는 값은 design matrix 의 조건수
조건수를 올리는 것은 degree 와 열 사이의 collinearity 이고, 내리는 것은 standardization 이다. 평균을 빼면 열 사이의 겹침이 줄고 표준편차로 나누면 열마다 다른 크기가 없어지므로, 두 부분을 함께 해야 조건수가 가장 낮아진다.
곱항을 남기면 그 곱을 이루는 두 변수의 1차 항, 곧 main effect 도 함께 남긴다. 이 규칙을 heredity 라 하며, 근거는 통계가 아니라 좌표계에 있다.
식 (13) 의 오른쪽에서
Expansion 의 대가는 두 가지다.
- 열 수 — 열 수가 빠르게 늘어 overfitting, 곧 훈련 자료에는 맞지만 새 자료에서는 어긋나는 상태를 부르고 계산 비용을 올린다. Degree 로 잡는다 (5.1 절).
- 계수의 흔들림 — Expansion 이 만든 열이 서로 닮아 계수가 표본에 따라 크게 움직인다. Penalty 로 잡는다 (5.2 절).
열의 수는 변수의 수에 대해 interaction_only 의 열 수는 식 (15) 이다.
두 식은 모두 식 (4) 의 집합에서 나오며, 그 유도는 Appendix D 에 있다.
Table 1. Column count after expansion, original variables included and bias column excluded
|
|
|
|
|
|
|---|---|---|---|---|
| 2 | 5 | 3 | 9 | 3 |
| 5 | 20 | 15 | 55 | 25 |
| 10 | 65 | 55 | 285 | 175 |
| 100 | 5,150 | 5,050 | 176,850 | 166,750 |
Table 1 에서 읽을 것은 interaction_only 가 줄여 주는 몫이 작다는 사실이다.
열 수를 실제로 정하는 것은 degree 다.
그래서 degree 는 이론이 아니라 적합에 쓰지 않고 남겨 둔 자료의 오차, 곧 held-out 오차로 고르며, 후보는 좁다. 실무의 거의 모든 경우에 2 이고, 3 이 필요한 자료는 드물며, 4 이상이 이기는 것처럼 보이면 expansion 이 아니라 다른 방법을 써야 한다는 신호다.
Expansion 이 만든 열에는 penalty 를 반드시 함께 건다. Penalty 는 계수의 크기에 값을 매겨 적합 기준에 더하는 항이다. Expansion 은 열 수를 늘리는 동시에 서로 닮은 열을 만드는데, penalty 없는 최소제곱은 그 닮음을 서로 상쇄하는 두 개의 큰 계수로 흡수하며, 그래서 자료가 조금만 흔들려도 적합이 크게 움직인다. Ridge 는 계수 제곱합에 비례하는 penalty 를 걸어 그 상쇄를 막는다 [3].
둘 중 기본은 ridge 다. Ridge 는 닮은 열들에 계수를 나누어 주어 예측을 안정시키고, lasso 는 그 가운데 하나만 남기고 나머지를 지운다. Expansion 이 만든 열에서 lasso 는 곱항을 남기고 그 main effect 를 지워 4.4 절의 heredity 를 깨뜨릴 수 있으므로, 홀로 쓰기보다 계층 제약과 함께 쓴다 [6].
Ridge 가 계수를 0 으로 만들지 않는다는 것은 ridge 로는 열을 지울 수 없다는 뜻이다. 그래도 기본으로 두는 이유는 expansion 에서 penalty 가 버는 것이 열의 개수가 아니라 예측의 안정이기 때문이며, 그 크기는 5.1 절의 degree 3 에서 held-out RMSE 가 1.08 에서 0.75 로 내려가는 차이다. 열의 개수를 실제로 줄여야 하면 그것은 lasso 나 elastic net 의 몫이다.
Penalty 는 열의 크기에 걸리므로 expansion 이 만든 열을 standardization 한 뒤에 적용하며, Appendix F 의 pipeline 에 두 번째 standardization 이 들어가는 이유가 그것이다. 세 penalty 의 목적 함수와 각각이 계수를 얼마나 움직이는지는 Appendix E 에 있다.
Fig 1 은 앞의 세 꼭지가 말한 것을 한 자료에서 잰 그림이다. (a) 는 degree 와 extrapolation (5.1 절), (b) 는 조건수 (4.3 절), (c) 는 열 수가 행 수에 닿을 때의 held-out 오차와 penalty 의 효과 (5.2 절) 다.
Fig 1. Degree and extrapolation, conditioning, and the cost of expansion
Fig 1(a) 는 degree 를 낮게 두는 이유다. 60 개 표본에 degree 2, 5, 9 를 맞춘 것으로, 훈련 구간 (회색) 안에서는 degree 5 와 9 가 모두 그럴듯하지만 구간을 벗어나면 차수가 높은 곡선이 먼저 폭주한다. 다항식의 바깥 거동은 최고차항이 지배하므로, extrapolation 이 필요한 곳에서 degree 를 올리면 훈련 구간 안의 적합은 좋아져도 구간 밖 예측의 오차는 커진다.
Fig 1(b) 는 4.3 절의 조건수를 차수별로 그린 것이고, Fig 1(c) 는 항 수와 행 수의 관계다. 변수 5 개, 행 60 개, 참 model 이 곱항 하나인 자료에서 held-out RMSE, 곧 그 오차를 제곱 평균의 제곱근으로 잰 값은 degree 1 의 1.34 에서 degree 2 의 0.34 로 내려갔다가 degree 3 에서 1.08 로 되돌아간다. degree 3 의 열 수는 55 로 행 수 60 에 거의 닿는다. 같은 자리에서 ridge 는 0.75 여서 그 악화의 절반 가까이를 막는다.
Expansion 이 실패하는 모습은 여섯 가지로 정리된다. 대부분은 model 이 못 맞추는 모습이 아니라 계수나 예측이 불안정해지는 모습으로 온다.
Table 2. Failure modes of a polynomial expansion
| # | Symptom | Cause | Countermeasure |
|---|---|---|---|
| 1 | Degree 2 의 held-out 오차가 degree 1 보다 나쁨 | 항 수가 행 수에 가까움 | Ridge 나 lasso, interaction_only, 선택적 expansion |
| 2 | 표본을 다시 뽑을 때마다 계수의 부호가 뒤집힘 | Expansion 이 만든 collinearity | Centering, penalty, 계수 대신 예측을 읽기 |
| 3 | 훈련 구간을 조금 벗어나면 예측이 폭주함 | 다항식의 extrapolation 거동 | Spline, 입력 범위 검사, extrapolation 하지 않기 |
| 4 | 몇 개의 행이 적합을 지배함 | 제곱항이 leverage 를 키움 | Expansion 전 이상치 처리, robust loss |
| 5 | 중복된 열이나 값이 모두 0 인 열 | Dummy 열의 제곱과 곱 | interaction_only=True, 연속형 열만 expansion |
| 6 | Imputation 으로 채운 값이 증폭됨 | 곱 안에서 제곱된 imputation 오차 | Expansion 전 imputation, 대체 여부를 적는 지시 열 |
Table 2 의 5 행, 곧 dummy 열에서 나오는 중복된 열과 값이 모두 0 인 열은 expansion 이 스스로 걸러 주지 않으므로 따로 적는다. 범주형 변수는 범주 하나에 열 하나를 두고 그 범주면 1, 아니면 0 을 적어 수치로 바꾸며, 그 열을 dummy 라 한다. Dummy 는 제곱이 자기 자신이어서 완전히 중복된 열이 되고, 한 행이 두 범주에 함께 속할 수 없으므로 같은 범주형 변수에서 나온 두 dummy 의 곱은 언제나 0 이다. Expansion 은 그것을 알지 못하므로, 범주형에서 나온 열은 expansion 대상에서 빼거나 interaction_only 로 다루어야 한다.
Expansion 이 도움이 되었는지는 네 가지로 확인한다.
- Degree 를 1 부터 올리며 그린 held-out 오차 곡선. 최저점이 2 를 넘지 않는지 본다.
- Expansion 뒤 design matrix 의 조건수와 열별 VIF (Variance Inflation Factor). VIF 는 열
$j$ 를 나머지 열로 회귀해 얻은$R_j^2$ 로$1 / (1 - R_j^2)$ 이며, 그 열이 나머지와 직교한 경우에 비해$\hat{\beta}_j$ 의 분산이 몇 배로 부푼지를 뜻한다 ($R_j^2 = 0.9$ 면 10). 조건수가 행렬 전체를 한 수로 보는 데 비해 VIF 는 어느 열이 겹치는지 열마다 짚어 주며, centering 뒤에도 큰 값이면 penalty 가 필요하다. - 자료에서 복원추출로 다시 뽑은 표본 (bootstrap) 에서 계수 부호가 유지되는 비율. 곱항의 부호가 뒤집히면 그 항은 해석하지 않는다.
- 잔차를 곱항에 대해 그린 산점도. Expansion 전에 남아 있던 구조가 사라졌는지 확인한다.
- Sparse polynomial chaos expansion — 서로 직교하는 다항식들의 모음 위에서 항을 희소하게 골라 고차 expansion 의 항 수를 줄이는 방법이다 [10]. 최소각 회귀 (least angle regression) 로 항을 고르는 절차가 자리 잡아 수백 개 후보에서 수십 개만 남기는 일이 계산으로 가능해졌다. 착수에는 입력 변수의 분포 가정 (기저가 그 분포에 따라 정해진다) 과 설계된 표본이 필요하다.
- Hierarchical interaction selection at scale — heredity 를 convex 제약으로 걸어 곱항을 고르는 lasso 계열이다 [6]. 제약이 convex 여서 찾은 최적해가 유일하고 수백 변수까지 풀리므로, 4.4 절의 규칙을 사람이 지키는 대신 최적화가 지키게 할 수 있다. 착수에는 곱항 후보의 범위를 미리 좁히는 규칙과 계산 예산이 필요하다.
- Learned basis — 고정된 monomial 기저 대신 1차원 함수를 학습해 쌓는 model 이다 [11]. 2024 년에 spline 기반 구현이 공개되어 같은 자료에서 expansion + ridge 와 직접 견줄 수 있게 되었다. 착수에는 held-out 비교 절차와, 학습되는 기저가 표본 수에 비해 과하지 않은지 판단할 기준이 필요하다.
[1] Box, G. E. P. and Wilson, K. B. (1951). On the Experimental Attainment of Optimum Conditions. Journal of the Royal Statistical Society: Series B, 13(1), 1–38.
[2] Marquardt, D. W. (1980). Comment: You Should Standardize the Predictor Variables in Your Regression Models. Journal of the American Statistical Association, 75(369), 87–91.
[3] Hoerl, A. E. and Kennard, R. W. (1970). Ridge Regression: Biased Estimation for Nonorthogonal Problems. Technometrics, 12(1), 55–67.
[4] Nelder, J. A. (1998). The Selection of Terms in Response-Surface Models—How Strong is the Weak-Heredity Principle? The American Statistician, 52(4), 315–318.
[5] Chipman, H. (1996). Bayesian variable selection with related predictors. The Canadian Journal of Statistics, 24(1), 17–36.
[6] Bien, J., Taylor, J. and Tibshirani, R. (2013). A lasso for hierarchical interactions. The Annals of Statistics, 41(3), 1111–1141.
[7] Pedregosa, F., Varoquaux, G., Gramfort, A., Michel, V., Thirion, B., Grisel, O., Blondel, M., Prettenhofer, P., Weiss, R., Dubourg, V., Vanderplas, J., Passos, A., Cournapeau, D., Brucher, M., Perrot, M. and Duchesnay, É. (2011). Scikit-learn: Machine Learning in Python. Journal of Machine Learning Research, 12, 2825–2830.
[8] Rahimi, A. and Recht, B. (2007). Random Features for Large-Scale Kernel Machines. Advances in Neural Information Processing Systems, 20.
[9] Friedman, J. H. and Popescu, B. E. (2008). Predictive learning via rule ensembles. The Annals of Applied Statistics, 2(3), 916–954.
[10] Blatman, G. and Sudret, B. (2011). Adaptive sparse polynomial chaos expansion based on least angle regression. Journal of Computational Physics, 230(6), 2345–2367.
[11] Liu, Z., Wang, Y., Vaidya, S., Ruehle, F., Halverson, J., Soljačić, M., Hou, T. Y. and Tegmark, M. (2024). KAN: Kolmogorov-Arnold Networks. arXiv:2404.19756.
[12] Tibshirani, R. (1996). Regression Shrinkage and Selection via the Lasso. Journal of the Royal Statistical Society: Series B, 58(1), 267–288.
[13] Zou, H. and Hastie, T. (2005). Regularization and variable selection via the elastic net. Journal of the Royal Statistical Society: Series B, 67(2), 301–320.
- collinearity: 두 개 이상의 열이 거의 같은 방향을 가리켜 계수를 따로 추정할 수 없는 상태.
- condition number: 행렬의 최대 특이값과 최소 특이값의 비. 입력의 작은 오차가 해에서 얼마나 커지는지를 나타낸다.
- curse of dimensionality: 열이 늘수록 그 공간을 같은 밀도로 채우는 데 필요한 관측 수가 지수로 늘어나는 현상.
-
degree: expansion 이 허용하는 monomial 의 최고 차수.
$X_1^2 X_2$ 의 차수는 3 이다. - derived variable: 도메인 지식으로 두 개 이상의 열을 묶어 새로 만든 변수. 비나 율이 그 예다.
- design matrix: 행이 관측이고 열이 model 이 쓰는 항인 행렬. 계수는 이 행렬을 풀어 얻는다.
- dummy: 범주형 변수의 한 범주에 대응하여 그 범주면 1, 아니면 0 을 담는 열.
- extrapolation: 훈련 자료가 덮지 않는 입력 범위에 대한 예측.
- held-out: 적합에 쓰지 않고 적합한 model 의 오차를 재는 데만 쓰는 자료.
- heredity: 곱항을 model 에 넣으면 그것을 이루는 낮은 차수 항도 함께 넣는 규칙.
- imputation: 비어 있는 값을 다른 값으로 채우는 일. 그 열의 평균이나 model 의 예측으로 채운다.
- leverage: 한 관측이 자신의 예측값을 끌어당기는 정도. 입력이 중심에서 멀수록 커진다.
-
main effect: 변수 하나의 1차 항
$\beta_i x_i$ . -
monomial: 변수들의 거듭제곱을 곱한 항.
$X_1^2 X_2$ 가 그 예다. - overfitting: 훈련 자료에는 맞지만 새 자료에서는 어긋나는 상태.
- penalty: 계수의 크기에 값을 매겨 적합 기준에 더하는 항. ridge 와 lasso 가 그것이다.
- RMSE: 제곱 오차의 평균에 제곱근을 취한 값 (Root Mean Squared Error).
- standardization: 각 열에서 그 열의 평균을 빼고 표준편차로 나누어 평균 0, 표준편차 1 로 맞추는 연산.
-
VIF: 한 열을 나머지 열로 회귀했을 때의
$R^2$ 로 계산하는 분산 팽창 계수.$1/(1-R^2)$ 이다.
공분산은 두 열이 함께 움직이는 정도를 재는 값이다. 모집단에 대한 정의가 식 (16) 이며,
기댓값의 성질로 괄호를 풀면 계산하기 쉬운 식 (6) 이 된다. 두 변수의 곱의 기댓값에서 각 변수의 기댓값의 곱을 뺀 것이며, 4.2 절이 쓰는 형태가 이것이다.
표본
부호와 자기 자신과의 공분산이 뜻하는 것은 넷이다.
-
$\mathrm{Cov}(X, Y) \gt 0$ 이면$X$ 가 커질 때$Y$ 도 커진다. -
$\mathrm{Cov}(X, Y) \lt 0$ 이면$X$ 가 커질 때$Y$ 는 작아진다. -
$\mathrm{Cov}(X, Y) = 0$ 이면 두 변수 사이에 선형 관계가 없다. -
$\mathrm{Cov}(X, X)$ 는 분산$\mathrm{Var}(X)$ 다.
4.2 절과 Appendix C 의 유도는
4.2 절은 식 (7) 에
나누어야 하는 이유는 단위다. 열
분자부터 구한다. 식 (6) 을
식 (20) 을 식 (19) 에 넣으면 식 (21) 이 된다.
식 (22) 의 두 항은 출처가 다르다. 앞의 항
남은 것은 분모의 두 표준편차다.
식 (22) 와 식 (23) 에서 centering 이 바꾸는 항을 한자리에 모으기 위해 4.2 절의
셋을 넣고, 표준편차는 분산의 제곱근이므로 식 (23) 에 제곱근을 취하면, 분자와 두 분모가 식 (24) 로 적힌다.
셋을 식 (7) 에 넣으면
집합 표기를 읽는 법이 먼저다. 집합은 원소를 늘어놓아
4.1 절의 식 (4) 를 여기에 다시 적는다.
식 (4) 는 기호가 빽빽하지만 읽는 법은 간단하다. 왼쪽의
변수가 두 개이고
Table 3. Exponent pairs admitted by equation (4) at two variables and degree 2
| Exponent of |
Exponent of |
Degree | Term |
|---|---|---|---|
| 1 | 0 | 1 | |
| 0 | 1 | 1 | |
| 2 | 0 | 2 | |
| 1 | 1 | 2 | |
| 0 | 2 | 2 |
빠진 짝은
식 (4) 는 만들 열의 집합을 정의할 뿐 그 크기를 말하지 않는다. 그 크기가 식 (14) 와 식 (15) 이며, 아래가 그 유도다.
차수가 정확히
세는 방법은 별과 막대 (stars and bars) 다. 차수
차수를 0 부터
식 (4) 의 집합은
interaction_only 에서는 같은 변수를 두 번 쓰지 않으므로, 남는 항 하나는 변수
Expansion 이 만든 열에 거는 penalty 는 셋 가운데 하나다. 목적 함수로 적으면 ridge 는 식 (28), lasso 는 식 (29) 이며 [12],
차이는 penalty 의 모양에서 온다. 열이 standardization 되어 있고 서로 직교하면 두 해는 식 (30) 으로 닫힌 꼴이 된다. Ridge 는 모든 계수를 같은 비율로 나누어 줄이고 0 에는 닿지 않으며, lasso 는 크기가
Expansion 이 만든 열은 직교와 거리가 멀고 (4.2 절), 서로 닮은 열이 무리를 이룬다. Ridge 는 그 무리에 계수를 나누어 주고, lasso 는 하나만 남기고 나머지를 0 으로 만든다. 어느 것이 남을지는 표본이 조금만 달라져도 바뀌므로, lasso 가 돌려주는 항의 목록은 그 자체로 불안정하다. 둘을
Table 4. Penalties on expanded columns
| Penalty | Term added | A group of columns that resemble one another | Where it fits |
|---|---|---|---|
| Ridge | Sum of the squared coefficients | Coefficient shared across the group | The default on expanded columns |
| Lasso | Sum of the absolute coefficients | One kept, the rest at zero | A short term list, under a heredity constraint |
| Elastic net | Both, mixed by |
Kept or dropped together | Selection wanted with a list that holds |
RidgeCV, LassoCV, ElasticNetCV 가 대신한다. 절편은 penalty 에서 뺀다. 절편에 penalty 를 걸면 적합된 수준이 0 쪽으로 끌려가 model 이 자료의 중심에서 벗어난다.
Penalty 를 건다고 degree 를 4 로 올릴 수 있는 것은 아니다. Penalty 가 버는 것은 열 수가 행 수에 가까울 때 적합이 무너지느냐 버티느냐의 차이이며, 그 차이의 크기는 5.1 절에 있다.
Expansion 자체는 sklearn.preprocessing.PolynomialFeatures 한 줄이며, 정할 것은 네 인자뿐이다 [7].
Table 5. PolynomialFeatures arguments
| Argument | Effect | Note |
|---|---|---|
degree |
Highest degree of the monomials | A (min, max) tuple for the lowest degree as well, so (2, 2) for second-order terms only |
interaction_only |
Products of distinct variables only | First-order terms kept, powers of a single variable dropped |
include_bias |
A constant column of ones | False where the estimator carries its own intercept |
order |
Memory layout of the output array | 'C' or 'F', a choice of layout rather than of content |
# Python
from sklearn.preprocessing import PolynomialFeatures
# interaction_only=True keeps X1*X2 and drops X1^2, X2^2
poly = PolynomialFeatures(degree=2, interaction_only=True, include_bias=False)
X_expanded = poly.fit_transform(X)
term_name = poly.get_feature_names_out()get_feature_names_out() 이 돌려주는 이름은 계수를 다시 열에 되짚는 유일한 통로다. Expansion 뒤에 이름을 잃으면 계수는 남아도 그것이 어느 곱의 계수인지 말할 수 없다.
Expansion 은 홀로 쓰지 않고 standardization 과 penalty 사이에 둔다. 순서는 원 변수의 standardization, expansion, expansion 이 만든 열의 두 번째 standardization, 그리고 penalty 를 건 적합이다.
앞의 standardization 은 4.3 절의 조건수 문제를 없애고, 뒤의 standardization 은 penalty 가 열마다 공평하게 걸리게 한다. 곱항의 분산은 원 변수 분산의 곱에 가까워 열마다 크게 벌어지므로, 두 번째 standardization 없이 ridge 를 걸면 penalty 가 사실상 분산이 큰 열에만 걸린다.
# Python
from sklearn.linear_model import Ridge
from sklearn.model_selection import GridSearchCV
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import PolynomialFeatures, StandardScaler
pipeline = Pipeline([
('raw_scale', StandardScaler()),
('expand', PolynomialFeatures(include_bias=False)),
('term_scale', StandardScaler()),
('fit', Ridge()),
])
grid = {'expand__degree': [1, 2, 3], 'fit__alpha': [0.1, 1.0, 10.0, 100.0]}
search = GridSearchCV(pipeline, grid, scoring='neg_root_mean_squared_error', cv=5)
search.fit(X, y)Expansion 을 pipeline 안에 두는 이유는 편의가 아니다. Expansion 자체는 행마다 독립이라 누수 (leakage) 를 만들지 않지만, 앞뒤의 standardization 은 cross-validation 이 자료를 나눈 조각 (fold) 의 훈련 부분에서만 평균과 분산을 얻어야 한다. degree 와 penalty 를 함께 고르는 일도 pipeline 안에서만 한 번의 탐색으로 끝난다.
Expansion 의 비용은 열 수에 선형이고, 그 열 수는 식 (14) 로 늘어난다. 행 100,000, 변수 100,
첫째는 kernel 이다. 다항 kernel 식 (32) 는 expansion 한 공간의 내적을 expansion 없이 계산한다.
KernelRidge(kernel='poly') 가 그 형태이며, 비용이 열이 아니라 행에 걸리므로 변수가 많고 행이 적은 자료에 맞는다. 대신 계수가 개별 monomial 에 붙지 않아 어느 곱이 기여했는지 읽을 수 없다.
둘째는 근사다. PolynomialCountSketch 는 다항 kernel 이 쓰는 항들을 정해진 수의 열로 줄여 담고 (sketch), Nystroem 은 표본의 부분집합으로 kernel 행렬을 근사한다. 둘 다 kernel 을 유한한 수의 열로 근사해 선형 model 의 속도를 지키는 계열이며 [8], 열 수를 사용자가 정한 값으로 묶는다.
희소 입력은 그대로 받는다. 0 이 아닌 값만 저장하는 CSR 형식의 행렬을 넣으면 expansion 결과도 같은 형식으로 나오므로, dummy 열이 많은 자료가 dense 로 부풀지 않는다.
모든 짝을 만들 필요는 없다. 곱할 열을 골라 넘기면 열 수는 Table 1 이 아니라 고른 개수로 끝난다.
# Python
from sklearn.compose import ColumnTransformer
from sklearn.preprocessing import PolynomialFeatures
expand_column = ['temperature', 'pressure']
transformer = ColumnTransformer(
[('expand', PolynomialFeatures(degree=2, include_bias=False), expand_column)],
remainder='passthrough',
)고를 근거는 셋이다. 공정이 이미 아는 상호작용, 잔차가 두 변수의 조합에서 구조를 보이는 경우, 그리고 tree 여러 개를 합친 model (tree ensemble) 을 먼저 돌려 상호작용의 세기를 재고 상위 짝만 남기는 방법이다 [9]. 셋 다 없으면 전체 expansion 에 penalty 를 거는 편이 낫다. 근거 없이 짝을 고르면 어느 상호작용이 model 에 들어갈지를 자료가 아니라 분석자가 정하게 된다.

