실험 관리 (MLflow)
MLflow는 ML 실험의 하이퍼파라미터, 평가 지표, 모델 아티팩트를 자동으로 기록하고, 여러 실험을 비교할 수 있는 오픈소스 플랫폼입니다.학습 목표
- MLflow의 핵심 개념(Experiment, Run, Artifact)을 이해합니다.
- 학습 과정의 파라미터와 메트릭을 자동으로 기록할 수 있습니다.
- MLflow UI에서 실험 결과를 비교하고 분석할 수 있습니다.
실험 관리 실습
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})")
# 여러 하이퍼파라미터 조합을 자동으로 기록
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")
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")
Q: MLflow 외에 다른 실험 관리 도구는 없나요?
Q: MLflow 외에 다른 실험 관리 도구는 없나요?
Weights & Biases (W&B), Neptune.ai, CometML 등이 있습니다. MLflow는 오픈소스이고 로컬에서 바로 사용할 수 있어서 입문에 적합합니다. 팀 협업이 필요하면 W&B를 추가로 고려해보세요.
체크리스트
- MLflow로 실험 파라미터와 메트릭을 기록할 수 있다
- 여러 실험 결과를 MLflow UI에서 비교할 수 있다
- 학습된 모델을 MLflow에 저장할 수 있다

