🤖 AI/ML

Epoch

Epoch

One pass of learning over the entire training dataset. Repeating multiple epochs improves model performance.

📖 Detailed Explanation

An epoch means one complete pass of the entire training dataset through a neural network. For example, when training on a dataset of 10,000 samples, 1 epoch refers to the point at which all 10,000 samples have passed through the model and contributed to weight updates.

The epoch, together with the batch and the iteration, is a core unit for measuring training progress. If the batch size is 100 and the data contains 10,000 samples, 1 epoch = 100 iterations. In each iteration, gradient descent is applied per batch, and each time an epoch ends, the entire dataset has been traversed.

Choosing an appropriate number of epochs is an important part of hyperparameter tuning. If there are too few epochs, the model cannot learn sufficiently and underfitting occurs; if there are too many, it overfits the training data. In general, the validation loss is monitored and the optimal number of epochs is determined using the Early Stopping technique.

In large-scale model training, the number of epochs directly affects training time and cost. GPT-3 was trained over dozens of epochs for several months. By using transfer learning, good performance can be obtained by fine-tuning a pretrained model for only 3-5 epochs, which greatly improves training efficiency.

💻 Code Example

# PyTorch에서 에포크 기반 학습 구현
import torch
import torch.nn as nn
from torch.utils.data import DataLoader, TensorDataset

# 하이퍼파라미터 설정
EPOCHS = 100
BATCH_SIZE = 32
LEARNING_RATE = 0.001
PATIENCE = 10  # Early Stopping 인내심

# 모델 정의
model = nn.Sequential(
    nn.Linear(784, 256),
    nn.ReLU(),
    nn.Dropout(0.2),
    nn.Linear(256, 10)
)

# 손실 함수와 옵티마이저
criterion = nn.CrossEntropyLoss()
optimizer = torch.optim.Adam(model.parameters(), lr=LEARNING_RATE)

# 학습 데이터 로더 (예시)
train_loader = DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=BATCH_SIZE)

# Early Stopping 변수
best_val_loss = float('inf')
patience_counter = 0

# 에포크 루프
for epoch in range(EPOCHS):
    # === 훈련 단계 ===
    model.train()
    train_loss = 0.0

    for batch_idx, (data, target) in enumerate(train_loader):
        optimizer.zero_grad()
        output = model(data)
        loss = criterion(output, target)
        loss.backward()
        optimizer.step()

        train_loss += loss.item()

        # 이터레이션 진행 상황
        if batch_idx % 100 == 0:
            print(f"Epoch {epoch+1}/{EPOCHS} - "
                  f"Iteration {batch_idx}/{len(train_loader)}")

    train_loss /= len(train_loader)

    # === 검증 단계 ===
    model.eval()
    val_loss = 0.0
    correct = 0

    with torch.no_grad():
        for data, target in val_loader:
            output = model(data)
            val_loss += criterion(output, target).item()
            pred = output.argmax(dim=1)
            correct += pred.eq(target).sum().item()

    val_loss /= len(val_loader)
    accuracy = 100. * correct / len(val_dataset)

    print(f"Epoch {epoch+1}/{EPOCHS} 완료 - "
          f"Train Loss: {train_loss:.4f}, "
          f"Val Loss: {val_loss:.4f}, "
          f"Val Acc: {accuracy:.2f}%")

    # === Early Stopping 체크 ===
    if val_loss < best_val_loss:
        best_val_loss = val_loss
        patience_counter = 0
        torch.save(model.state_dict(), 'best_model.pt')  # 최고 모델 저장
        print(f"  → 최적 모델 저장 (Val Loss: {val_loss:.4f})")
    else:
        patience_counter += 1
        if patience_counter >= PATIENCE:
            print(f"\nEarly Stopping: {PATIENCE} 에포크 동안 개선 없음")
            break

print(f"\n학습 완료! 최종 에포크: {epoch+1}, 최적 Val Loss: {best_val_loss:.4f}")

📊 Performance & Cost

Item Typical values Notes
Image Classification (Transfer Learning) 3-10 epochs When fine-tuning a pretrained model
Image Classification (From Scratch) 50-200 epochs Varies depending on data size
NLP Fine-Tuning 2-5 epochs BERT and GPT-based models
Large-Scale Pretraining 1-3 epochs If the data is large enough, even 1 epoch is OK
GPU Time (ImageNet) ~2 hours/epoch Based on a single V100 GPU

🗣️ Say It Like This in Practice

"I ran 10 epochs, and overfitting had already started by epoch 5."

"I set Early Stopping with a patience of 5."

"The training time per epoch was too long, so I increased the batch size."

"The validation loss hasn't dropped since epoch 3. Should we lower the learning rate?"

⚠️ Common Mistakes & Cautions

1. Fixed number of epochs: Training for a fixed number of epochs without looking at the validation loss leads to overfitting or underfitting. Be sure to use Early Stopping.

2. Not applying shuffling: If the data order is the same every epoch, training can become biased. Set shuffle=True in the DataLoader.

3. Missing validation: If you do not measure performance on the validation data every epoch, you cannot detect overfitting.

4. Ignoring learning rate scheduling: Decreasing the learning rate as epochs progress enables more stable convergence. Use StepLR, CosineAnnealing, and the like.

🔗 Related Terms

Batch Normalization - A technique for stabilizing training

Gradient Descent - A weight update algorithm

Overfitting - Occurs when there are too many epochs

Dropout - A technique for preventing overfitting

Transfer Learning - A strategy for reducing epochs

📚 Learn More

PyTorch Training Tutorial - Hands-on practice with epoch-based training

TensorFlow/Keras Training Guide - Using the epochs parameter

Early Stopping Guide - Finding the optimal epoch