🎯 Mục tiêu bài học
Sau bài này, bạn sẽ:
✅ Hiểu Overfitting là gì và cách phát hiện
✅ Biết 5 kỹ thuật chống overfitting
✅ Áp dụng Dropout, Early Stopping vào code
✅ Chọn kỹ thuật phù hợp cho từng bài toán
Ôn lại bài trước
Bài 4 đã học cách train model. Nhưng train xong chưa chắc đã tốt!
Hôm nay học cách làm model tốt hơn trên data mới.
⚠️ Overfitting là gì?
Định nghĩa
Overfitting: Mô hình "nhớ" training data thay vì "học" patterns → hoạt động tốt trên training nhưng kém trên data mới.
Phân biệt các trường hợp
| Trường hợp | Training Loss | Val Loss | Chẩn đoán |
|---|---|---|---|
| Good fit | Thấp | Thấp | ✅ Mô hình tốt |
| Underfitting | Cao | Cao | Model quá đơn giản |
| Overfitting | Thấp | Cao | Model quá phức tạp |
Đồ thị minh họa
Training vs Validation Loss
Gap lớn giữa 2 đường = Overfitting!
Ví dụ thực tế
Ví dụ Overfitting trong đời thực
Học thuộc lòng ≠ hiểu bài!
Checkpoint
Bạn đã hiểu Overfitting là gì?
🎲 Dropout
Dropout là gì?
Dropout: Tắt ngẫu nhiên một số neurons trong quá trình training, buộc model không phụ thuộc vào một vài neurons cụ thể.
Cách hoạt động
Dropout: Training vs Inference
30% neurons bị tắt ngẫu nhiên khi training
Tại sao Dropout hiệu quả?
- Ngăn co-adaptation: Neurons không phụ thuộc lẫn nhau
- Ensemble effect: Như training nhiều models nhỏ
- Feature redundancy: Học nhiều cách biểu diễn
Sử dụng trong Keras
1from tensorflow.keras import layers23model = keras.Sequential([4 layers.Dense(64, activation='relu', input_shape=(10,)),5 layers.Dropout(0.3), # Tắt 30% neurons6 7 layers.Dense(32, activation='relu'),8 layers.Dropout(0.2), # Tắt 20% neurons9 10 layers.Dense(1, activation='sigmoid')11])Best Practices cho Dropout
| Vị trí | Dropout rate |
|---|---|
| Sau Input layer | 0.1 - 0.2 |
| Hidden layers | 0.2 - 0.5 |
| Trước Output | Thường không dùng |
Tip: Bắt đầu với Dropout(0.2), tăng nếu còn overfitting
Checkpoint
Bạn đã hiểu cách sử dụng Dropout?
📏 L1 và L2 Regularization
Ý tưởng
Thêm một "penalty" vào loss function để giữ weights nhỏ:
L1 Regularization (Lasso)
Đặc điểm:
- Tạo sparse weights (nhiều weights = 0)
- Dùng cho feature selection
L2 Regularization (Ridge)
Đặc điểm:
- Giữ weights nhỏ nhưng không bằng 0
- Phổ biến hơn trong Deep Learning
So sánh L1 vs L2
| Đặc điểm | L1 | L2 |
|---|---|---|
| Công thức | ||
| Weights | Nhiều = 0 (sparse) | Nhỏ nhưng ≠ 0 |
| Feature selection | ✅ Tốt | ❌ Không |
| Deep Learning | Ít dùng | ⭐ Phổ biến |
Sử dụng trong Keras
1from tensorflow.keras import regularizers23# L2 Regularization4model = keras.Sequential([5 layers.Dense(64, activation='relu',6 kernel_regularizer=regularizers.l2(0.01)), # λ = 0.017 layers.Dense(32, activation='relu',8 kernel_regularizer=regularizers.l2(0.01)),9 layers.Dense(1, activation='sigmoid')10])1112# L1 Regularization13layers.Dense(64, kernel_regularizer=regularizers.l1(0.01))1415# L1 + L2 (Elastic Net)16layers.Dense(64, kernel_regularizer=regularizers.l1_l2(l1=0.01, l2=0.01))Chọn λ (lambda)
| λ | Ảnh hưởng |
|---|---|
| Quá nhỏ (0.0001) | Gần như không có regularization |
| Vừa (0.001 - 0.01) | ⭐ Thường dùng |
| Quá lớn (0.1+) | Underfitting |
Checkpoint
Bạn đã hiểu L1 và L2 Regularization?
📊 Batch Normalization
Batch Normalization là gì?
Batch Normalization: Chuẩn hóa input của mỗi layer để có mean ≈ 0 và std ≈ 1, giúp training nhanh và ổn định hơn.
Công thức
Trong đó:
- : Mean và std của batch
- : Learnable parameters
- : Hằng số nhỏ tránh chia cho 0
Tại sao BatchNorm hiệu quả?
- Giảm Internal Covariate Shift: Distribution input ổn định
- Cho phép learning rate cao hơn: Training nhanh hơn
- Regularization effect nhẹ: Giảm overfitting
Sử dụng trong Keras
1from tensorflow.keras import layers23model = keras.Sequential([4 layers.Dense(64, activation='relu', input_shape=(10,)),5 layers.BatchNormalization(), # Sau Dense, trước activation6 7 layers.Dense(32, activation='relu'),8 layers.BatchNormalization(),9 10 layers.Dense(1, activation='sigmoid')11])Vị trí đặt BatchNorm
Vị trí đặt BatchNorm
Option 1 phổ biến hơn trong thực tế
Tip: Thường đặt BatchNorm sau Dense, trước Activation
Checkpoint
Bạn đã hiểu Batch Normalization?
⏹️ Early Stopping
Early Stopping là gì?
Early Stopping: Dừng training khi validation loss bắt đầu tăng (dấu hiệu overfitting), thay vì đợi hết epochs.
Minh họa
Early Stopping
Dừng training khi validation loss bắt đầu tăng
Sử dụng trong Keras
1from tensorflow.keras.callbacks import EarlyStopping23early_stop = EarlyStopping(4 monitor='val_loss', # Theo dõi metric nào5 patience=10, # Số epochs chờ6 min_delta=0.001, # Thay đổi tối thiểu7 restore_best_weights=True, # ⭐ Quan trọng!8 verbose=19)1011history = model.fit(12 X_train, y_train,13 epochs=1000, # Đặt cao, để early stopping quyết định14 callbacks=[early_stop]15)Tham số quan trọng
| Tham số | Ý nghĩa | Giá trị thường dùng |
|---|---|---|
monitor | Metric theo dõi | 'val_loss', 'val_accuracy' |
patience | Số epochs chờ | 5, 10, 15, 20 |
restore_best_weights | Lấy weights tốt nhất | True ⭐ |
mode | Hướng tốt: min/max | 'auto' |
Checkpoint
Bạn đã hiểu Early Stopping?
🖼️ Data Augmentation
Data Augmentation là gì?
Data Augmentation: Tạo thêm dữ liệu training từ dữ liệu gốc bằng các phép biến đổi (xoay, lật, zoom...), giúp model generalize tốt hơn.
Các kỹ thuật cho Image Data
| Kỹ thuật | Mô tả | Keras |
|---|---|---|
| Horizontal Flip | Lật ngang | RandomFlip('horizontal') |
| Rotation | Xoay ảnh | RandomRotation(0.2) |
| Zoom | Phóng to/thu nhỏ | RandomZoom(0.2) |
| Brightness | Thay đổi độ sáng | RandomBrightness(0.2) |
| Contrast | Thay đổi độ tương phản | RandomContrast(0.2) |
Sử dụng trong Keras
1from tensorflow.keras import layers23# Tạo augmentation layer4data_augmentation = keras.Sequential([5 layers.RandomFlip("horizontal"),6 layers.RandomRotation(0.1),7 layers.RandomZoom(0.1),8])910# Thêm vào model11model = keras.Sequential([12 data_augmentation,13 layers.Conv2D(32, 3, activation='relu'),14 # ...15])Augmentation cho Text
| Kỹ thuật | Mô tả |
|---|---|
| Synonym Replacement | Thay từ bằng từ đồng nghĩa |
| Random Insertion | Chèn từ ngẫu nhiên |
| Random Swap | Hoán đổi vị trí từ |
| Back Translation | Dịch sang ngôn ngữ khác rồi dịch lại |
Checkpoint
Bạn đã hiểu Data Augmentation?
🔧 Kết hợp các kỹ thuật
Ví dụ Model với đầy đủ Regularization
1from tensorflow import keras2from tensorflow.keras import layers, regularizers3from tensorflow.keras.callbacks import EarlyStopping, ReduceLROnPlateau45# Xây dựng model với các kỹ thuật regularization6model = keras.Sequential([7 # Input layer8 layers.Dense(128, input_shape=(20,)),9 layers.BatchNormalization(),10 layers.Activation('relu'),11 layers.Dropout(0.3),12 13 # Hidden layer 114 layers.Dense(64, kernel_regularizer=regularizers.l2(0.01)),15 layers.BatchNormalization(),16 layers.Activation('relu'),17 layers.Dropout(0.3),18 19 # Hidden layer 220 layers.Dense(32, kernel_regularizer=regularizers.l2(0.01)),21 layers.BatchNormalization(),22 layers.Activation('relu'),23 layers.Dropout(0.2),24 25 # Output26 layers.Dense(1, activation='sigmoid')27])2829# Compile30model.compile(31 optimizer='adam',32 loss='binary_crossentropy',33 metrics=['accuracy']34)3536# Callbacks37callbacks = [38 EarlyStopping(39 monitor='val_loss',40 patience=15,41 restore_best_weights=True42 ),43 ReduceLROnPlateau(44 monitor='val_loss',45 factor=0.5,46 patience=547 )48]4950# Train51history = model.fit(52 X_train, y_train,53 epochs=200,54 batch_size=32,55 validation_split=0.2,56 callbacks=callbacks57)Thứ tự áp dụng các kỹ thuật
Thứ tự áp dụng các kỹ thuật chống Overfitting
Checkpoint
Bạn đã biết cách kết hợp các kỹ thuật?
📊 Bảng Tổng hợp
So sánh các kỹ thuật Regularization
| Kỹ thuật | Cách hoạt động | Khi nào dùng | Keras |
|---|---|---|---|
| Dropout | Tắt ngẫu nhiên neurons | Mọi mạng | Dropout(0.3) |
| L1 | Penalty | Feature selection | l1(0.01) |
| L2 | Penalty | ⭐ Mặc định | l2(0.01) |
| BatchNorm | Chuẩn hóa activations | Deep networks | BatchNormalization() |
| Early Stopping | Dừng sớm | Mọi training | EarlyStopping() |
| Data Augmentation | Tạo thêm data | Image, Text | RandomFlip() |
Checklist chống Overfitting
- Sử dụng Early Stopping
- Thêm Dropout (0.2-0.5)
- Thêm L2 Regularization
- Sử dụng Batch Normalization
- Data Augmentation (nếu image/text)
- Giảm model complexity nếu cần
- Tăng training data nếu có thể
🎉 Tuyệt vời! Bạn đã nắm vững các kỹ thuật chống Overfitting!
🎯 Tổng kết Module 1
Những gì đã học trong Module 1: ANN
- Bài 1: Deep Learning là gì, so sánh với ML
- Bài 2: Neuron, Activation Functions (Sigmoid, ReLU, Softmax)
- Bài 3: Forward & Backward Propagation
- Bài 4: Training với TensorFlow/Keras
- Bài 5: Regularization (Dropout, L2, BatchNorm)
Key Takeaways
- Neural Network = Layers of neurons với weighted connections
- Training = Forward → Loss → Backward → Update
- Keras = High-level API dễ sử dụng
- Regularization = Chống overfitting
Chuẩn bị cho Module 2: CNN
Bài tiếp theo sẽ học về:
- Convolutional Neural Networks cho xử lý ảnh
- Convolution, Pooling operations
- Các kiến trúc nổi tiếng: VGG, ResNet
🎉 Chúc mừng! Bạn đã hoàn thành Module 1: ANN Fundamentals!
