Skip to main content
MLflow는 머신러닝 실험의 하이퍼파라미터, 평가 지표, 모델 아티팩트를 자동으로 기록하고, 여러 실험을 비교할 수 있는 오픈소스 플랫폼입니다.

학습 목표

  • MLflow의 핵심 개념(Experiment, Run, Artifact)을 이해합니다.
  • 학습 과정의 파라미터와 메트릭을 자동으로 기록할 수 있습니다.
  • MLflow UI에서 실험 결과를 비교하고 분석할 수 있습니다.

실험 관리 실습

1
MLflow 설정
2
# 설치
pip install mlflow

# 로컬 UI 실행 (http://localhost:5000)
mlflow ui
3
기본 실험 기록
4
import mlflow
import mlflow.sklearn
from sklearn.ensemble import RandomForestClassifier
from sklearn.model_selection import cross_val_score
from sklearn.datasets import load_iris

X, y = load_iris(return_X_y=True)

# 실험 생성
mlflow.set_experiment("iris-classification")

# 실험 실행
with mlflow.start_run(run_name="rf-baseline"):
    # 하이퍼파라미터 기록
    params = {"n_estimators": 100, "max_depth": 5, "random_state": 42}
    mlflow.log_params(params)

    # 모델 학습
    model = RandomForestClassifier(**params)
    scores = cross_val_score(model, X, y, cv=5, scoring="accuracy")

    # 메트릭 기록
    mlflow.log_metric("cv_accuracy_mean", scores.mean())
    mlflow.log_metric("cv_accuracy_std", scores.std())

    # 모델 저장
    model.fit(X, y)
    mlflow.sklearn.log_model(model, "model")

    print(f"정확도: {scores.mean():.4f} (+/- {scores.std():.4f})")
5
여러 실험 자동 비교
6
# 여러 하이퍼파라미터 조합을 자동으로 기록
configs = [
    {"n_estimators": 50, "max_depth": 3},
    {"n_estimators": 100, "max_depth": 5},
    {"n_estimators": 200, "max_depth": 10},
    {"n_estimators": 200, "max_depth": None},
]

for config in configs:
    with mlflow.start_run(run_name=f"rf-n{config['n_estimators']}-d{config['max_depth']}"):
        mlflow.log_params(config)

        model = RandomForestClassifier(**config, random_state=42)
        scores = cross_val_score(model, X, y, cv=5, scoring="accuracy")

        mlflow.log_metric("cv_accuracy_mean", scores.mean())
        mlflow.log_metric("cv_accuracy_std", scores.std())

        model.fit(X, y)
        mlflow.sklearn.log_model(model, "model")
7
MLflow 파이프라인 통합
8
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler

with mlflow.start_run(run_name="pipeline-experiment"):
    pipe = Pipeline([
        ("scaler", StandardScaler()),
        ("classifier", RandomForestClassifier(n_estimators=100, random_state=42))
    ])

    scores = cross_val_score(pipe, X, y, cv=5, scoring="accuracy")

    mlflow.log_param("scaler", "StandardScaler")
    mlflow.log_param("n_estimators", 100)
    mlflow.log_metric("cv_accuracy", scores.mean())

    pipe.fit(X, y)
    mlflow.sklearn.log_model(pipe, "pipeline")
mlflow ui 명령으로 웹 대시보드를 실행하면, 기록된 모든 실험을 테이블과 차트로 비교할 수 있습니다.
Weights & Biases (W&B), Neptune.ai, CometML 등이 있습니다. MLflow는 오픈소스이고 로컬에서 바로 사용할 수 있어서 입문에 적합합니다. 팀 협업이 필요하면 W&B를 추가로 고려해 봅니다.

체크리스트

  • MLflow로 실험 파라미터와 메트릭을 기록할 수 있다
  • 여러 실험 결과를 MLflow UI에서 비교할 수 있다
  • 학습된 모델을 MLflow에 저장할 수 있다

다음 문서

모델 저장과 배포

학습된 모델을 저장하고 재사용합니다.

AutoML

모델 선택과 튜닝을 자동화하는 AutoML 도구를 학습합니다.

언제 쓰나

현재 문제의 목표 지표와 데이터 특성을 먼저 확인한 뒤 적용합니다. 작은 실험셋으로 빠르게 기준 성능을 확인한 뒤, 필요하면 더 복잡한 모델로 확장합니다.

실무 적용 체크리스트

  • 데이터 누수 가능성을 먼저 점검했습니다.
  • 학습/검증/테스트 분할 기준을 고정했습니다.
  • 핵심 지표(예: F1, RMSE, AUC)를 명시했습니다.
  • 베이스라인 대비 개선폭과 비용 변화를 함께 기록했습니다.

자주 나는 실수

  1. 데이터 분할 전에 전처리를 수행해 데이터 누수가 발생합니다.
  2. 단일 지표만 보고 모델을 선택해 운영 성능이 불안정해집니다.
  3. 하이퍼파라미터를 과도하게 조정해 검증셋 과적합이 생깁니다.