Tech PostsTech Posts
머신러닝Machine Learning · 22 / 24
22 머신러닝Machine Learning

지수 하나가 계수를 줄이느냐 없애느냐를 가른다One Exponent Decides Whether Coefficients Shrink or Vanish

OLS는 계수가 얼마나 커지든 상관하지 않습니다. 상관된 회귀변수를 주면 서로 상쇄하는 거대한 값을 내놓습니다.OLS has no opinion about how large its coefficients get. Give it correlated regressors and it produces enormous offsetting values.

OLS는 계수가 얼마나 커지든 상관하지 않습니다. 상관된 회귀변수를 주면 서로 상쇄하는 거대한 값 — 한 변수에 +40,000, 그와 거의 같은 변수에 −39,800 — 을 내놓습니다. 표본에는 아름답게 맞고 새 데이터에서는 무너집니다.

OLS has no opinion about how large its coefficients get. Give it correlated regressors and it will produce enormous offsetting values — a coefficient of +40,000 on one variable and −39,800 on its near-twin — that fit the sample beautifully and fall apart on new data.

정규화가 해법입니다. 손실함수에 계수 크기에 대한 벌점을 더해서 적합이 쓰는 크기 한 단위마다 정당화를 요구하게 만듭니다.

Regularisation is the fix: add a penalty on coefficient size to the loss function, so the fit has to justify every unit of magnitude it uses.

두 벌점, 두 행동Two penalties, two behaviours

두 방법 모두 잔차제곱합에 벌점을 더한 것을 최소화하고 벌점의 선택이 모든 것을 바꿉니다.

Both methods minimise residual sum of squares plus a penalty, and the choice of penalty changes everything.

능형 / Ridge : RSS + α · Σ βⱼ² (L2) LASSO : RSS + α · Σ |βⱼ| (L1)

지수의 그 차이가 질적으로 다른 행동을 만듭니다. 능형은 계수를 0 쪽으로 매끄럽게 줄이지만 결코 0에 닿지 않습니다. 모든 변수가 작은 가중치를 달고 모형에 남습니다. LASSO는 계수를 정확히 0으로 보냅니다. 그래서 축소 방법이면서 동시에 변수 선택 방법입니다.

That difference in exponent produces a qualitative difference in behaviour. Ridge shrinks coefficients toward zero smoothly but never reaches it — every variable stays in the model with a small weight. LASSO sets coefficients exactly to zero, which makes it a variable selection method as well as a shrinkage method.

기하학적 이유를 알아 둘 값어치가 있습니다. L1 제약 영역은 축 위에 꼭짓점이 있는 마름모이고 L2 영역은 원입니다. 최적해는 손실 등고선이 그 영역에 처음 닿는 곳에 있는데 마름모는 꼭짓점에서 닿을 확률이 훨씬 높고 꼭짓점에서는 계수가 정확히 0입니다. 원에는 꼭짓점이 없으므로 능형 해가 축 위에 놓이는 일은 거의 없습니다.

The geometric reason is worth knowing. The L1 constraint region is a diamond with corners on the axes; the L2 region is a circle. The optimum sits where the loss contours first touch that region, and a diamond is far more likely to be touched at a corner — where a coefficient is exactly zero. A circle has no corners, so ridge solutions almost never land on an axis.

능형 (L2)LASSO (L1)
상관된 예측변수상관 집단에 가중치를 나눠 줍니다. 안정적입니다.하나를 다소 임의로 고르고 나머지를 0으로 보냅니다.
해석모든 변수를 감쇠된 계수와 함께 남깁니다.짧은 목록을 줍니다.
p > n일 때제한 없습니다.최대 n개까지만 선택할 수 있습니다.
Ridge (L2)LASSO (L1)
Correlated predictorsSpreads weight across the group. Stable.Picks one somewhat arbitrarily and zeroes the rest.
InterpretabilityAll variables, with damped coefficients.Gives you a short list.
When p > nNo limit.Can select at most n variables.

엘라스틱넷은 두 벌점을 결합하고 예측변수가 상관되어 있을 때 합리적인 기본값입니다. LASSO의 희소성을 유지하면서 상관 집단을 능형처럼 다뤄 함께 선택하거나 함께 버립니다.

Elastic Net combines both penalties and is the sensible default when predictors are correlated: it keeps LASSO sparsity while handling correlated groups more like ridge, selecting or dropping them together.

벌점이 하는 거래The trade the penalty makes

정규화는 일부러 편향을 도입합니다. 추정치가 0 쪽으로 당겨지고 더 이상 참 모수의 불편추정량이 아닙니다. 거래는 편향이 오르는 것보다 분산이 더 빨리 떨어져서 전체 예측 오차가 개선된다는 것입니다.

Regularisation deliberately introduces bias: the estimates are pulled toward zero and are no longer unbiased for the true parameters. The trade is that variance falls faster than bias rises, so total prediction error improves.

그 제약을 우회하려고 설계된 것이 시리즈 마지막 편의 Double LASSO입니다.

That restriction is what Double LASSO — the final post in this series — is designed to work around.

정규화 경로 읽기Reading a regularisation path

가장 먼저 볼 것은 계수 경로입니다. α를 여러 자릿수에 걸쳐 바꾸면서 각 계수가 어떻게 변하는지를 그립니다. α는 로그 축에 놓고 정규화가 왼쪽으로 갈수록 커지도록 뒤집습니다.

The first thing to plot is a coefficient path: each coefficient value as α varies over several orders of magnitude, with α on a log scale and reversed so that regularisation increases to the left.

python
import numpy as np
import matplotlib.pyplot as plt
from sklearn.linear_model import Ridge, lars_path
from sklearn.datasets import load_diabetes

# Hilbert matrix: notoriously ill-conditioned, so OLS on it is unstable
X = 1.0 / (np.arange(1, 11) + np.arange(0, 10)[:, np.newaxis])
y = np.ones(10)

alphas = np.logspace(-10, -2, 200)
coefs = [Ridge(alpha=a, fit_intercept=False).fit(X, y).coef_ for a in alphas]

fig, axes = plt.subplots(1, 2, figsize=(13, 4))
axes[0].plot(alphas, coefs)
axes[0].set_xscale("log"); axes[0].set_xlim(axes[0].get_xlim()[::-1])
axes[0].set_xlabel("alpha"); axes[0].set_ylabel("weights")
axes[0].set_title("Ridge: coefficients collapse smoothly, never to zero")

Xd, yd = load_diabetes(return_X_y=True)
_, _, lasso_coefs = lars_path(Xd, yd, method="lasso")
xx = np.sum(np.abs(lasso_coefs.T), axis=1); xx /= xx[-1]
axes[1].plot(xx, lasso_coefs.T)
axes[1].set_xlabel("|coef| / max|coef|")
axes[1].set_title("LASSO: coefficients hit zero one at a time")
힐베르트 행렬은 일부러 고약한 예입니다. 거의 특이행렬이라 OLS를 깨뜨리도록 만들어진 데이터에서 안정화가 일어나는 걸 봅니다.The Hilbert matrix is a deliberately vicious example — nearly singular, designed to break OLS. Watching stabilisation happen on it makes the point.

왼쪽 패널의 약하게 정규화된 끝에서 계수들이 극단값으로 흔들리는 것이 보이고 α가 커지면서 매끄럽게 0으로 무너집니다. 그 붕괴가 곧 안정화입니다. 오른쪽의 LASSO 경로는 다른 행동을 보여 줍니다. α가 커질 때 계수들이 하나씩 0에 닿고 꺾이는 지점마다 변수 하나가 모형을 떠납니다. 떠나는 순서가 예측 유용성의 암묵적 순위인데 상관된 예측변수 문제 때문에 취약한 순위입니다.

At the weakly regularised end of the left panel you can see coefficients swinging to extreme values; as α grows they collapse smoothly toward zero. That collapse is the stabilisation. The LASSO path on the right shows the other behaviour: coefficients hit zero one at a time as α increases, each kink marking a variable leaving the model. The order in which they leave is an implicit ranking of predictive usefulness — though a fragile one, for the correlated-predictor reason above.

α 고르기Choosing α

벌점 강도는 데이터에서 직접 읽어 낼 수 있는 것이 아니라 교차검증으로 고릅니다. 이 시리즈의 교차검증 편의 주제이고 RidgeCV·LassoCV·ElasticNetCV가 자동으로 해 줍니다.

The penalty strength is not something you read off the data; it is chosen by cross-validation, the subject of the cross-validation post. RidgeCV, LassoCV and ElasticNetCV do it automatically.

알아 둘 만한 정련 하나. "1 표준오차 규칙"은 교차검증 오차가 최솟값의 1 표준오차 안에 드는 가장 큰 α를 고릅니다. 일부러 조금 더 정규화하는 것인데 근거는 CV 곡선이 최솟값 근처에서 평평하므로 성능이 같아 보인다면 더 단순한 모형이 낫다는 것입니다. R의 glmnet 기본값이고 눈에 띄게 더 희소한 모형을 냅니다.

One refinement worth knowing: the "one standard error rule" selects the largest α whose cross-validated error is within one standard error of the minimum. This deliberately over-regularises slightly, on the reasoning that the CV curve is flat near its minimum and a simpler model at equivalent measured performance is the better bet. It is the default in R glmnet and produces noticeably sparser models.

실무에서In practice

  • 피처를 표준화하십시오. 선택이 아닙니다. 벌점은 계수 크기에 적용되고 크기는 단위에 의존합니다. 천 단위로 잰 변수는 같은 변수를 단위로 잰 것보다 계수가 작아지므로 벌점을 덜 받습니다. 즉 단위 선택이 어떤 변수가 살아남는지를 조용히 결정합니다. 항상 파이프라인 안에 StandardScaler를 앞에 두어 훈련 폴드에서만 적합되게 하십시오.
  • 절편에는 벌점을 주지 마십시오. 표준 구현들이 기본으로 올바르게 처리하지만 이유를 알아 둘 값어치가 있습니다. 절편을 0으로 줄이면 예측이 평균이 아니라 0 쪽으로 당겨지고 그건 아무도 원하지 않습니다.
  • 예측변수가 상관되어 있으면 엘라스틱넷을 쓰십시오. 순수 LASSO가 상관 집단 안에서 임의로 고르는 성질은 선택된 변수 목록을 불안정하게 만들고 그 불안정성을 발견으로 오해하기 쉽습니다. 부트스트랩 표본에서 다시 돌렸을 때 선택 집합이 달라진다면 그 사실을 밝히십시오.
  • LASSO가 무엇을 골랐는지를 발견으로 해석하지 마십시오. 선택은 추론이 아닙니다. 변수가 빠졌다는 것은 효과가 없다는 뜻이 아니라 이 표본에서 다른 변수들을 조건으로 예측 가치를 별로 더하지 않았다는 뜻입니다. 어떤 변수가 중요한지 주장하려면 안정성 선택 — 많은 부트스트랩 재표본에 LASSO를 돌려 자주 뽑히는 변수를 남기는 것 — 이 더 방어 가능합니다.
  • 약한 신호가 많은 순수 예측에는 능형이 기본값입니다. LASSO는 진실이 정말로 희소하다고 믿을 때 — 소수의 변수만 중요하고 대부분은 아닐 때 — 맞습니다. 두 가정 모두 교차검증으로 확인 가능하니 둘 다 해 보십시오.
  • Standardise the features. This is not optional. The penalty applies to coefficient magnitudes, and magnitudes depend on units. A variable measured in thousands gets a smaller coefficient than the same variable in units, so it is penalised less — meaning your choice of units silently determines which variables survive. Always put a StandardScaler before the estimator, inside a pipeline so it fits on training folds only.
  • Do not penalise the intercept. All standard implementations handle this correctly by default, but it is worth knowing why: shrinking the intercept toward zero would pull predictions toward zero rather than toward the mean.
  • Prefer Elastic Net when predictors are correlated. Pure LASSO arbitrary selection within a correlated group makes the resulting variable list unstable, and that instability is easy to mistake for a finding. If you rerun on a bootstrap sample and get a different set, say so.
  • Do not interpret which variables LASSO selected as a discovery. Selection is not inference. A variable being dropped does not mean it has no effect; it means it added little predictive value conditional on the others in this sample. Stability selection — running LASSO on many bootstrap resamples and keeping frequently chosen variables — is the more defensible way to make such claims.
  • Ridge is the right default for pure prediction with many weak signals. LASSO is right when you believe the truth is genuinely sparse — a few variables matter and most do not. Both assumptions are testable by cross-validation, so try both.

유전체학과 텍스트에서는 예측변수가 수천 개인데 관측치가 수백 개입니다. OLS는 정의되지 않고 LASSO가 표준입니다. 신용평가와 수요예측에서는 상관된 피처가 많고 규제나 운영상 간결한 모형을 선호합니다. 그리고 상관된 통제변수가 몇 개를 넘는 모든 회귀 — 응용 작업 대부분이 여기 해당합니다.

In genomics and text, thousands of predictors and hundreds of observations: OLS is undefined and LASSO is standard. In credit scoring and demand forecasting, many correlated features and a regulatory or operational preference for compact models. And any regression with more than a handful of correlated controls, which is most of applied work.

직관을 잡으려면 베이즈 통계와의 연결을 짚어 둘 값어치가 있습니다. 능형은 계수에 정규 사전분포를 둔 사후 최빈값이고 LASSO는 라플라스 사전분포입니다. 벌점은 계수가 작다는 사전 믿음을 명시적으로 적은 것입니다. 그렇게 보면 둘 사이의 선택이 덜 임의적이 됩니다. 데이터를 보기 전에 세계가 어떻게 생겼다고 믿는지에 대한 질문이 되기 때문입니다.

The connection to Bayesian statistics is worth noting for intuition: ridge is exactly the posterior mode under a normal prior on the coefficients, and LASSO under a Laplace prior. The penalty is a prior belief that coefficients are small, made explicit. That framing makes the choice between them less arbitrary — it becomes a question about what you believe the world looks like before seeing the data.