이 포스트는 지난 포스팅에 이어 MLflow의 tracking에 대해 리뷰.
개발자 커뮤니티 SQLER.com - Azure Databricks - MLflow를 이용한 머신러닝(1)
개발자 커뮤니티 SQLER.com - Azure Databricks - MLflow를 이용한 머신러닝(2) - Tracking
개발자 커뮤니티 SQLER.com - Azure Databricks - MLflow를 이용한 머신러닝(3) - Project
개발자 커뮤니티 SQLER.com - Azure Databricks - MLflow를 이용한 머신러닝(4) - Model Registry
개발자 커뮤니티 SQLER.com - Azure Databricks - MLflow를 이용한 머신러닝(5) - Model 배포
Azure Databricks - MLflow를 이용한 머신러닝(2) - Tracking
이 포스팅에서 수행한 전체 코드는 CloudBreadPaPa/pyspark-basic: pyspark basic self-study repo (github.com) 에서 확인할 수 있다.
왜 MLflow tracking이 필요한가?
머신러닝을 하루에서 수십번을 수행한다.
- 이러한 머신러닝 Experiment 들에서 사용한 파라미터와 모델의 metric 정보를 어떻게 관리해야 하는가?
- 한달 전에 실행한 Experiment의 정확도가 아무리 파라미터 튜닝을 해도 높지 않다, 한달 전 Experiment를 어떻게 재현할 수 있는가?
- 여러 머신러닝 모델들의 정확도 metric의 추이를 시각적으로 확인하고 싶다. 어떤 형태로 할 수 있는가?
이 Azure Databricks MLflow 문서에서는 이러한 머신러닝의 logging과 metric에 대한 문제를 해결한다.
MLflow experiment
Experiment는 MLflow run에 접근하고 제어하는 주요 요소이다. MLflow의 개별 run은 experiment에 종속된다.
Experiment를 통해 run들의 시각화나 비교, 검색을 할 수 있고 여러 artifact나 메타데이터에 접근할 수 있다.
Experiment는 두가지로 분류된다. "Notebook experiment"와 "Workspace experiment"이다.
Notebook experiment
Databricks에서 활성화된 experiment 없이 "mlflow.start_run()"를 수행할 경우 logging 정보는 notebook에 저장된다.
Workspace experiment
노트북에 속하지 않는다. 아무 노트북이나 experiment에 name이나 id로 접근해 experiment에 로그를 저장한다.
Experiment를 생성하고 로깅 수행
Diabetes 코드를 이용한다. 다음 코드를 수행해 데이터를 로드한다.
전체 코드는 CloudBreadPaPa/pyspark-basic: pyspark basic self-study repo (github.com) 리포를 참조한다.
# Import the dataset from scikit-learn and create the training and test datasets. from sklearn.model_selection import train_test_split from sklearn.datasets import load_diabetes db = load_diabetes() X = db.data y = db.target X_train, X_test, y_train, y_test = train_test_split(X, y)
Notebook experiment
experiment 지정 없이 mlflow.start_run()으로 로깅한다. notebook experiment로 지정되고 저장된다.
import mlflow import mlflow.sklearn from sklearn.ensemble import RandomForestRegressor from sklearn.metrics import mean_squared_error # In this run, neither the experiment_id nor the experiment_name parameter is provided. MLflow automatically creates a notebook experiment and logs runs to it. # Access these runs using the Experiment sidebar. Click Experiment at the upper right of this screen. with mlflow.start_run(): n_estimators = 100 max_depth = 6 max_features = 3 # Create and train model rf = RandomForestRegressor(n_estimators = n_estimators, max_depth = max_depth, max_features = max_features) rf.fit(X_train, y_train) # Make predictions predictions = rf.predict(X_test) # Log parameters mlflow.log_param("num_trees", n_estimators) mlflow.log_param("maxdepth", max_depth) mlflow.log_param("max_feat", max_features) # Log model mlflow.sklearn.log_model(rf, "random-forest-model") # Create metrics mse = mean_squared_error(y_test, predictions) # Log metrics mlflow.log_metric("mse", mse)
Workspace experiment
mlflow.set_experiment()로 experiment name을 지정하고 이곳에 로깅한다.
# This run uses mlflow.set_experiment() to specify an experiment in the workspace where runs should be logged. # If the experiment specified by experiment_name does not exist in the workspace, MLflow creates it. # Access these runs using the experiment name in the workspace file tree. experiment_name = "/Shared/diabetes_experiment/" mlflow.set_experiment(experiment_name) with mlflow.start_run(): n_estimators = 100 max_depth = 6 max_features = 3 # Create and train model rf = RandomForestRegressor(n_estimators = n_estimators, max_depth = max_depth, max_features = max_features) rf.fit(X_train, y_train) # Make predictions predictions = rf.predict(X_test) # Log parameters mlflow.log_param("num_trees", n_estimators) mlflow.log_param("maxdepth", max_depth) mlflow.log_param("max_feat", max_features) # Log model mlflow.sklearn.log_model(rf, "random-forest-model") # Create metrics mse = mean_squared_error(y_test, predictions) # Log metrics mlflow.log_metric("mse", mse)
workspace logging은 이렇게 workspace를 지정하거나 이후 id로 접근해 metric을 계속 누적할 수 있다.
우선 비교를 위해, "n_estimators", "max_depth", "max_features" 파라미터들을 수정해 두 세번 더 수행한다.
추후 결과를 비교하기 위해서이다.
Python 코드를 이용해 이러한 logging이나 metric에 접근해 display 가능하나, 이 포스팅에서는 Databricks Portal에서 먼저 체크한다. 언급한 것처럼, experiment logging을 확인하자.
이렇게 Experiment를 선택하고, 우리의 workspace experiment였던 "diabetes_experiment"을 선택한다.
몇 번 파라미터를 변경해 실행한 결과와 metric 정보가 보인다. 화면처럼, 비교할 run들을 선택하고 "compare"를 선택.
화면처럼, 개별 run에 대한 parameter와 metric의 변화를 볼 수 있다.
파라미터 별 MSE를 통한 인사이트
그렇다면, 어떤 parameter를 이용했을 경우 가장 낮은 MSE 결과를 얻는가?
위의 plot 이미지처럼, "parallel Coordinates Plot"을 선택한다. Plot을 보면, 맨 오른쪽 MSE 결과가 보이고, 푸른색 라인이 가장 낮은 MSE를 제공한다. 맨 우측부터 왼쪽으로 가면서 paramter를 보면, num_trees=90, maxdepth=6, max_feat=3일 경우 좋은 성능을 보이고 있다.
즉, 이러한 plot 비교를 통해 파라미터에 따른 모델의 성능 결과를 손쉽게 비교할 수 있고, 한단계 더 나아가, 성능이 높은 파라미터를 기준으로 조금씩 수정하면서 더 나은 모델의 성능을 기대할 수 있다.
모델 재현(Reproduce)
개별 experiment를 보면 "Reproduct Run"이 있다. 이 루틴을 이용해, 과거에 실행했던 Experiment run을 재현할 수 있다.
로깅 타겟 - 이렇게 반드시 Databricks workspace에 저장해야 하는가?
기업의 머신러닝 솔루션 개발에는 다양한 페르소나(Persona)가 있다. 예를 들면, Data scientist, 모델을 Serving하는 개발자, 인프라와 어플리케이션을 모니터링 하는 시스템관리자, 비즈니스 관리자 등이 있다.
MLaaS를 수행하는 Databricks나 AzureML은 모델과 데이터를 다루는 크리티컬한 클라우드 서비스이다. 이 서비스에 접근 가능한 페르소나는 일반적으로 Data scientist이다.
그렇다면 다른 페르소나들은 어떻게 로깅을 보고 확인하는가?
Azure라면 Application Insight나 Fluentd 와 같은 로깅을 이용하면, 이러한 모델의 트레이닝 과정을 추가적으로 외부 독립 서비스에 로깅 가능하고, 필요한 정보를 다른 페르소나들에게 전달 가능하다.
예를 들어, Azure Application Insight라면 로깅들을 Kusto query로 가져와 Visualize 하여 유사한 metric 트렌드 chart등을 손쉽게 제작이 가능하고, 필요한 페르소나들에게 Azure Dashboard 등을 통해 보여줄 수 있다.
개발자 커뮤니티 SQLER.com - MLaaS - (1) 12가지의 머신러닝을 먼저 도입한 기업들의 고민
Databricks나 AzureML 모두 Python SDK를 제공하고, 다양한 패턴의 logging을 제공한다.
프로젝트의 성격과 필요에 맞게 취사선택해 사용하자.
질문에 대한 답변
- 이러한 머신러닝 Experiment 들에서 사용한 파라미터와 모델의 metric 정보를 어떻게 관리해야 하는가?
Databricks MLflow의 tracking을 이용해 experiment에 logging해 파라미터와 모델의 metric을 저장/관리할 수 있다.
- 한달 전에 실행한 Experiment의 정확도가 아무리 파라미터 튜닝을 해도 높지 않다, 한달 전 Experiment를 어떻게 재현할 수 있는가?
Databricks의 Experiment에 개별 Run이 기록된다. 이 Run을 Reproduce해서 한달 전의 Run도 재현할 수 있다.
- 여러 머신러닝 모델들의 정확도 metric의 추이를 시각적으로 확인하고 싶다. 어떤 형태로 할 수 있는가?
Databricks의 Experiment에 저장된 모델 metric들을 compare 하여 시각적으로 metric이나 parameter의 추이를 plot으로 확인 가능하다.
당연히, Databricks처럼, 클라우드 벤더들이 제공하는 Azure AzureML이나 AWS SageMaker, GCP Vertex AI도 같은 기능을 제공한다.
참고링크
개발자 커뮤니티 SQLER.com - Azure Databricks - MLflow를 이용한 머신러닝(1)
개발자 커뮤니티 SQLER.com - Azure Databricks - MLflow를 이용한 머신러닝(2) - Tracking
개발자 커뮤니티 SQLER.com - Azure Databricks - MLflow를 이용한 머신러닝(3) - Project
개발자 커뮤니티 SQLER.com - Azure Databricks - MLflow를 이용한 머신러닝(4) - Model Registry
개발자 커뮤니티 SQLER.com - Azure Databricks - MLflow를 이용한 머신러닝(5) - Model 배포
개발자 커뮤니티 SQLER.com - MLaaS - (1) 12가지의 머신러닝을 먼저 도입한 기업들의 고민
머신러닝을 시작하는 개발자를 위한 - (1) 머신러닝 용어정리, 분류부터 MLOps까지
머신러닝을 시작하는 개발자를 위한 - (2) 머신러닝 서비스/프레임워크/툴킷 분류 및 전체 개발 흐름
머신러닝을 시작하는 개발자를 위한 - (3) 우리 개발자가 머신러닝을 해야 하는 이유는?
머신러닝을 시작하는 개발자를 위한 - (4) 2021년의 ML Trend - MLaaS와 MLOps(Machine Learning + DevOps)
2021년 머신러닝과 인공지능(AI) 트렌드 - MLaaS (서비스로의 머신러닝)
LogRunsToExperiment - Databricks (microsoft.com)
Track machine learning training runs - Azure Databricks | Microsoft Docs