본문 바로가기
KT AIVLE SCHOOL

[KT AIVLE] mlflow를 활용한 MLOps 기초 배우기

by 얀나대장 2023. 9. 11.

주제

AI를 활용해 수어를 번역해주는 웹 사이트 제작

활용

데이터 아키텍쳐 분석, mlflow

MLFLOW 사용 방법

  • MLflow : 머신러닝 모델을 관리할 수 있는 DB 사이트. 최신/성능이 가장 좋은 모델을 선택해 업데이트하게 해줌
    https://mlflow.org/
 

MLflow - A platform for the machine learning lifecycle

An open source platform for the end-to-end machine learning lifecycle

mlflow.org

 

로컬 db 사용

  1. 코드 실행
mlflow_uri = "sqlite:///mlflow.db"
mlflow.set_tracking_uri(mlflow_uri)

2. 코드 실행

with mlflow.start_run():  # 추적 시작 지정

    model = DecisionTreeClassifier()
    model.fit(x_train, y_train)

    pred = model.predict(x_val)

    accuracy = accuracy_score(y_val, pred)

    mlflow.log_metric("accuracy", accuracy)
    mlflow.sklearn.log_model(model, "model", registered_model_name="Test_Model")

✓Terminal을 cmd로 오픈

✓conda activate ml_pipeline

✓터미널에서 아래 명령어 실행

▪ mlflow server --backend-store-uri sqlite:///mlflow.db --default-artifact-root ./artifacts

http://127.0.0.1:5000 열기.

 

실험에서 모델 추적하기

with mlflow.start_run(experiment_id=1) :

✓ mlflow.log_metric(이름, 값)

✓ mlflow.sklearn.log_model(sk_model, artifact_path, registered_model_name)

▪ sk_model : 생성한 모델 이름, artifact_path : 폴더이름

registered_model_name : mlflow에 등록할 모델 이름(버전관리하는 모델 이름)

 

수동 로깅 vs autolog

  • 수동 로깅
    • 내가 지정한 parameter, model이 저장됨
with mlflow.start_run(experiment_id = exp_id):
    
    model = RandomForestRegressor()
    model.fit(x_train, y_train)
    
    pred = model.predict(x_val)
    mlflow.log_metric("mae", mean_absolute_error(y_val, pred))
        
    # best 모델 기록하기
    mlflow.sklearn.log_model(model, "model", registered_model_name="RF")
  • autolog
    • RandomForestRegressor() 의 다양한 하이퍼파리미터 설정
    • 평가 점수들
    • 모델은 등록
    with mlflow.start_run(experiment_id=exp_id):
        
        # autolog!
        mlflow.sklearn.autolog()
        
        model = RandomForestRegressor()
        model.fit(x_train, y_train)
        
        mlflow.sklearn.autolog(disable = True)
    
    • mlflow → name 클릭 → 아래 우측 register model → 모델 이름 선택
  • autolog가 필요한 실험들
    • 여러 단계가 포함된 실험
      • 튜닝 : GridSearchCV, RandomizedSearchCV
      • 반복작업(iteration) 중간 단계의 성능 기록 관리가 필요한 알고리즘들
        • XGBoost
        • Deep Learning
    • 튜닝
     
  • with mlflow.start_run(experiment_id=exp_id):
        
        mlflow.sklearn.autolog()
        
        params = {'n_estimators':range(20,201,20)}
        model = GridSearchCV(RandomForestRegressor(), params, cv = 5)
        model.fit(x_train, y_train)
        
        # 자동기록되는 부분 : 하이퍼파리미터, 성능지표, 성능평가 결과(.cv_results_)
        
        # 수동으로 등록해야 하는 부분 : 모델등록, 그래프, 추가적인 fitting 함수
        result = pd.DataFrame(model.cv_results_)
        plt.plot('param_n_estimators', 'mean_test_score', data = result, marker = '.' )
        plt.title('RF GridSearch Tuning')
        plt.ylabel('r2 score')
        plt.xlabel('n_estimators')
        plt.grid()    
        plt.savefig('RF_GridSearch_Tuning.png')
        mlflow.log_artifact("RF_GridSearch_Tuning.png")
        
        # best 모델 기록하기
        mlflow.sklearn.log_model(model.best_estimator_, "model", registered_model_name="RF_Tuning")    
           
        mlflow.sklearn.autolog(disable = True)
    

운영중인 모델 로딩하기

✓model uri 지정하여 불러오기

✓"models:/<등록된 모델이름>/<버전>"

▪ 버전

  • 숫자
  • latest (최신버전)
  • STAGE_NAME
  • production(운영상태 버전)

 

  • tracking 서버 주소 : 각자 주소
  • 실험 이름 : experiment_09
  • 모델 이름 : Sign_Signal_09

댓글