Mô hình ghi nhớ train set nhưng thua trên test — đó là overfitting. Kungfutech Chương 3 minh họa hiện tượng này qua logistic regression với C lớn/nhỏ, và giới thiệu regularization như công cụ kiểm soát độ phức tạp mô hình. Đây là khái niệm sống còn cho mọi thuật toán ML.
Mục tiêu
- Định nghĩa overfitting, underfitting, và bias-variance tradeoff.
- Hiểu L1/L2 regularization trong logistic regression (
C,penalty). - Nhận diện overfitting bằng learning curve và validation.
Lý thuyết
Overfitting là gì?
Overfitting (học vẹt): Mô hình fit nhiễu trong train data thay vì quy luật thật → train error thấp, test error cao.
Underfitting: Mô hình quá đơn giản → cả train và test đều kém.
Sweet spot: Mô hình đủ phức tạp để nắm pattern, đủ constrained để generalize.
Bias-Variance Decomposition (intuition)
Lỗi tổng quát hóa xấp xỉ:
$$ \text{Error} \approx \text{Bias}^2 + \text{Variance} + \text{Irreducible Noise} $$
| High Bias (underfit) | High Variance (overfit) | |
|---|---|---|
| Train error | Cao | Rất thấp |
| Test error | Cao | Cao (gap lớn vs train) |
| Nguyên nhân | Model quá đơn giản | Model quá linh hoạt |
| Fix | Tăng complexity | Regularization, more data |
Regularization trong Logistic Regression
Thay vì minimize log loss thuần, thêm penalty:
L2 (Ridge): $\frac{1}{C}|w|_2^2 = \frac{1}{C}\sum_j w_j^2$
- Co trọng số về 0, không về đúng 0
- Default trong sklearn
L1 (Lasso): $\frac{1}{C}|w|_1 = \frac{1}{C}\sum_j |w_j|$
- Một số $w_j$ → 0 → feature selection tự động
- Cần
solver='liblinear'hoặc'saga'
C nhỏ = penalty mạnh = weights nhỏ = ít overfit C lớn = penalty yếu = fit sát train = dễ overfit
Plot decision boundary: C=100 vs C=0.01 trên Iris — boundary lớn uốn cong hơn (overfit nhẹ trên train nhưng có thể kém test nếu nhiễu).
Dấu hiệu overfitting thực tế
- Train accuracy 99%, test accuracy 75%
- Learning curve: train và validation gap tăng khi thêm feature hoặc tăng model complexity
- Coefficient phình to khi không regularization (perfect separation)
- Cross-validation score thấp hơn train score đáng kể
Cách chống overfitting (Ch.3 context)
- Regularization: tune
C, chọn L1/L2 - More data: variance giảm khi $n$ tăng
- Feature selection: bỏ feature nhiễu (L1 giúp)
- Cross-validation: chọn hyperparameter trên validation, không test
- Early stopping (GD tay): dừng khi validation loss tăng
Overfitting không chỉ ở Logistic
Các thuật toán Ch.3 sau cũng overfit:
- SVM:
Clớn → hard margin trên nhiễu - Decision Tree: depth không giới hạn → memorization
- k-NN: $k=1$ → boundary cực kỳ phức tạp
Code Python
Minh họa overfitting qua C và learning curve:
import numpy as np
import matplotlib.pyplot as plt
from sklearn.datasets import load_iris
from sklearn.model_selection import train_test_split, learning_curve
from sklearn.preprocessing import StandardScaler
from sklearn.pipeline import Pipeline
from sklearn.linear_model import LogisticRegression
iris = load_iris()
X = iris.data[:, [2, 3]]
y = iris.target
X, y = X[y != 2], y[y != 2]
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.3, random_state=42, stratify=y
)
def eval_model(C):
pipe = Pipeline([
('scaler', StandardScaler()),
('clf', LogisticRegression(C=C, max_iter=1000, random_state=42))
])
pipe.fit(X_train, y_train)
train_acc = pipe.score(X_train, y_train)
test_acc = pipe.score(X_test, y_test)
return train_acc, test_acc, np.abs(pipe.named_steps['clf'].coef_[0])
# Sweep C
C_values = [0.001, 0.01, 0.1, 1, 10, 100, 1000]
results = [eval_model(C) for C in C_values]
print("C\t\tTrain\tTest\t|w|_1")
for C, (tr, te, w_norm) in zip(C_values, results):
print(f"{C:<10}\t{tr:.3f}\t{te:.3f}\t{w_norm:.3f}")
# Learning curve (C=1000 — dễ overfit hơn trên data nhỏ)
pipe = Pipeline([
('scaler', StandardScaler()),
('clf', LogisticRegression(C=1000, max_iter=1000, random_state=42))
])
train_sizes, train_scores, val_scores = learning_curve(
pipe, X, y, cv=5, train_sizes=np.linspace(0.1, 1.0, 10), scoring='accuracy'
)
plt.figure(figsize=(8, 4))
plt.plot(train_sizes, train_scores.mean(axis=1), 'o-', label='Train')
plt.plot(train_sizes, val_scores.mean(axis=1), 'o-', label='CV Validation')
plt.fill_between(train_sizes,
val_scores.mean(axis=1) - val_scores.std(axis=1),
val_scores.mean(axis=1) + val_scores.std(axis=1), alpha=0.1)
plt.xlabel('Training samples')
plt.ylabel('Accuracy')
plt.title('Learning curve — LogisticRegression (C=1000)')
plt.legend()
plt.show()
L1 vs L2 coefficient path
from sklearn.linear_model import LogisticRegression
X_train_std = StandardScaler().fit_transform(X_train)
for penalty, solver in [('l2', 'lbfgs'), ('l1', 'liblinear')]:
lr = LogisticRegression(penalty=penalty, solver=solver, C=0.1, max_iter=1000)
lr.fit(X_train_std, y_train)
print(f"{penalty.upper()}: coef = {lr.coef_[0]}")
Lỗi thường gặp
- Chọn C lớn nhất vì train accuracy cao nhất. Luôn ưu tiên validation/test performance.
- Regularization nhưng không scale feature. L2 penalty không công bằng giữa features khác scale.
- Nhầm overfitting với data leakage. Metric test quá tốt bất thường → kiểm tra pipeline trước.
- Một split duy nhất. Seed khác → kết luận khác; dùng CV.
- Thêm feature để fix underfitting nhưng không regularize. Complexity tăng → overfit mới.
Bài tập
- Vẽ train vs test accuracy theo
C(log scale x-axis). Xác định vùng underfit, sweet spot, overfit. - Train L1 logistic (
C=0.1,solver='liblinear') trên Iris 4 features. Feature nào có coefficient = 0? - Tạo synthetic data 2D với 5 mẫu nhiễu. So sánh decision boundary
C=1000vsC=0.01. Mô tả overfitting trực quan.
Tóm tắt
Overfitting machine learning xảy ra khi mô hình học nhiễu thay vì signal. Regularization (L1/L2 qua tham số C) là cách đầu tiên và hiệu quả để kiểm soát — áp dụng xuyên suốt logistic, SVM, và các mô hình sau trong chương.
Tiếp tục tại Khóa Machine Learning cơ bản trên KungfuTech.