🤖 AI/ML

Data Drift

Data Drift

A change in data distribution over time. A cause of model performance degradation.

📖 Detailed Explanation

Data Drift is a phenomenon in which the distribution of an ML model's input data changes between training time and inference (production) time. As a result, model performance gradually degrades over time, which is called Model Decay.

Data drift is broadly classified into two types. Covariate Drift is a change in the distribution of the input features P(X), and Concept Drift is a change in the relationship between input and output P(Y|X). The change in consumption patterns during the COVID-19 pandemic is a representative example of Concept Drift.

Drift detection methods are divided into statistical tests (KS Test, Chi-Square, PSI), distribution distance measures (KL Divergence, Wasserstein Distance), and ML-based detectors. As of 2024-2025, monitoring tools such as Evidently, Arize, and NannyML provide automated drift detection.

In practice, managing data drift is at the core of MLOps. Continuous monitoring, automation of retraining pipelines, and building an alerting system for when drift occurs are essential. The EU AI Act also requires drift management in the post-market monitoring of high-risk AI.

💻 Code Example

# 데이터 드리프트 감지 - Evidently AI 활용
import pandas as pd
import numpy as np
from evidently import ColumnMapping
from evidently.report import Report
from evidently.metrics import DataDriftTable, DatasetDriftMetric
from scipy import stats

# 1. 통계적 드리프트 감지 (기본 구현)
def detect_drift_ks_test(reference_data: np.ndarray,
                         current_data: np.ndarray,
                         threshold: float = 0.05) -> dict:
    """
    Kolmogorov-Smirnov 테스트로 드리프트 감지
    귀무가설: 두 분포가 동일
    """
    statistic, p_value = stats.ks_2samp(reference_data, current_data)

    return {
        "statistic": statistic,
        "p_value": p_value,
        "drift_detected": p_value < threshold,
        "severity": "high" if statistic > 0.2 else "medium" if statistic > 0.1 else "low"
    }

# 2. PSI (Population Stability Index) 계산
def calculate_psi(reference: np.ndarray, current: np.ndarray,
                  buckets: int = 10) -> float:
    """
    PSI 계산 - 금융권에서 많이 사용
    PSI < 0.1: 변화 없음
    0.1 <= PSI < 0.2: 약간의 변화
    PSI >= 0.2: 유의미한 변화 (재훈련 필요)
    """
    # 버킷 경계 설정 (reference 기준)
    breakpoints = np.percentile(reference, np.linspace(0, 100, buckets + 1))
    breakpoints[0], breakpoints[-1] = -np.inf, np.inf

    # 각 버킷의 비율 계산
    ref_counts = np.histogram(reference, breakpoints)[0] / len(reference)
    cur_counts = np.histogram(current, breakpoints)[0] / len(current)

    # 0 방지
    ref_counts = np.clip(ref_counts, 0.0001, None)
    cur_counts = np.clip(cur_counts, 0.0001, None)

    psi = np.sum((cur_counts - ref_counts) * np.log(cur_counts / ref_counts))
    return psi

# 3. Evidently AI 활용 (실무 권장)
def create_drift_report(reference_df: pd.DataFrame,
                        current_df: pd.DataFrame,
                        target_column: str = None):
    """Evidently AI로 종합 드리프트 리포트 생성"""
    column_mapping = ColumnMapping(target=target_column)

    report = Report(metrics=[
        DatasetDriftMetric(),  # 전체 데이터셋 드리프트
        DataDriftTable()       # 컬럼별 드리프트
    ])

    report.run(reference_data=reference_df,
               current_data=current_df,
               column_mapping=column_mapping)

    return report

# 사용 예시
np.random.seed(42)
# 훈련 시점 데이터 (정규분포)
reference = np.random.normal(50, 10, 10000)
# 운영 시점 데이터 (분포 이동 발생!)
current = np.random.normal(55, 12, 10000)

# 드리프트 감지
ks_result = detect_drift_ks_test(reference, current)
psi_value = calculate_psi(reference, current)

print(f"KS Test - 드리프트 감지: {ks_result['drift_detected']}")
print(f"PSI 값: {psi_value:.4f} ({'재훈련 필요!' if psi_value >= 0.2 else '정상'})")

📊 Performance & Cost

Major data drift monitoring tools as of January 2025:

Tool Features Cost Suitable Environment
Evidently AI Open source, report generation Free (Cloud: from $400/month) Startups, PoC
Arize AI Real-time monitoring, LLM support From $750/month Enterprise
NannyML Performance estimation without labels Free (Cloud: from $500/month) Environments with label delay
WhyLabs Profile-based, lightweight Free (Pro: from $600/month) Large-scale data
AWS SageMaker AWS integration, automatic retraining Usage-based AWS environment

🗣️ Say It Like This in Practice

💬 In a Meeting
"Since last week, the CTR of the recommendation model has dropped by 15%, and the Evidently dashboard detected a PSI of 0.25 for the 'user_age' feature. It seems the age range of the customer segment brought in by the new marketing campaign has changed. I'll trigger the retraining pipeline with the new data."
💬 In an Interview
"Data drift is divided into Covariate Drift and Concept Drift. Covariate Drift is a change in the input distribution P(X), and Concept Drift is a change in P(Y|X). For detection, we use statistical tests (KS, Chi-Square) and distribution distances (PSI, KL Divergence), and I have experience building an automated monitoring system with a combination of Evidently and Prometheus-Grafana."
💬 In a Technical Discussion
"The drift response strategy differs depending on the situation. Gradual drift is handled with regular retraining, while sudden drift requires immediate alerts along with switching to a fallback model. Online learning or Continual Learning can also be considered, but caution is needed from the perspective of model stability."

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

⚠️ Common Mistakes & Cautions

❌
Monitoring not set up after deployment

If you only deploy the model and do not set up drift monitoring, you will discover performance degradation late. Set up monitoring at the same time as deployment.

❌
Applying the same threshold to all features

Drift sensitivity differs for each feature. Set a low threshold (PSI 0.1) for important features and a higher threshold (PSI 0.25) for less important features.

✅
The right way: an automated retraining pipeline

Build an automated pipeline that covers drift detection → alerting → automatic retraining → A/B testing → deployment. It is also good to operate a regular retraining schedule alongside it.

🔗 Related Terms

📚 Learn More