🤖 AI/ML

Domain Adaptation

Domain Adaptation

Adapting a model to data from a different domain. A subfield of transfer learning.

📖 Detailed Explanation

Domain Adaptation is a core Transfer Learning technique that adjusts a model trained on a source domain so that it also works well on a target domain. In the real world, training data and actual operating data often have different distributions. For example, a self-driving model trained on daytime images suffers a sharp drop in performance at night or in bad weather. Domain Adaptation addresses this Domain Shift problem.

Domain Adaptation is classified according to whether the target domain has labels. Unsupervised Domain Adaptation (UDA) deals with situations where the target domain has no labels at all, while Semi-Supervised Domain Adaptation (SSDA) deals with situations where only some labels are available. As of 2024-2025, Domain Adaptation using foundation models such as CLIP and DINO v2 has become mainstream, and zero-shot Domain Adaptation through prompt tuning has also entered the stage of practical use.

Technically, learning Domain-Invariant Features is the key approach. DANN (Domain Adversarial Neural Network) trains the feature extractor to fool the domain discriminator, and MMD (Maximum Mean Discrepancy)-based methods minimize the distance between the feature distributions of the two domains. Recently, Source-Free Domain Adaptation has also been attracting attention, and it is intended for situations where source data cannot be used directly due to privacy concerns.

In practice, Sim-to-Real transfer is the most common use case. In robot manipulation, autonomous driving, and similar fields, a large amount of training data is generated with a simulator, and Domain Adaptation is used to narrow the performance gap in the real environment. Other representative examples include adapting a model trained on English to other languages in multilingual NLP, and using existing product data for new product image classification.

💻 Code Example

DANN (Domain Adversarial Neural Network) Implementation

import torch
import torch.nn as nn
from torch.autograd import Function

# Gradient Reversal Layer - 도메인 적응의 핵심
class GradientReversal(Function):
    @staticmethod
    def forward(ctx, x, alpha):
        ctx.alpha = alpha
        return x.view_as(x)

    @staticmethod
    def backward(ctx, grad_output):
        return grad_output.neg() * ctx.alpha, None

class DANN(nn.Module):
    def __init__(self, num_classes=10, backbone='resnet50'):
        super().__init__()
        # 특징 추출기 (소스와 타겟이 공유)
        self.feature_extractor = torch.hub.load(
            'pytorch/vision', backbone, pretrained=True
        )
        feature_dim = self.feature_extractor.fc.in_features
        self.feature_extractor.fc = nn.Identity()

        # 레이블 분류기
        self.classifier = nn.Sequential(
            nn.Linear(feature_dim, 256),
            nn.ReLU(),
            nn.Dropout(0.5),
            nn.Linear(256, num_classes)
        )

        # 도메인 분류기 (소스=0, 타겟=1 구분)
        self.domain_classifier = nn.Sequential(
            nn.Linear(feature_dim, 256),
            nn.ReLU(),
            nn.Dropout(0.5),
            nn.Linear(256, 2)
        )

    def forward(self, x, alpha=1.0):
        features = self.feature_extractor(x)
        class_output = self.classifier(features)
        # Gradient Reversal로 도메인 구분자를 '속이는' 학습
        reversed_features = GradientReversal.apply(features, alpha)
        domain_output = self.domain_classifier(reversed_features)
        return class_output, domain_output

# 학습 루프
def train_dann(model, source_loader, target_loader, epochs=100):
    optimizer = torch.optim.Adam(model.parameters(), lr=1e-4)
    ce_loss = nn.CrossEntropyLoss()

    for epoch in range(epochs):
        # Alpha 스케줄링 (점진적 증가)
        p = epoch / epochs
        alpha = 2. / (1. + np.exp(-10 * p)) - 1

        for (src_x, src_y), (tgt_x, _) in zip(source_loader, target_loader):
            # 소스 도메인 분류 손실
            class_out, domain_out = model(src_x, alpha)
            class_loss = ce_loss(class_out, src_y)
            src_domain_loss = ce_loss(domain_out, torch.zeros(len(src_x)).long())

            # 타겟 도메인 적대적 손실
            _, tgt_domain_out = model(tgt_x, alpha)
            tgt_domain_loss = ce_loss(tgt_domain_out, torch.ones(len(tgt_x)).long())

            total_loss = class_loss + src_domain_loss + tgt_domain_loss
            optimizer.zero_grad()
            total_loss.backward()
            optimizer.step()

CLIP-Based Zero-Shot Domain Adaptation (2025 Practical Standard)

import torch
from transformers import CLIPProcessor, CLIPModel

# CLIP을 활용한 프롬프트 기반 도메인 적응
class CLIPDomainAdapter:
    def __init__(self, model_name="openai/clip-vit-large-patch14"):
        self.model = CLIPModel.from_pretrained(model_name)
        self.processor = CLIPProcessor.from_pretrained(model_name)
        self.device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
        self.model.to(self.device)

    def create_domain_prompts(self, class_names, source_domain, target_domain):
        """도메인 특화 프롬프트 생성"""
        prompts = []
        for cls in class_names:
            # 타겟 도메인에 맞는 프롬프트
            prompts.append(f"a {target_domain} photo of a {cls}")
            prompts.append(f"a {cls} in {target_domain} conditions")
        return prompts

    def adapt_and_classify(self, image, class_names, target_domain="night"):
        """도메인 적응된 제로샷 분류"""
        prompts = [f"a {target_domain} photo of a {cls}" for cls in class_names]
        inputs = self.processor(
            text=prompts,
            images=image,
            return_tensors="pt",
            padding=True
        ).to(self.device)

        with torch.no_grad():
            outputs = self.model(**inputs)
            logits = outputs.logits_per_image
            probs = logits.softmax(dim=1)

        return class_names[probs.argmax()], probs.max().item()

# 사용 예시: 주간 학습 -> 야간 적용
adapter = CLIPDomainAdapter()
classes = ["car", "pedestrian", "bicycle", "truck"]
predicted_class, confidence = adapter.adapt_and_classify(
    night_image, classes, target_domain="nighttime"
)
print(f"예측: {predicted_class} (신뢰도: {confidence:.2%})")

📊 Performance & Cost

Domain Adaptation Techniques Target Accuracy Improvement Additional Training Time Labels Required
Direct Transfer (No Adaptation) Baseline (60-70%) None No Target Labels
DANN +10-15% +50% Training Time No Target Labels
MMD-Based +8-12% +30% Training Time No Target Labels
CLIP Zero-Shot +15-25% (vs. Direct Transfer) Inference Only (No Training Needed) No Target Labels
Few-shot Fine-tuning +20-30% +20% Training Time Small Amount of Target Labels Needed

Practical Guide: If there are no target domain labels at all, we recommend CLIP-based zero-shot adaptation; if even a small number are available, we recommend Few-shot Fine-tuning. In Sim-to-Real scenarios, combining Domain Randomization with DANN is effective.

🗣️ Say It Like This in Practice

At the Project Kickoff:

"We collected the training data from a U.S. factory, but we have to deploy to a Korean factory. Since a Domain Shift is expected, we should consider collecting unlabeled images from the Korean factory and applying Unsupervised Domain Adaptation."

In a Technical Review:

"Training on simulator data reduces data collection costs, but the Sim-to-Real gap is a problem. If we learn domain-invariant features with DANN and use only 1% of real-environment data for Fine-tuning, we can secure sufficient performance."

When Explaining Domain Adaptation in an Interview:

"The core of Domain Adaptation is aligning the feature distributions of the source and target. DANN uses adversarial learning to learn features that make the domains indistinguishable, while MMD-based methods directly minimize the statistical distance. Recently, foundation models such as CLIP have been trained on diverse domains, making zero-shot adaptation possible."

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

⚠️ Common Mistakes & Cautions

❌ Mistake 1: Ignoring the Case Where the Label Spaces of the Source and Target Differ

Domain Adaptation basically assumes that the source and target share the same classes. If there are new classes that exist only in the target, or if some classes are missing, you must use Open-set Domain Adaptation or Partial Domain Adaptation techniques.

❌ Mistake 2: Underestimating the Size of the Domain Gap

The gap between synthetic data (rendered images) and real data is very large. Simple Domain Adaptation alone may not solve it, and you should also apply Domain Randomization (randomizing color, lighting, and texture).

✅ The Right Approach

First, visualize the feature distributions of the source and target with t-SNE or UMAP to gauge the size of the domain gap. If the gap is large, use a strong pretrained model such as CLIP as the backbone; if the gap is small, simple Fine-tuning may be sufficient. Before actual deployment, be sure to validate performance on the target domain's test set.

🔗 Related Terms

📚 Learn More