🤖 AI/ML

Dropout

Dropout

A regularization technique that randomly deactivates neurons during training. Effective at preventing overfitting.

📖 Detailed Explanation

Dropout is a regularization technique that prevents overfitting by randomly deactivating some neurons during the training of a neural network. Since being proposed by Professor Hinton's team in 2012, it has become a basic building block of deep learning. The core idea is to prevent over-reliance on specific neurons and thereby encourage the network to learn more robust features.

During training, each neuron is deactivated with a specified probability (usually 0.2–0.5). For example, if the dropout rate is 0.5, half of the neurons are randomly turned off at every training step. As a result, the network behaves like an ensemble of numerous sub-networks. During inference, all neurons are activated, but the output is multiplied by (1 - dropout_rate) to match the expected value from training (Inverted Dropout applies scaling during training).

As of 2024-2025, various variants besides standard Dropout are used in practice. DropBlock drops contiguous regions, taking the spatial characteristics of CNNs into account, and DropConnect drops weights. In the Transformer architecture, Attention Dropout and Stochastic Depth (Layer Dropout) are widely used. In particular, in large language models (LLMs), a low dropout rate of around 0.1 is standard for training stability.

The role of Dropout in modern deep learning varies depending on the architecture. In CNNs, BatchNorm provides a strong regularization effect, so there is a tendency to omit Dropout or apply only a low rate. On the other hand, it remains an essential regularization technique in Transformers and MLPs. Recent research has also demonstrated that Scheduled Dropout, which dynamically adjusts the dropout rate according to the training stage, is effective.

💻 Code Example

Basic Usage of Dropout in PyTorch

import torch
import torch.nn as nn

# 1. 기본 Dropout 레이어
class MLPWithDropout(nn.Module):
    def __init__(self, input_dim, hidden_dim, output_dim, dropout_rate=0.5):
        super().__init__()
        self.layers = nn.Sequential(
            nn.Linear(input_dim, hidden_dim),
            nn.ReLU(),
            nn.Dropout(p=dropout_rate),  # 학습 시 50% 뉴런 비활성화
            nn.Linear(hidden_dim, hidden_dim),
            nn.ReLU(),
            nn.Dropout(p=dropout_rate),
            nn.Linear(hidden_dim, output_dim)
        )

    def forward(self, x):
        return self.layers(x)

# 2. 학습/추론 모드 전환 (매우 중요!)
model = MLPWithDropout(784, 256, 10)

# 학습 시: Dropout 활성화
model.train()
train_output = model(train_data)

# 추론 시: Dropout 비활성화 (모든 뉴런 사용)
model.eval()
with torch.no_grad():
    test_output = model(test_data)

# 3. 2D Dropout (CNN용) - 채널 전체를 드롭
class CNNWithDropout(nn.Module):
    def __init__(self):
        super().__init__()
        self.conv_layers = nn.Sequential(
            nn.Conv2d(3, 64, 3, padding=1),
            nn.BatchNorm2d(64),
            nn.ReLU(),
            nn.Dropout2d(p=0.2),  # 공간 전체가 아닌 채널 단위 드롭
            nn.MaxPool2d(2)
        )

    def forward(self, x):
        return self.conv_layers(x)

Dropout in Transformers (Practical Pattern)

import torch.nn as nn
import torch.nn.functional as F

class TransformerBlockWithDropout(nn.Module):
    """GPT/BERT 스타일 Transformer 블록의 Dropout 적용 위치"""
    def __init__(self, d_model=768, n_heads=12, dropout=0.1):
        super().__init__()
        self.attention = nn.MultiheadAttention(d_model, n_heads, dropout=dropout)
        self.norm1 = nn.LayerNorm(d_model)
        self.norm2 = nn.LayerNorm(d_model)
        self.ffn = nn.Sequential(
            nn.Linear(d_model, d_model * 4),
            nn.GELU(),
            nn.Dropout(dropout),  # FFN 중간에 Dropout
            nn.Linear(d_model * 4, d_model),
            nn.Dropout(dropout)   # FFN 출력에 Dropout
        )
        self.dropout = nn.Dropout(dropout)

    def forward(self, x, mask=None):
        # Attention 후 Dropout + Residual
        attn_out, _ = self.attention(x, x, x, attn_mask=mask)
        x = self.norm1(x + self.dropout(attn_out))

        # FFN 후 Residual
        ffn_out = self.ffn(x)
        x = self.norm2(x + ffn_out)
        return x

# Stochastic Depth (Layer Dropout) - 레이어 전체를 드롭
class StochasticDepthBlock(nn.Module):
    def __init__(self, block, drop_prob=0.1):
        super().__init__()
        self.block = block
        self.drop_prob = drop_prob

    def forward(self, x):
        if self.training and torch.rand(1) < self.drop_prob:
            return x  # 레이어 스킵 (residual만 통과)
        return self.block(x) + x

# 학습 진행에 따른 Dropout 스케줄링
class ScheduledDropout(nn.Module):
    def __init__(self, max_dropout=0.5, warmup_steps=1000):
        super().__init__()
        self.max_dropout = max_dropout
        self.warmup_steps = warmup_steps
        self.current_step = 0

    def forward(self, x):
        if self.training:
            # 초기에는 낮은 dropout, 점진적 증가
            p = self.max_dropout * min(1.0, self.current_step / self.warmup_steps)
            return F.dropout(x, p=p, training=True)
        return x

    def step(self):
        self.current_step += 1

📊 Performance & Cost

Dropout Types Recommended Rate Main Applications Effect
Standard Dropout 0.2 ~ 0.5 FC Layer, MLP Prevents overfitting, improves accuracy by 1-3%
Dropout2d 0.1 ~ 0.3 CNN (without BatchNorm) Preserves spatial correlation
Attention Dropout 0.1 Transformer Attention Stabilizes training
Stochastic Depth 0.1 ~ 0.3 Deep ResNet, ViT Faster training, memory savings
DropConnect 0.5 Special cases Stronger regularization

Practical guide: In CNNs that use BatchNorm, minimize or omit Dropout. In Transformers, 0.1 is standard, and you can raise it up to 0.2 if overfitting is severe. For very small datasets, a dropout rate as high as 0.5 can be effective.

🗣️ Say It Like This in Practice

In a code review:

"The call to model.eval() is missing in the inference code. Because of this, Dropout stays active and the inference results differ every time. It must be fixed before deployment."

In a model tuning discussion:

"The validation loss keeps increasing while the training loss decreases. These are typical symptoms of overfitting, so let's raise the dropout rate from 0.3 to 0.5 and also add data augmentation."

In an interview:

"Dropout randomly deactivates neurons during training to prevent co-adaptation (excessive dependence between neurons). As a result, each neuron learns more independent and robust features. During inference, all neurons are used, and the output is scaled to match the expected value."

Take a mock interview on this topic → WIA SOOM AI Interview · Start for free

⚠️ Common Mistakes & Cautions

❌ Mistake 1: Forgetting to call model.eval() during inference

This is the most common mistake. If you do not call model.eval(), Dropout remains active even during inference, producing different outputs each time for the same input. BatchNorm likewise behaves differently in eval mode, so be sure to switch modes.

❌ Mistake 2: Applying Dropout right after BatchNorm

BatchNorm already provides a strong regularization effect. Applying Dropout right after BatchNorm can over-regularize and actually make training unstable. In CNNs, it is common to apply Dropout only to FC layers.

✅ The Right Way

1) Always call model.train() before training and model.eval() before inference. 2) If you use BatchNorm in a CNN, apply Dropout only to the Classifier (FC) part. 3) In Transformers, apply a low Dropout of around 0.1 to the Attention and FFN outputs. 4) Monitor for overfitting and adjust the dropout rate accordingly.

🔗 Related Terms

📚 Learn More