Sau khi scale feature, mô hình tuyến tính vẫn có thể overfit khi số chiều lớn hoặc multicollinearity cao. L1/L2 regularization thêm penalty vào loss, kéo trọng số về nhỏ và — với L1 — tạo sparsity. Kungfutech trình bày hình học penalty (geometry): giao điểm contour loss elipsoid với “viên bi” L1 (hình thoi) vs L2 (hình tròn) giải thích vì sao Lasso chọn feature và Ridge co trọng số đều.
Mục tiêu
- Hiểu công thức loss + penalty L1 ($|\mathbf{w}|_1$) và L2 ($|\mathbf{w}|_2^2$).
- Phân biệt Ridge (L2), Lasso (L1) và Elastic Net kết hợp.
- Liên hệ regularization với preprocessing (scale bắt buộc trước khi so sánh $\lambda$).
Lý thuyết
Overfitting và norm penalty
Linear model $ \hat{y} = \mathbf{w}^T \mathbf{x} + b $. OLS minimize SSE:
$$J(\mathbf{w}) = \sum_i (y_i - \hat{y}_i)^2$$
Regularization thêm penalty controlled bởi $\lambda \geq 0$ (sklearn: alpha — $\alpha = \lambda$):
Ridge (L2):
$$J_{Ridge} = SSE + \alpha |\mathbf{w}|_2^2 = SSE + \alpha \sum_j w_j^2$$
Lasso (L1):
$$J_{Lasso} = SSE + \alpha |\mathbf{w}|_1 = SSE + \alpha \sum_j |w_j|$$
Elastic Net:
$$J = SSE + \alpha \left( \rho |\mathbf{w}|_1 + \frac{1-\rho}{2} |\mathbf{w}|_2^2 \right)$$
Hình học — vì sao L1 sparse?
Minimize constrained form tương đương:
$$\min SSE \quad \text{s.t.} \quad |\mathbf{w}|_p \leq t$$
Contour SSE là elipsoid trong không gian $\mathbf{w}$. Điểm tối ưu = contour SSE chạm vùng ràng buộc norm:
| Penalty | Vùng ràng buộc | Hình dạng 2D | Giao elipsoid |
|---|---|---|---|
| L2 | $|\mathbf{w}|_2 \leq t$ | Hình tròn | Thường chạm ở điểm không trục → mọi $w_j$ nhỏ nhưng ≠ 0 |
| L1 | $|\mathbf{w}|_1 \leq t$ | Hình thoi (octahedron) | Hay chạm đỉnh trục → một số $w_j = 0$ exact |
Đó là lý do Lasso feature selection implicit — coefficient về đúng 0. Ridge chỉ shrink toward zero.
Ridge — multicollinearity
Khi feature correlated cao, OLS coefficient dao động lớn. Ridge phạt $w_j^2$ lớn — phân bố trọng số ổn định, variance giảm, bias tăng nhẹ. Không zero-out feature.
Ridge — alpha càng lớn, $|\mathbf{w}|$ càng nhỏ.
Lasso — sparsity
Lasso — chọn subset feature. Hữu ích khi nhiều feature irrelevant (Wine 13 feature, một số weak).
Giới hạn: nếu nhóm feature highly correlated, Lasso chọn ngẫu nhiên một trong nhóm — Elastic Net kết hợp L1+L2 ổn định hơn.
ElasticNet — l1_ratio = $\rho$.
alpha và scale feature
Penalty $\alpha \sum w_j^2$ — nếu feature $x_j$ scale lớn, $|w_j|$ nhỏ nhưng $w_j x_j$ vẫn lớn. StandardScaler trước Ridge/Lasso để $\alpha$ có nghĩa comparable giữa features và giữa dataset.
Kungfutech Chương 4 preprocessing + regularization: Pipeline (StandardScaler, Ridge).
Logistic Regression với L1/L2
LogisticRegression(penalty='l2') default L2. penalty='l1' cần solver liblinear hoặc saga — classification sparse.
C chuẩn SVM vs alpha Ridge
SVM: $C = 1/\alpha_{eff}$ — $C$ nhỏ = regularization mạnh. Đừng nhầm notation giữa thư viện.
Code Python
So sánh Ridge, Lasso, ElasticNet trên Wine (regression target = alcohol):
import numpy as np
import pandas as pd
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import Ridge, Lasso, ElasticNet
from sklearn.metrics import mean_squared_error, r2_score
wine = load_wine()
X = wine.data
y = wine.data[:, 0] # regression: dự đoán alcohol từ feature khác
X = np.delete(X, 0, axis=1) # bỏ alcohol khỏi X
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=42
)
alphas = [0.01, 0.1, 1.0, 10.0]
for name, Model in [("Ridge", Ridge), ("Lasso", Lasso), ("ElasticNet", ElasticNet)]:
print(f"\n=== {name} ===")
for alpha in alphas:
pipe = Pipeline([
("scaler", StandardScaler()),
("model", Model(alpha=alpha, random_state=42, max_iter=5000)),
])
pipe.fit(X_train, y_train)
w = pipe.named_steps["model"].coef_
n_nonzero = np.sum(np.abs(w) > 1e-4)
pred = pipe.predict(X_test)
print(f" alpha={alpha:5.2f} nonzero_coef={n_nonzero:2d}/12 "
f"R2={r2_score(y_test, pred):.3f} RMSE={np.sqrt(mean_squared_error(y_test, pred)):.3f}")
# Lasso path — coefficient shrink to zero
lasso_pipe = Pipeline([
("scaler", StandardScaler()),
("lasso", Lasso(alpha=0.5, random_state=42, max_iter=5000)),
])
lasso_pipe.fit(X_train, y_train)
coef = lasso_pipe.named_steps["lasso"].coef_
feature_names = [f for f in wine.feature_names if f != "alcohol"]
print("\nLasso coef (alpha=0.5):")
for name, c in zip(feature_names, coef):
marker = " ← zero" if abs(c) < 1e-4 else ""
print(f" {name:25s}: {c:+.4f}{marker}")
Lasso alpha lớn → nhiều coef = 0 — minh họa geometry sparsity.
Lỗi thường gặp
- Ridge/Lasso không scale: Penalty unfair giữa features — luôn StandardScaler trước.
- So alpha giữa raw và scaled data: $\alpha$ optimal khác hoàn toàn — tune lại sau scale.
- Kỳ vọng Lasso luôn chọn đúng feature “thật”: Correlated feature → unstable selection; dùng Elastic Net hoặc RF importance.
- Nhầm
CSVM vớialphaRidge: Inverse relationship — đọc docs từng estimator.
Bài tập
- Lasso path: Dùng
LassoCVtrên Breast Cancer (bỏ cột target, regression giả trên mean radius). Vẽ số nonzero coef vs alpha. - Logistic L1:
LogisticRegression(penalty='l1', solver='saga', C=0.1)+ StandardScaler trên Wine classification. Bao nhiêu feature có coef ≠ 0? - Hình học (tự luận): Vẽ 2D sketch contour SSE (ellipse) chạm hình tròn L2 vs hình thoi L1 — giải thích vì sao L1 solution hay nằm trên trục.
Tóm tắt
L1 L2 regularization — Ridge (L2) shrink trọng số, Lasso (L1) tạo sparsity; hình học penalty giải thích giao elipsoid–L1/L2 constraint. Elastic Net kết hợp cả hai. Luôn feature scaling trước khi tune alpha. Liên kết trực tiếp preprocessing Ch.4 với generalization — bước tiếp: chọn feature có ý nghĩa.
Tiếp tục tại khóa Machine Learning cơ bản — bài cuối chương: Feature Selection.