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
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
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(θ)
Trong đó Ldata là loss chính (MSE, cross-entropy…), R(θ) là regularizer, và λ điều khiển cường độ. Các kỹ thuật khác nhau = các lựa chọn khác nhau cho R hoặc cách chèn nó vào pipeline training.
L1 và L2
L1 Regularization (Lasso):
RL1(θ)=i∑∣wi∣,L=Ldata+λi∑∣wi∣
Gradient của ∣w∣ là 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=0 ), mô hình tự động feature selection. Cập nhật có dạng soft-thresholding:
w←sign(w)⋅max(∣w∣−ηλ,0)
L2 Regularization (Ridge / Weight Decay):
RL2(θ)=21i∑wi2,L=Ldata+2λi∑wi2
Gradient của 21w2 là w — càng lớn càng bị kéo. Cập nhật có dạng multiplicative decay:
w←w(1−ηλ)−η∇Ldata
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−α)21i∑wi2
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)
Mỗi forward pass ở train, mask ngẫu nhiên m được sample — p 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) ở train thay vì nhân ở eval. Dropout tương đương trung bình cộng của 2n 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 W 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 đượ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
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=argtminLval(θ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+Kα
Với K classes và α≈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
importtorchimporttorch.nnasnnimporttorch.nn.functionalasFfromtorch.utils.dataimportDataLoaderfromtorchvisionimporttransforms# ───────────────────────────────────────────────────────────────# 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# ───────────────────────────────────────────────────────────────defl1_penalty(model,lambda_l1=1e-5):returnlambda_l1*sum(p.abs().sum()forpinmodel.parameters()ifp.requires_grad)# training loop:loss=criterion(output,target)+l1_penalty(model)# ───────────────────────────────────────────────────────────────# 3) ElasticNet: kết hợp L1 + L2# ───────────────────────────────────────────────────────────────defelastic_penalty(model,l1=1e-5,l2=1e-4,alpha=0.5):l1_term=sum(p.abs().sum()forpinmodel.parameters())l2_term=sum((p**2).sum()forpinmodel.parameters())returnalpha*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 activationnn.ReLU(),nn.Dropout(0.3),# tắt 30% sau activationnn.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/evalmodel.train()# Dropout ON, BN dùng batch statsmodel.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)defmixup_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]returnmixed_x,y_a,y_b,lam
early_stopping_label_smoothing.py
# ───────────────────────────────────────────────────────────────# 6) Early Stopping helper# ───────────────────────────────────────────────────────────────classEarlyStopping:def__init__(self,patience=7,min_delta=0.0,restore_best=True):self.patience=patienceself.min_delta=min_deltaself.restore_best=restore_bestself.counter=0self.best_loss=float("inf")self.best_state=Noneself.should_stop=Falsedefstep(self,val_loss,model):ifval_loss<self.best_loss-self.min_delta:self.best_loss=val_lossself.counter=0ifself.restore_best:self.best_state={k:v.detach().clone()fork,vinmodel.state_dict().items()}else:self.counter+=1ifself.counter>=self.patience:self.should_stop=Trueifself.restore_bestandself.best_stateisnotNone:model.load_state_dict(self.best_state)# Usage:stopper=EarlyStopping(patience=5)forepochinrange(100):train_one_epoch(model,train_loader,optimizer)val_loss=evaluate(model,val_loader)stopper.step(val_loss,model)ifstopper.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)defsmooth_cross_entropy(logits,target,smoothing=0.1):n_classes=logits.size(-1)log_probs=F.log_softmax(logits,dim=-1)# target one-hotwithtorch.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)# ───────────────────────────────────────────────────────────────classDropConnectLinear(nn.Module):def__init__(self,in_features,out_features,p=0.3):super().__init__()self.linear=nn.Linear(in_features,out_features)self.p=pdefforward(self,x):ifself.trainingandself.p>0:mask=torch.bernoulli(torch.full_like(self.linear.weight,1-self.p))W=self.linear.weight*mask/(1-self.p)# invertedreturnF.linear(x,W,self.linear.bias)returnself.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):
wminLdata(w)s.t. ∥w∥p≤t
Với p=1 (L1), constraint set là hình vuông xoay (diamond) trong 2D. Với p=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 Ldata và constraint set.
Diamond có đỉnh (corner) trên các trục toạ độ — đó là nơi một số wi=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=0.
Nhìn từ gradient: ∂∣w∣/∂w là sign(w) (hằng số ±1) — lực đẩy không đổi dù w nhỏ. Trái lại, ∂w2/∂w=2w — lực đẩy giảm tuyến tính. Khi w 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θ . Hệ quả:
y^MC=T1t=1∑Tfθ∼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
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.