MLflow Tracking Quickstart
MLflow Tracking Quickstart
MLflow Tracking의 핵심 API를 가장 빠르게 익히는 방법을 소개할게요. 몇 분만 따라 하면 파라미터·메트릭·모델을 로깅하고, MLflow UI에서 확인하고, 로그된 모델을 다시 불러와 추론하는 흐름을 한 번에 잡을 수 있어요. 학습 코드에 mlflow.sklearn.autolog() 한 줄만 추가하면 나머지는 MLflow가 알아서 처리해 준다는 점이 특히 편리해요.
설치와 준비
MLflow는 PyPI에서 설치할 수 있어요.
pip install mlflow
노트북 셀에서 가장 빠르게 시작하려면 이렇게 실험을 설정해요.
import mlflow
mlflow.set_experiment("MLflow Quickstart")
모델 학습 전에 훈련 데이터와 하이퍼파라미터를 준비해요.
import pandas as pd
from sklearn import datasets
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import accuracy_score, precision_score, recall_score, f1_score
# Load the Iris dataset
X, y = datasets.load_iris(return_X_y=True)
# Split the data into training and test sets
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
# Define the model hyperparameters
params = {
"solver": "lbfgs",
"max_iter": 1000,
"random_state": 8888,
}
Autologging으로 로깅하기
이 단계에서 이전에 준비한 훈련 데이터로 모델을 학습하고, 모델과 메타데이터를 MLflow에 로깅해요. 가장 쉬운 방법은 MLflow의 Autologging 기능을 쓰는 거예요.
import mlflow
# Enable autologging for scikit-learn
mlflow.sklearn.autolog()
# Just train the model normally
lr = LogisticRegression(**params)
lr.fit(X_train, y_train)
mlflow.sklearn.autolog() 한 줄만 추가하면 모델 학습 자체에 집중할 수 있고, 나머지는 MLflow가 처리해 줘요.
- 학습된 모델 저장
- 학습 중 정확도·정밀도·AUC 곡선 같은 성능 메트릭 기록
- 모델 학습에 쓴 하이퍼파라미터 값 로깅
- 입력 데이터 형식, 사용자, 타임스탬프 같은 메타데이터 추적
autologging과 지원 라이브러리에 대한 자세한 내용은 Autologging 문서를 참고해요.
UI에서 결과 확인
학습 결과를 보려면 Tracking Server URL로 MLflow UI에 접속해요. 서버를 아직 띄우지 않았다면 MLflow 프로젝트 루트에서 새 터미널을 열고 다음을 실행해 http://localhost:5000(또는 지정한 포트)에서 UI에 접속해요.
mlflow server --port 5000
"Experiments" 섹션에는 (최근 생성된) 실험 목록이 보여요. "MLflow Quickstart" 실험을 클릭하면 학습으로 만들어진 실행 Run이 테이블에 보이고, 실행을 클릭하면 측정된 메트릭·하이퍼파라미터·태그 등을 볼 수 있는 상세 페이지가 열려요.
"Model" 섹션까지 스크롤하면 학습 중 로깅된 모델이 보여요. 모델 페이지에는 성능 메트릭·하이퍼파라미터뿐 아니라, 학습 중 로깅된 파일 목록인 "Artifacts" 섹션과 재현성을 위해 저장된 Python 버전·의존성 같은 환경 정보도 담겨요.
수동 로깅
autologging으로 로깅하는 법을 배웠으니, 이제 모델과 메타데이터를 수동으로 로깅하는 방법도 살펴볼게요. 로깅 과정을 더 세밀하게 제어하고 싶을 때 유용해요.
이 단계에서 할 일은 이래요.
- 로그할 새 실행을 시작하기 위해 MLflow run 컨텍스트 시작
- 모델 학습·테스트
- 모델 파라미터와 성능 메트릭 로깅
- 쉽게 검색하도록 실행 태그 지정
# Start an MLflow run with
with mlflow.start_run():
# Log the hyperparameters
mlflow.log_params(params)
# Train the model
lr = LogisticRegression(**params)
lr.fit(X_train, y_train)
# Log the model
model_info = mlflow.sklearn.log_model(sk_model=lr, name="iris_model")
# Predict on the test set, compute and log the loss metric
y_pred = lr.predict(X_test)
accuracy = accuracy_score(y_test, y_pred)
mlflow.log_metric("accuracy", accuracy)
# Optional: Set a tag that we can use to remind ourselves what this run was for
mlflow.set_tag("Training Info", "Basic LR model for iris data")
모델 로딩과 추론
모델을 로깅한 뒤 추론은 이렇게 해요.
- MLflow의
pyfunc플레이버로 모델 로딩 - 로드된 모델에 새 데이터로 Predict 실행
네이티브 scikit-learn 모델로 로드하려면 pyfunc 대신 mlflow.sklearn.load_model(model_info.model_uri)를 쓰면 돼요.
# Load the model back for predictions as a generic Python Function model
loaded_model = mlflow.pyfunc.load_model(model_info.model_uri)
predictions = loaded_model.predict(X_test)
iris_feature_names = datasets.load_iris().feature_names
result = pd.DataFrame(X_test, columns=iris_feature_names)
result["actual_class"] = y_test
result["predicted_class"] = predictions
result[:4]
출력은 대략 이런 모습이에요.
| sepal length (cm) | sepal width (cm) | petal length (cm) | petal width (cm) | actual_class | predicted_class |
|---|---|---|---|---|---|
| 6.1 | 2.8 | 4.7 | 1.2 | 1 | 1 |
| 5.7 | 3.8 | 1.7 | 0.3 | 0 | 0 |
| 7.7 | 2.6 | 6.9 | 2.3 | 2 | 2 |
| 6.0 | 2.9 | 4.5 | 1.5 | 1 | 1 |
이제 MLflow Tracking API로 모델을 로깅하는 기본 흐름을 이해했어요.
더 알아보기
- MLflow Tracking — Tracking API 상세
- MLflow Model Registry — 모델 버전·수명주기 관리
- MLflow Models — 모델 패키징 포맷
- MLflow Projects — 재현 가능한 코드 패키징