0Pricing
Machine Learning Academy · บทเรียน

การทำให้เป็นระเบียบด้วยดรอปเอาต์เพื่อป้องกันการเรียนรู้เกิน

ผู้เรียนจะเพิ่ม nn.Dropout ด้วยความน่าจะเป็นหลายค่า เปรียบเทียบเส้นโค้งค่าความสูญเสียของการฝึกกับการตรวจสอบ และเรียกใช้ model.eval() เพื่อปิดดรอปเอาต์ขณะอนุมาน

การทำให้เป็นระเบียบด้วยดรอปเอาต์เพื่อป้องกันการเรียนรู้เกิน เป็นบทเรียน Machine Learning Academy ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน Machine Learning Academy และความก้าวหน้าของคุณจะซิงค์ข้ามเว็บและแอป CoddyKit คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน

บางส่วนของบทเรียนนี้ยังไม่ได้รับการแปล และแสดงเป็นภาษาอังกฤษ

What Is Dropout and Why Use It?

Dropout, introduced by Srivastava et al. in 2014, is a regularisation technique that randomly sets a fraction of neuron activations to zero during each training step. By forcing the network to operate with a random subset of neurons, it prevents any single neuron from becoming too specialised and forces the network to learn redundant representations. This reduces overfitting significantly in large fully connected networks.

import torch
import torch.nn as nn

dropout = nn.Dropout(p=0.5)   # 50% chance each neuron is zeroed

x = torch.ones(1, 8)

# Training mode: randomly zeros activations
dropout.train()
out = dropout(x)
print('Training output:', out)
# Some values are 0, survivors are scaled by 1/(1-p)

# Eval mode: dropout is disabled (identity function)
dropout.eval()
out_eval = dropout(x)
print('Eval output:', out_eval)   # all ones

The Inverted Dropout Trick

PyTorch implements inverted dropout: during training, surviving activations are scaled up by 1/(1-p) to compensate for the zeroed neurons. This means the expected sum of activations stays the same regardless of the dropout rate. The advantage is that at inference you disable dropout and use the network as-is — no need to scale outputs. This is why Dropout in eval mode is simply an identity function.

import torch
import torch.nn as nn

# With p=0.5, surviving neurons are scaled by 2.0
dropout = nn.Dropout(p=0.5)
dropout.train()

# Start with all-ones tensor
x = torch.ones(1, 10)
out = dropout(x)
print('Scaled values:', out)
# Values are either 0 or 2.0 (= 1 / (1 - 0.5))

# Expected value = (1-p) * (1/(1-p)) = 1.0 (same as input)
print('Expected value preserved:', out.mean().item())

Adding Dropout to a Network

Dropout layers are typically placed after activation functions in fully connected networks, or after pooling in CNNs. Common dropout probabilities are p=0.5 for large hidden layers and p=0.2-0.3 for smaller layers or CNNs. Dropout is usually not applied to the input layer or the final output layer. The example below shows a deep MLP with Dropout between hidden layers.

import torch.nn as nn

model = nn.Sequential(
    nn.Linear(784, 512),
    nn.ReLU(),
    nn.Dropout(p=0.5),    # regularise large hidden layer

    nn.Linear(512, 256),
    nn.ReLU(),
    nn.Dropout(p=0.5),

    nn.Linear(256, 128),
    nn.ReLU(),
    nn.Dropout(p=0.3),    # less aggressive for smaller layer

    nn.Linear(128, 10)    # no dropout on output layer
)
print(model)

train() vs eval(): Critical Usage

Forgetting to switch between training and evaluation mode is one of the most common and hard-to-debug mistakes. In training mode (model.train()), Dropout randomly zeros activations. In eval mode (model.eval()), Dropout is completely disabled and all neurons are active. Failing to call model.eval() before evaluation means the validation loss will be artificially higher and non-deterministic, making it impossible to reliably compare runs.

import torch
import torch.nn as nn

model = nn.Sequential(
    nn.Linear(4, 16), nn.ReLU(),
    nn.Dropout(0.5),
    nn.Linear(16, 2)
)

x = torch.randn(1, 4)

# Different output each time in training mode!
model.train()
print(model(x))
print(model(x))  # different due to random dropout

# Deterministic in eval mode
model.eval()
with torch.no_grad():
    print(model(x))
    print(model(x))  # same result both times

Observing Dropout's Effect on Overfitting

To see Dropout's regularisation effect, compare training and validation loss curves with and without it. Without Dropout, a large network will typically show the classic overfitting pattern: training loss near zero while validation loss remains high. With Dropout, both curves track each other more closely. The gap between training and validation accuracy (the generalisation gap) is the key metric Dropout reduces.

import torch
import torch.nn as nn
import torch.optim as optim

def make_net(use_dropout):
    layers = [nn.Linear(20, 256), nn.ReLU()]
    if use_dropout: layers.append(nn.Dropout(0.5))
    layers += [nn.Linear(256, 2)]
    return nn.Sequential(*layers)

for use_do in [False, True]:
    model = make_net(use_do)
    print(f'Dropout={use_do}:')
    # Train on 50 samples -> large model will overfit without DO
    X = torch.randn(50, 20)
    y = torch.randint(0, 2, (50,))
    opt = optim.Adam(model.parameters())
    crit = nn.CrossEntropyLoss()
    for e in range(100):
        model.train(); opt.zero_grad()
        loss = crit(model(X), y); loss.backward(); opt.step()
    print(f'  Train loss: {loss.item():.3f}')

Dropout Rate Tuning

The dropout probability p is a hyperparameter you need to tune. p=0.5 is the original default from the Dropout paper and works well for very large layers. For convolutional layers, p=0.1 to 0.25 is typical because spatial features are more structured. For Transformers, p=0.1 is standard. If your model is not overfitting, reduce p or remove Dropout. If it is strongly overfitting, increase p incrementally and monitor validation performance.

# Dropout rate guidelines
rates = {
    'Large FC layer (1000+ units)': 0.5,
    'Small FC layer (100-500 units)': 0.3,
    'CNN hidden layers': 0.1,
    'Transformer attention': 0.1,
    'LSTM': 0.2,
    'Input layer (rare)': 0.1
}

for context, rate in rates.items():
    print(f'{context}: p={rate}')

Monte Carlo Dropout for Uncertainty

An advanced use of Dropout is MC Dropout for uncertainty estimation. Instead of disabling Dropout at inference, keep it enabled and run the model N times on the same input. The mean of the N predictions is the estimate; the variance across predictions measures model uncertainty. This approximates Bayesian inference without a full Bayesian neural network. It is used in safety-critical applications like medical diagnosis where knowing 'I don't know' is valuable.

import torch
import torch.nn as nn

model = nn.Sequential(
    nn.Linear(4, 16), nn.ReLU(),
    nn.Dropout(0.5),
    nn.Linear(16, 2)
)

x = torch.randn(1, 4)
model.train()   # keep dropout ON for MC dropout

# Run 100 stochastic forward passes
preds = torch.stack([model(x) for _ in range(100)])
mean_pred = preds.mean(dim=0)
uncertainty = preds.std(dim=0)

print('Mean prediction:', mean_pred)
print('Uncertainty:', uncertainty)  # high = unsure

Spatial Dropout for CNNs

nn.Dropout2d (Spatial Dropout) zeros entire channels rather than individual activations in convolutional feature maps. This is more effective for CNNs because adjacent pixels in the same channel are highly correlated — dropping individual pixels has little effect. By dropping entire channels, the network cannot rely on any single filter and must distribute information across many channels. Use Dropout2d after Conv2d layers in place of regular Dropout.

import torch
import torch.nn as nn

conv_model = nn.Sequential(
    nn.Conv2d(3, 32, 3, padding=1),
    nn.ReLU(),
    nn.Dropout2d(p=0.1),   # drops entire channels
    nn.Conv2d(32, 64, 3, padding=1),
    nn.ReLU(),
    nn.Dropout2d(p=0.1)
)

conv_model.train()
x = torch.randn(4, 3, 16, 16)   # batch of 4 images
out = conv_model(x)
print(out.shape)   # torch.Size([4, 64, 16, 16])

Dropout vs Weight Decay: Complementary Techniques

Dropout and weight decay (L2 regularisation) are complementary regularisers — use them together. Dropout prevents co-adaptation between neurons; weight decay penalises large weights, shrinking all parameters towards zero. The combination is stronger than either alone. In AdamW, weight decay is applied correctly as a separate term, not mixed into the gradient update like in Adam. Most production models use both techniques.

import torch.nn as nn
import torch.optim as optim

model = nn.Sequential(
    nn.Linear(64, 256), nn.ReLU(),
    nn.Dropout(0.4),
    nn.Linear(256, 128), nn.ReLU(),
    nn.Dropout(0.3),
    nn.Linear(128, 10)
)

# Combine dropout in model with weight decay in optimizer
optimizer = optim.AdamW(
    model.parameters(),
    lr=1e-3,
    weight_decay=1e-4   # L2 regularisation
)
print('Model has both Dropout and L2 regularisation')

Diagnosing Overfitting with Dropout

Use the training vs validation loss plot to diagnose whether you need more regularisation. The validation loss increasing while training loss decreases is the signature of overfitting. Systematically increase dropout probability or add Dropout layers where missing. Other signals of severe overfitting include training accuracy 98%+ while validation accuracy stagnates at 70-80%, or very high variance in validation metrics across different random seeds.

# Decision guide for dropout tuning

# Gap = train_acc - val_acc
# Gap < 2% -> no overfitting, Dropout not needed (or reduce p)
# Gap 2-5% -> mild overfitting, add p=0.2-0.3
# Gap 5-10% -> moderate overfitting, use p=0.4-0.5
# Gap > 10% -> severe overfitting:
#   1. Increase dropout probability
#   2. Add more Dropout layers
#   3. Increase weight decay
#   4. Collect more training data
#   5. Reduce model capacity
print('Diagnose overfitting gap, then tune p')

Dropout in Practice: Summary

To use Dropout correctly: add nn.Dropout(p) after hidden layer activations; call model.train() during training to enable it and model.eval() during evaluation to disable it; start with p=0.5 for large FC layers and reduce if the model underfits. Pair with weight decay via AdamW for best results. Always track both training and validation metrics to confirm Dropout is actually helping — sometimes it hurts convergence speed without improving generalisation when the model is already well-regularised.

import torch.nn as nn
import torch.optim as optim

# Complete setup: Dropout + BatchNorm + AdamW
model = nn.Sequential(
    nn.Linear(128, 512),
    nn.BatchNorm1d(512),
    nn.ReLU(),
    nn.Dropout(0.5),

    nn.Linear(512, 256),
    nn.BatchNorm1d(256),
    nn.ReLU(),
    nn.Dropout(0.4),

    nn.Linear(256, 10)
)

optimizer = optim.AdamW(
    model.parameters(), lr=1e-3, weight_decay=1e-4
)
print('Ready to train with full regularisation stack')

Quick Check

Test your understanding of Machine Learning with Python concepts from this lesson.

Lesson Recap

In this lesson you learned: Dropout randomly zeros neuron activations during training to prevent co-adaptation and reduce overfitting, inverted dropout scales surviving values by 1/(1-p) so inference requires no adjustment, and model.eval() disables Dropout for deterministic and correct inference. Next up we explore weight initialisation strategies that prevent vanishing and exploding gradients in deep networks.

คำถามที่พบบ่อย

บทเรียน “การทำให้เป็นระเบียบด้วยดรอปเอาต์เพื่อป้องกันการเรียนรู้เกิน” ฟรีหรือไม่

ใช่ — ข้อความเต็มของ “การทำให้เป็นระเบียบด้วยดรอปเอาต์เพื่อป้องกันการเรียนรู้เกิน” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส Machine Learning Academy ให้อัปเกรดเป็น CoddyKit PRO คอร์ส Machine Learning Academy มีบทเรียนทั้งหมด 4 บทเรียน

คุณจะเรียนรู้อะไรในบทเรียน “การทำให้เป็นระเบียบด้วยดรอปเอาต์เพื่อป้องกันการเรียนรู้เกิน”

ผู้เรียนจะเพิ่ม nn.Dropout ด้วยความน่าจะเป็นหลายค่า เปรียบเทียบเส้นโค้งค่าความสูญเสียของการฝึกกับการตรวจสอบ และเรียกใช้ model.eval() เพื่อปิดดรอปเอาต์ขณะอนุมาน คุณปฏิบัติ Machine Learning Academy ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน

คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน Machine Learning Academy หรือไม่

ไม่จำเป็นต้องมีประสบการณ์มาก่อน Machine Learning Academy บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน

บทเรียน “การทำให้เป็นระเบียบด้วยดรอปเอาต์เพื่อป้องกันการเรียนรู้เกิน” ใช้เวลานานแค่ไหน

บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย

ฉันเขียนและรันโค้ดในบทเรียน Machine Learning Academy นี้ได้ไหม

ได้ บทเรียน Machine Learning Academy ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ

บทเรียนทั้งหมดในหลักสูตรนี้

  1. อัตราการเรียนรู้: ไฮเปอร์พารามิเตอร์ที่สำคัญที่สุด
  2. การทำให้เป็นมาตรฐานแบบแบตช์: การฝึกที่เสถียรและเร็วขึ้น
  3. การทำให้เป็นระเบียบด้วยดรอปเอาต์เพื่อป้องกันการเรียนรู้เกิน
  4. การเริ่มต้นน้ำหนัก: การเริ่มต้นแบบ Xavier และ He
← กลับไปที่ Machine Learning Academy