ONE is preparing: 01 / INITIALIZING MODEL ROUTER. Evaluating routing across providers.
Current state
01 / INITIALIZING MODEL ROUTER.

Evaluating routing across providers.

Start learning
← Lý thuyết sâu

AI Researcher

Chính quy hóa

Vietnamese onlyThe learning content is available in Vietnamese only. The surrounding interface follows your language.

Các kỹ thuật chống overfitting bằng cách thêm ràng buộc vào quá trình huấn luyện.

lesson140 minLý thuyết sâuAI Researcher

Dự đoán

Đội bóng có 1 ngôi sao ghi 90% bàn thắng. Khi ngôi sao chấn thương, đội thua liên tục. Huấn luyện viên nên làm gì?

Buộc mọi cầu thủ đóng góp đều = Regularization! Trong mạng nơ-ron, nó ngăn vài trọng số quá lớn ('ngôi sao') chi phối toàn bộ mô hình.

Regularization ép mạng "chia sẻ vai trò" đều hơn. Hãy xem từng kỹ thuật thay đổi phân bổ trọng số như thế nào khi bạn kéo thanh cường độ, và so sánh L1 vs L2 vs ElasticNet trên bài toán sparse vs smooth.

Khoảnh khắc Aha

Regularization là cách nói "đừng quá phức tạp" với mạng nơ-ron. L1 loại bỏ trọng số thừa (cắt cầu thủ dự bị), L2 chia đều vai trò (ai cũng chơi), Dropout cho nghỉ phép ngẫu nhiên (đội mạnh ở mọi đội hình). BatchNorm chuẩn hoá áp lực, Data Augmentation mở rộng sân tập, Early Stopping gọi về khi đội bắt đầu mệt, Label Smoothing nhắc cầu thủ đừng quá tự tin.

Thử thách 1

Bạn dùng Dropout(0.5) khi huấn luyện. Khi deploy mô hình cho người dùng (inference), Dropout hoạt động thế nào?

Khi inference (model.eval()), Dropout TẮT — mọi nơ-ron đều chạy. PyTorch dùng inverted dropout: ở train, output của neuron CÒN LẠI nhân với 1/(1-p); ở eval, không làm gì. Điều này đảm bảo expected output khớp giữa train và eval.

Hàm mục tiêu có regularizer

Regularization là tập hợp kỹ thuật thêm ràng buộc vào quá trình huấn luyện để ngăn mô hình học quá sát với dữ liệu train (overfitting). Nguyên lý chung: đánh đổi một chút bias lấy rất nhiều variance giảm — theo lý thuyết bias-variance tradeoff . Công thức tổng quát:

Ltotal(θ)=Ldata(θ)+λ⋅R(θ)L_{\text{total}}(\theta) = L_{\text{data}}(\theta) + \lambda \cdot R(\theta)

Trong đó LdataL_{\text{data}} là loss chính (MSE, cross-entropy…), R(θ)R(\theta) là regularizer, và λ\lambda điều khiển cường độ. Các kỹ thuật khác nhau = các lựa chọn khác nhau cho RR hoặc cách chèn nó vào pipeline training.

L1 và L2

L1 Regularization (Lasso):

RL1(θ)=∑i∣wi∣,L=Ldata+λ∑i∣wi∣R_{L1}(\theta) = \sum_{i} |w_i|, \quad L = L_{\text{data}} + \lambda \sum_{i}|w_i|

Gradient của ∣w∣|w| là sign(w)\text{sign}(w) — không phụ thuộc độ lớn. Điều này tạo áp lực cố định đẩy mọi trọng số về 0, kể cả trọng số nhỏ. Kết quả: sparsity (nhiều wi=0w_i = 0 ), mô hình tự động feature selection. Cập nhật có dạng soft-thresholding:

w←sign(w)⋅max⁡(∣w∣−ηλ,0)w \leftarrow \text{sign}(w) \cdot \max(|w| - \eta\lambda, 0)

L2 Regularization (Ridge / Weight Decay):

RL2(θ)=12∑iwi2,L=Ldata+λ2∑iwi2R_{L2}(\theta) = \frac{1}{2}\sum_{i} w_i^2, \quad L = L_{\text{data}} + \frac{\lambda}{2} \sum_{i}w_i^2

Gradient của 12w2\tfrac{1}{2}w^2 là ww — càng lớn càng bị kéo. Cập nhật có dạng multiplicative decay:

w←w(1−ηλ)−η∇Ldataw \leftarrow w(1 - \eta\lambda) - \eta \nabla L_{\text{data}}

Thu nhỏ tất cả trọng số đều nhưng hiếm khi về 0 → phân bổ đều vai trò. Đây là kỹ thuật phổ biến nhất trong thực tế vì easy to tune và tương thích với mọi optimizer. AdamW (Adam + decoupled weight decay) là lựa chọn mặc định hiện đại.

ElasticNet

ElasticNet (L1 + L2):

REN(θ)=α∑i∣wi∣+(1−α)12∑iwi2R_{EN}(\theta) = \alpha \sum_i |w_i| + (1-\alpha) \frac{1}{2} \sum_i w_i^2

Kết hợp sparsity của L1 với stability của L2. Đặc biệt hữu ích khi feature có tương quan: L1 một mình có xu hướng chọn ngẫu nhiên 1 trong nhóm feature tương quan và loại các feature còn lại; ElasticNet giữ cả nhóm và thu nhỏ đều.

Bảng L1, L2, ElasticNet

Dropout

Dropout:

htrain(l)=m⊙h(l),mi∼Bernoulli(1−p)h^{(l)}_{\text{train}} = m \odot h^{(l)}, \quad m_i \sim \text{Bernoulli}(1-p)

Mỗi forward pass ở train, mask ngẫu nhiên mm được sample — pp phần nơ-ron bị tắt (output = 0). Ở inference, mọi nơ-ron bật. Để expected output khớp, PyTorch dùng inverted dropout: chia cho (1−p)(1-p) ở train thay vì nhân ở eval. Dropout tương đương trung bình cộng của 2n2^n mạng con — một dạng model averaging cực lớn và rẻ.

DropConnect và BatchNorm

DropConnect: Thay vì tắt neuron (output), tắt connection (weight). Mask áp dụng lên WW thay vì lên activation. Tổng quát hơn Dropout nhưng tốn memory hơn vì mỗi connection cần mask riêng. Trong thực tế hiếm dùng vì Dropout đơn giản và đủ tốt.

BatchNorm như regularizer: BatchNorm chuẩn hoá activation theo batch để giảm internal covariate shift. Hiệu ứng regularization đến từ việc μB,σB\mu_B, \sigma_B được tính trên batch ngẫu nhiên — batch khác cho statistics hơi khác, tạo noise injection nhẹ vào mỗi forward pass. Đây là dropout-like noise, nên thường khi dùng BN có thể giảm dropout rate.

Data augmentation

Data Augmentation: Tăng số lượng training sample bằng biến đổi bảo toàn label:

x~=T(x),T∈Tinvariance\tilde{x} = T(x), \quad T \in \mathcal{T}_{\text{invariance}}

Với ảnh: flip, crop, rotate, color jitter, cutout, mixup, CutMix. Với audio: pitch shift, time stretch, SpecAugment. Với text: synonym replacement, back-translation. Đây có thể là kỹ thuật regularization MẠNH nhất — với coverage data đủ, nhiều khi không cần L2 hoặc dropout.

Early stopping

Early Stopping:

θ∗=θt where t=arg⁡min⁡tLval(θt)\theta^* = \theta_t \text{ where } t = \arg\min_{t} L_{\text{val}}(\theta_t)

Theo dõi val loss mỗi epoch; dừng train khi val loss không giảm nữa (với patience). Về mặt lý thuyết, early stopping tương đương L2 implicit — train time giới hạn = capacity giới hạn.

Label smoothing

Label Smoothing: Thay vì target one-hot cứng, dùng target mềm:

yksmooth=(1−α)⋅ykonehot+αKy^{\text{smooth}}_k = (1-\alpha) \cdot y^{\text{onehot}}_k + \frac{\alpha}{K}

Với KK classes và α≈0.1\alpha \approx 0.1. Ngăn output quá confident (logit → ∞), cải thiện calibration và generalization. Phổ biến trong CV (ResNet, Vision Transformer) và NLP (Transformer). Khi dùng cross-entropy với one-hot target, model có xu hướng đẩy logit về ±∞ để gradient đạt 0 — điều này không ổn định trong finite precision.

Tổng hợp và code mẫu

regularization_full.py

import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.utils.data import DataLoader
from torchvision import transforms

# ───────────────────────────────────────────────────────────────
# 1) L2 weight decay: thêm vào optimizer
#    (Adam + weight decay đúng cách = AdamW — decoupled WD)
# ───────────────────────────────────────────────────────────────
optimizer = torch.optim.AdamW(
    model.parameters(),
    lr=1e-3,
    weight_decay=1e-4,  # λ cho L2
)

# ───────────────────────────────────────────────────────────────
# 2) L1 regularization: thêm thủ công vào loss
# ───────────────────────────────────────────────────────────────
def l1_penalty(model, lambda_l1=1e-5):
    return lambda_l1 * sum(
        p.abs().sum() for p in model.parameters() if p.requires_grad
    )

# training loop:
loss = criterion(output, target) + l1_penalty(model)

# ───────────────────────────────────────────────────────────────
# 3) ElasticNet: kết hợp L1 + L2
# ───────────────────────────────────────────────────────────────
def elastic_penalty(model, l1=1e-5, l2=1e-4, alpha=0.5):
    l1_term = sum(p.abs().sum() for p in model.parameters())
    l2_term = sum((p ** 2).sum() for p in model.parameters())
    return alpha * l1 * l1_term + (1 - alpha) * l2 * l2_term

# ───────────────────────────────────────────────────────────────
# 4) Dropout + BatchNorm trong model definition
# ───────────────────────────────────────────────────────────────
model = nn.Sequential(
    nn.Linear(784, 256),
    nn.BatchNorm1d(256),   # BN trước activation
    nn.ReLU(),
    nn.Dropout(0.3),       # tắt 30% sau activation
    nn.Linear(256, 128),
    nn.BatchNorm1d(128),
    nn.ReLU(),
    nn.Dropout(0.3),
    nn.Linear(128, 10),
)

# Quan trọng: bật/tắt Dropout và BN khi train/eval
model.train()  # Dropout ON, BN dùng batch stats
model.eval()   # Dropout OFF, BN dùng running stats

# ───────────────────────────────────────────────────────────────
# 5) Data Augmentation (torchvision)
# ───────────────────────────────────────────────────────────────
train_transform = transforms.Compose([
    transforms.RandomResizedCrop(224),
    transforms.RandomHorizontalFlip(),
    transforms.ColorJitter(0.4, 0.4, 0.4),
    transforms.RandomRotation(15),
    transforms.ToTensor(),
    transforms.Normalize(mean=[0.485, 0.456, 0.406],
                         std=[0.229, 0.224, 0.225]),
    transforms.RandomErasing(p=0.25),  # Cutout
])

# Mixup (trong training loop)
def mixup_data(x, y, alpha=0.2):
    lam = torch.distributions.Beta(alpha, alpha).sample().item()
    idx = torch.randperm(x.size(0))
    mixed_x = lam * x + (1 - lam) * x[idx]
    y_a, y_b = y, y[idx]
    return mixed_x, y_a, y_b, lam

early_stopping_label_smoothing.py

# ───────────────────────────────────────────────────────────────
# 6) Early Stopping helper
# ───────────────────────────────────────────────────────────────
class EarlyStopping:
    def __init__(self, patience=7, min_delta=0.0, restore_best=True):
        self.patience = patience
        self.min_delta = min_delta
        self.restore_best = restore_best
        self.counter = 0
        self.best_loss = float("inf")
        self.best_state = None
        self.should_stop = False

    def step(self, val_loss, model):
        if val_loss < self.best_loss - self.min_delta:
            self.best_loss = val_loss
            self.counter = 0
            if self.restore_best:
                self.best_state = {
                    k: v.detach().clone()
                    for k, v in model.state_dict().items()
                }
        else:
            self.counter += 1
            if self.counter >= self.patience:
                self.should_stop = True
                if self.restore_best and self.best_state is not None:
                    model.load_state_dict(self.best_state)

# Usage:
stopper = EarlyStopping(patience=5)
for epoch in range(100):
    train_one_epoch(model, train_loader, optimizer)
    val_loss = evaluate(model, val_loader)
    stopper.step(val_loss, model)
    if stopper.should_stop:
        print(f"Early stopping at epoch {epoch}")
        break

# ───────────────────────────────────────────────────────────────
# 7) Label Smoothing
# ───────────────────────────────────────────────────────────────
# Cách 1 — có sẵn trong PyTorch 1.10+
criterion = nn.CrossEntropyLoss(label_smoothing=0.1)

# Cách 2 — tự viết (dùng được cho custom loss)
def smooth_cross_entropy(logits, target, smoothing=0.1):
    n_classes = logits.size(-1)
    log_probs = F.log_softmax(logits, dim=-1)
    # target one-hot
    with torch.no_grad():
        true_dist = torch.zeros_like(log_probs)
        true_dist.fill_(smoothing / (n_classes - 1))
        true_dist.scatter_(1, target.unsqueeze(1), 1 - smoothing)
    return -(true_dist * log_probs).sum(dim=-1).mean()

# ───────────────────────────────────────────────────────────────
# 8) DropConnect (không có trong PyTorch — tự implement)
# ───────────────────────────────────────────────────────────────
class DropConnectLinear(nn.Module):
    def __init__(self, in_features, out_features, p=0.3):
        super().__init__()
        self.linear = nn.Linear(in_features, out_features)
        self.p = p

    def forward(self, x):
        if self.training and self.p > 0:
            mask = torch.bernoulli(
                torch.full_like(self.linear.weight, 1 - self.p)
            )
            W = self.linear.weight * mask / (1 - self.p)  # inverted
            return F.linear(x, W, self.linear.bias)
        return self.linear(x)

Đi sâu: vì sao L1 tạo sparsity

Xét optimization với constraint (dạng Lagrangian tương đương với thêm penalty):

min⁡wLdata(w)s.t. ∥w∥p≤t\min_w L_{\text{data}}(w) \quad \text{s.t. } \|w\|_p \leq t

Với p=1p=1 (L1), constraint set là hình vuông xoay (diamond) trong 2D. Với p=2p=2 (L2), constraint set là hình tròn. Nghiệm tối ưu nằm ở điểm tiếp xúc giữa contour của LdataL_{\text{data}} và constraint set.

Diamond có đỉnh (corner) trên các trục toạ độ — đó là nơi một số wi=0w_i = 0. Khi contour của loss tiếp xúc với diamond, xác suất cao tiếp xúc ở corner → sparsity. Hình tròn không có corner → tiếp xúc ở bất kỳ điểm nào, thường không có wi=0w_i = 0.

Nhìn từ gradient: ∂∣w∣/∂w\partial |w| / \partial w là sign(w)\text{sign}(w) (hằng số ±1) — lực đẩy không đổi dù ww nhỏ. Trái lại, ∂w2/∂w=2w\partial w^2 / \partial w = 2w — lực đẩy giảm tuyến tính. Khi ww nhỏ, L1 vẫn đẩy bằng lực cũ nên đưa về 0; L2 chỉ đẩy nhẹ nên dừng ở số nhỏ khác 0.

Đi sâu: Dropout là Bayesian approximation

Gal & Ghahramani (2016) chứng minh: một mạng với Dropout áp dụng trước mỗi weight layer, được train với L2, xấp xỉ variational inference trong Bayesian neural network với prior Gaussian.

Từ góc nhìn này, Dropout không chỉ là trick — nó là một phép gần đúng của p(y∣x)=∫p(y∣x,θ)p(θ∣D)dθp(y | x) = \int p(y | x, \theta) p(\theta | D) d\theta . Hệ quả:

y^MC=1T∑t=1Tfθ∼dropout(x)\hat{y}_{\text{MC}} = \frac{1}{T}\sum_{t=1}^{T} f_{\theta \sim \text{dropout}}(x)

Nếu giữ Dropout BẬT ở inference và chạy nhiều pass (Monte Carlo Dropout), ta được uncertainty estimate: variance giữa các pass phản ánh model uncertainty. Đây là kỹ thuật rẻ và dễ deploy cho predictive uncertainty, đặc biệt trong medical AI và active learning.

Tuy nhiên, MC Dropout không thay thế được Bayesian đầy đủ — chỉ approximate một họ prior cụ thể. Khi cần uncertainty chất lượng cao, nên dùng Deep Ensembles hoặc SWAG.

Ứng dụng và pitfalls

Thử thách 2

Bạn có 100 features nhưng nghi ngờ chỉ 10 features thực sự hữu ích. Nên dùng regularization nào?

L1 tạo sparsity: features không quan trọng có trọng số = 0. Đây chính là lý do L1 còn gọi là Lasso (Least Absolute Shrinkage and Selection Operator). Nếu features có tương quan cao, cân nhắc ElasticNet (L1+L2) để giữ cả nhóm feature tương quan thay vì chọn ngẫu nhiên 1.

Tóm tắt

  • Regularization = thêm ràng buộc vào quá trình train để ngăn overfitting, đánh đổi ít bias lấy nhiều variance giảm.
  • L1 (Lasso): sparse, feature selection. L2 (Ridge/weight decay): smooth, mặc định. ElasticNet: kết hợp khi feature có tương quan.
  • Dropout: tắt ngẫu nhiên p% nơ-ron khi train, mọi nơ-ron bật khi inference. DropConnect: tắt weight thay vì neuron.
  • BatchNorm có hiệu ứng regularization nhẹ nhờ noise từ batch statistics. Data Augmentation là regularization MẠNH nhất qua input.
  • Early Stopping dừng train khi val loss tăng — tương đương L2 implicit. Label Smoothing ngăn output quá confident, cải thiện calibration.
  • Combo chuẩn: AdamW(wd=1e-4) + Dropout(0.1-0.3) + BN + Augmentation + EarlyStopping + LabelSmoothing(0.1) — các kỹ thuật hỗ trợ chứ không thay thế nhau.

Continue the module

Lesson 3 of 3