MLflow는 머신러닝 관련 실험들을 관리하고 내용들을 기록할 수 있는 오픈소스 솔루션입니다. 실험의 소스 코드, 하이퍼 파라미터, 지표, 기타 부산물들을 저장하고, 해당 모델들을 협업하는 동료들과 공유할 필요가 있는데 하나의 MLflow 서버 위에서 각자 자기 실험을 만들고 공유할 수 있습니다.
비슷한 기능의 Weights & Biases가 있기는 하지만, 이는 별도 솔루션을 구매해야 하기 때문에 비용 측면에 있어서 강점이 있습니다.
1. MLflow 설치와 실행
우선, MLflow가 없는 경우 설치가 필요합니다.
pip install mlflow
설치가 완료되었다면, MLflow를 실행하기 위해서는 아래와 같은 코드를 통해 UI를 불러올 수 있습니다.
# UI 실행
$ mlflow ui
# 호스트 및 포트 지정
$ mlflow server --host 127.0.0.1 --port 8080
2. 훈련 기록
기록을 위해 모델을 훈련시키고 필요한 메타 데이터 저장을 아래와 같이 수행한다고 가정하겠습니다.
import mlflow
from mlflow.models import infer_signature
# Define the model hyperparameters
params = {
"solver": "lbfgs",
"max_iter": 1000,
"multi_class": "auto",
"random_state": 8888,
}
# Train the model
lr = LogisticRegression(**params)
lr.fit(X_train, y_train)
# Predict on the test set
y_pred = lr.predict(X_test)
# Calculate metrics
accuracy = accuracy_score(y_test, y_pred)
위 모델에서 나오는 데이터들을 기록할 수 있도록 아래 코드를 추가할 수 있습니다.
# Set our tracking server uri for logging
mlflow.set_tracking_uri(uri="http://127.0.0.1:8080")
# Create a new MLflow Experiment
mlflow.set_experiment("MLflow Quickstart")
# Start an MLflow run
with mlflow.start_run():
# Log the hyperparameters
mlflow.log_params(params)
# Log the loss metric
mlflow.log_metric("accuracy", accuracy)
# 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")
# Infer the model signature
signature = infer_signature(X_train, lr.predict(X_train))
# Log the model
model_info = mlflow.sklearn.log_model(
sk_model=lr,
artifact_path="iris_model",
signature=signature,
input_example=X_train,
registered_model_name="tracking-quickstart",
)
3. 모델 로드 및 추론
모델 기록이 끝난 후에 모델을 로드하고, 추론을 수행할 수 있습니다. 아래 코드는 mlflow의 pyfunc을 사용해 로드하는 예시 코드입니다.
# 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
4. MLflow 환경 관리
MLflow에서는 실험은 하나의 프로젝트 단위로 생각할 수 있고, 그 아래에서 실행되는 여러 Run으로 구성됩니다. 실험은 아래와 같은 코드로 실행 가능합니다.
mlflow experiments create --experiment-name [실험명]
프로젝트를 어떤 환경에서 실행시킬지 정의하는 MLProject.yaml 파일을 작성합니다. 이 파일은 패키지 모듈의 상단에 위치해서 프로젝트의 메타 정보를 저장합니다.
name: My Project
python_env: python_env.yaml
# or
# conda_env: my_env.yaml
# or
# docker_env:
# image: mlflow-docker-example
entry_points:
main:
parameters:
data_file: path
regularization: {type: float, default: 0.1}
command: "python train.py -r {regularization} {data_file}"
validate:
parameters:
data_file: path
command: "python validate.py {data_file}"
그리고 연결된 python_env.yaml 파일은 파이썬의 버전과 관련된 정보를 저장합니다.
# Python version required to run the project.
python: "3.8.15"
# Dependencies required to build packages. This field is optional.
build_dependencies:
- pip
- setuptools
- wheel==0.37.1
# Dependencies required to run the project.
dependencies:
- mlflow==2.3
- scikit-learn==1.0.2
CLI로 mlflow run을 통해 프로젝트를 실행할 수 있습니다.
mlflow run <projrect> --experiment-name <실험명>
참고자료
[1] 변성윤. "[Product Serving] 모델 관리와 모델 평가". boostcamp AI Tech.
[2] MLflow 공식 문서 Tutorial : https://mlflow.org/docs/latest/getting-started/intro-quickstart/index.html
'Python > etc' 카테고리의 다른 글
PyTorch로 Pruning 구현하기 (0) | 2025.01.02 |
---|---|
[Airflow] Slack 연동해 Task 실패 메시지 보내기 (0) | 2024.12.22 |
[Airflow] Airflow 기초 개념 공부 및 Hello World! | DAG, Operator (1) | 2024.12.20 |
[FastAPI] Web Single 패턴 구현하기 (1) | 2024.12.18 |
[FastAPI] 파이썬으로 웹 구현하기 (2) | FastAPI 확장 기능 : Lifespan, APIRouter, HTTPException, Background Task (0) | 2024.12.16 |