다음을 통해 공유


시작: Azure Databricks에서 첫 번째 기계 학습 모델 빌드

이 문서에서는 Azure Databricks의 scikit-learn 라이브러리를 사용하여 기계 학습 분류 모델을 빌드하는 방법을 보여 줍니다.

목표는 와인이 "고품질"로 간주되는지 여부를 예측하는 분류 모델을 만드는 것입니다. 데이터 세트는 다양한 와인(예: 알코올 함량, 산도 및 잔류 설탕)의 11가지 기능과 1에서 10 사이의 품질 순위로 구성됩니다.

이 예는 또한 MLflow를 사용하여 모델 개발 프로세스를 추적하고, Hyperopt를 사용하여 하이퍼 매개 변수 튜닝을 자동화하는 방법을 보여 줍니다.

데이터 세트는 물리화학적 속성에서 데이터 마이닝을 통한 와인 기본 설정 모델링[Cortez et al., 2009]에 제시된 UCI 머신 러닝 리포지토리에서 나온 것입니다.

시작하기 전에

  • Unity 카탈로그용으로 작업 영역을 활성화해야 합니다.
  • 클러스터를 만들거나 클러스터에 액세스할 수 있는 권한이 있어야 합니다.
  • 카탈로그에 대한 USE_CATALOG 권한이 있어야 합니다.
  • 해당 카탈로그 내에서 스키마에는 다음과 같은 권한이 있어야 합니다: USE_SCHEMA, CREATE_TABLE 및 CREATE_MODEL에 대한 권한이 있어야 합니다.

이 문서의 모든 코드는 작업 영역으로 직접 가져올 수 있는 Notebook에서 사용할 수 있습니다. 예제 Notebook: 분류 모델 빌드를 참조하세요.

1단계: Databricks Notebook 만들기

작업 영역에서 Notebook을 생성하려면 사이드바의 새 아이콘새로 만들기를 클릭한 다음 Notebook을 클릭합니다. 작업 영역에서 빈 전자 필기장이 열립니다.

Notebook 만들기 및 관리에 대한 자세한 내용은 Notebook 관리를 참조하세요.

2단계: 컴퓨팅 리소스에 연결

예비 데이터 분석 및 데이터 엔지니어링을 수행하려면 컴퓨팅에 액세스할 수 있어야 합니다.

기존 컴퓨팅 리소스에 연결하는 방법에 대한 지침은 컴퓨팅을 참조하세요. 새 컴퓨팅 리소스를 구성하는 방법에 대한 지침은 컴퓨팅 구성 참조를 참조하세요.

이 문서의 단계에는 Machine Learning용 Databricks 런타임이 필요합니다. Databricks Runtime의 ML 버전을 선택하는 자세한 정보와 지침은 Machine Learning용 Databricks Runtime을 참조하세요.

3단계: 모델 레지스트리, 카탈로그 및 스키마 설정

시작하기 전에 두 가지 중요한 단계가 필요합니다. 먼저 Unity 카탈로그를 모델 레지스트리로 사용하도록 MLflow 클라이언트를 구성해야 합니다. Notebook의 새 셀에 다음 코드를 입력합니다.

import mlflow
mlflow.set_registry_uri("databricks-uc")

모델을 등록할 카탈로그 및 스키마도 설정해야 합니다. 카탈로그에 대한 USE CATALOG 권한과 스키마에 대한 USE_SCHEMA, CREATE_TABLE 및 CREATE_MODEL 권한이 있어야 합니다.

Unity 카탈로그를 사용하는 방법에 대한 자세한 내용은 Unity 카탈로그란?을 참조하세요..

Notebook의 새 셀에 다음 코드를 입력합니다.

# If necessary, replace "main" and "default" with a catalog and schema for which you have the required permissions.
CATALOG_NAME = "main"
SCHEMA_NAME = "default"

4단계: 데이터 로드 및 Unity 카탈로그 테이블 만들기

이 예제에서는 Azure Databricks에 기본 제공되는 두 개의 CSV 파일을 사용합니다. 사용자 고유의 데이터를 수집하는 방법을 알아보려면 Databricks Lakehouse로 데이터 수집을 참조하세요.

Notebook의 새 셀에 다음 코드를 입력합니다.

white_wine = spark.read.csv("dbfs:/databricks-datasets/wine-quality/winequality-white.csv", sep=';', header=True)
red_wine = spark.read.csv("dbfs:/databricks-datasets/wine-quality/winequality-red.csv", sep=';', header=True)

# Remove the spaces from the column names
for c in white_wine.columns:
    white_wine = white_wine.withColumnRenamed(c, c.replace(" ", "_"))
for c in red_wine.columns:
    red_wine = red_wine.withColumnRenamed(c, c.replace(" ", "_"))

# Define table names
red_wine_table = f"{CATALOG_NAME}.{SCHEMA_NAME}.red_wine"
white_wine_table = f"{CATALOG_NAME}.{SCHEMA_NAME}.white_wine"

# Write to tables in Unity Catalog
spark.sql(f"DROP TABLE IF EXISTS {red_wine_table}")
spark.sql(f"DROP TABLE IF EXISTS {white_wine_table}")
white_wine.write.saveAsTable(f"{CATALOG_NAME}.{SCHEMA_NAME}.white_wine")
red_wine.write.saveAsTable(f"{CATALOG_NAME}.{SCHEMA_NAME}.red_wine")

5단계 데이터 전처리 및 분할

이 단계에서는 4단계에서 만든 Unity 카탈로그 테이블의 데이터를 Pandas DataFrames로 로드하고 데이터를 전처리합니다. 이 섹션의 코드는 다음과 같은 작업을 수행합니다.

  1. 데이터를 Pandas DataFrames로 로드합니다.
  2. 각 DataFrame에 부울 열을 추가하여 빨간색 와인과 화이트 와인을 구분한 다음, DataFrame을 새 DataFrame data_df으로 결합합니다.
  3. 데이터 세트에는 와인을 1에서 10까지 평가하는 quality 열이 포함되어 있으며, 10은 최고 품질을 나타냅니다. 이 코드는 이 열을 두 가지 분류 값으로 변환합니다. "True"는 고품질 와인(quality>= 7)을 나타내고 "False"는 고품질이 아닌 와인을 나타냅니다(quality< 7).
  4. DataFrame을 학습 및 테스트 세트로 분할합니다.

먼저 필요한 라이브러리 가져오기:

import numpy as np
import pandas as pd
import sklearn.datasets
import sklearn.metrics
import sklearn.model_selection
import sklearn.ensemble

import matplotlib.pyplot as plt

from hyperopt import fmin, tpe, hp, SparkTrials, Trials, STATUS_OK
from hyperopt.pyll import scope

데이터 로드 및 전처리:

# Load data from Unity Catalog as Pandas dataframes
white_wine = spark.read.table(f"{CATALOG_NAME}.{SCHEMA_NAME}.white_wine").toPandas()
red_wine = spark.read.table(f"{CATALOG_NAME}.{SCHEMA_NAME}.red_wine").toPandas()

# Add Boolean fields for red and white wine
white_wine['is_red'] = 0.0
red_wine['is_red'] = 1.0
data_df = pd.concat([white_wine, red_wine], axis=0)

# Define classification labels based on the wine quality
data_labels = data_df['quality'].astype('int') >= 7
data_df = data_df.drop(['quality'], axis=1)

# Split 80/20 train-test
X_train, X_test, y_train, y_test = sklearn.model_selection.train_test_split(
  data_df,
  data_labels,
  test_size=0.2,
  random_state=1
)

6단계 분류 모델 학습

이 단계에서는 기본 알고리즘 설정을 사용하여 그라데이션 부스팅 분류자를 학습시킵니다. 그런 다음 결과 모델을 테스트 데이터 세트에 적용하고, 모델의 성능을 평가하기 위해 수신기 작동 곡선 아래의 영역을 계산, 로그 및 표시합니다.

먼저 MLflow 자동 로깅 사용:

mlflow.autolog()

이제 모델 학습 실행을 시작합니다.

with mlflow.start_run(run_name='gradient_boost') as run:
    model = sklearn.ensemble.GradientBoostingClassifier(random_state=0)

    # Models, parameters, and training metrics are tracked automatically
    model.fit(X_train, y_train)

    predicted_probs = model.predict_proba(X_test)
    roc_auc = sklearn.metrics.roc_auc_score(y_test, predicted_probs[:,1])
    roc_curve = sklearn.metrics.RocCurveDisplay.from_estimator(model, X_test, y_test)

    # Save the ROC curve plot to a file
    roc_curve.figure_.savefig("roc_curve.png")

    # The AUC score on test data is not automatically logged, so log it manually
    mlflow.log_metric("test_auc", roc_auc)

    # Log the ROC curve image file as an artifact
    mlflow.log_artifact("roc_curve.png")

    print("Test AUC of: {}".format(roc_auc))

셀 결과에는 곡선 아래의 계산 영역과 ROC 곡선의 그림이 표시됩니다.

분류 모델의 ROC 곡선입니다.

7단계 MLflow에서 실험 실행 보기

MLflow 실험 추적을 사용하면 모델을 반복적으로 개발할 때 코드 및 결과를 로깅하여 모델 개발을 추적할 수 있습니다.

방금 실행한 학습 실행에서 기록된 결과를 보려면 다음 이미지와 같이 셀 출력의 링크를 클릭합니다.

셀 결과 실험에 연결합니다.

실험 페이지에서 실행을 비교하고 특정 실행에 대한 세부 정보를 볼 수 있습니다. MLflow 실험 추적을 참조하세요.

8단계. 하이퍼 매개 변수 튜닝

ML 모델을 개발하는 중요한 단계는 하이퍼 매개 변수라는 알고리즘을 제어하는 매개 변수를 튜닝하여 모델의 정확도를 최적화하는 것입니다.

Databricks Runtime ML에는 하이퍼 매개 변수 튜닝을 위한 Python 라이브러리인 Hyperopt가 포함되어 있습니다. Hyperopt를 사용하여 하이퍼 매개 변수 스윕을 실행하고 여러 모델을 병렬로 학습하여 모델 성능을 최적화하는 데 필요한 시간을 줄일 수 있습니다. MLflow 추적은 Hyperopt와 통합되어 모델 및 매개 변수를 자동으로 기록합니다. Databricks에서 Hyperopt 이용에 관한 추가 정보는 Hyperparameter 튜닝을 참조하세요.

다음은 Hyperopt를 사용하는 예입니다.

# Define the search space to explore
search_space = {
  'n_estimators': scope.int(hp.quniform('n_estimators', 20, 1000, 1)),
  'learning_rate': hp.loguniform('learning_rate', -3, 0),
  'max_depth': scope.int(hp.quniform('max_depth', 2, 5, 1)),
}

def train_model(params):
  # Enable autologging on each worker
  mlflow.autolog()
  with mlflow.start_run(nested=True):
    model_hp = sklearn.ensemble.GradientBoostingClassifier(
      random_state=0,
      **params
    )
    model_hp.fit(X_train, y_train)
    predicted_probs = model_hp.predict_proba(X_test)
    # Tune based on the test AUC
    # In production, you could use a separate validation set instead
    roc_auc = sklearn.metrics.roc_auc_score(y_test, predicted_probs[:,1])
    mlflow.log_metric('test_auc', roc_auc)

    # Set the loss to -1*auc_score so fmin maximizes the auc_score
    return {'status': STATUS_OK, 'loss': -1*roc_auc}

# SparkTrials distributes the tuning using Spark workers
# Greater parallelism speeds processing, but each hyperparameter trial has less information from other trials
# On smaller clusters try setting parallelism=2
spark_trials = SparkTrials(
  parallelism=1
)

with mlflow.start_run(run_name='gb_hyperopt') as run:
  # Use hyperopt to find the parameters yielding the highest AUC
  best_params = fmin(
    fn=train_model,
    space=search_space,
    algo=tpe.suggest,
    max_evals=32,
    trials=spark_trials)

9단계. 최상의 모델을 찾아 Unity 카탈로그에 등록

다음 코드는 ROC 곡선 아래의 영역으로 측정된 최상의 결과를 생성한 실행을 식별합니다.

# Sort runs by their test auc. In case of ties, use the most recent run.
best_run = mlflow.search_runs(
  order_by=['metrics.test_auc DESC', 'start_time DESC'],
  max_results=10,
).iloc[0]
print('Best Run')
print('AUC: {}'.format(best_run["metrics.test_auc"]))
print('Num Estimators: {}'.format(best_run["params.n_estimators"]))
print('Max Depth: {}'.format(best_run["params.max_depth"]))
print('Learning Rate: {}'.format(best_run["params.learning_rate"]))

식별한 최상의 모델 run_id를 사용하여, 다음 코드는 그 모델을 Unity 카탈로그에 등록합니다.

model_uri = 'runs:/{run_id}/model'.format(
    run_id=best_run.run_id
  )

mlflow.register_model(model_uri, f"{CATALOG_NAME}.{SCHEMA_NAME}.wine_quality_model")

Notebook 예제: 분류 모델 빌드

다음 Notebook을 사용하여 이 문서의 단계를 수행합니다. Azure Databricks 작업 영역으로 Notebook을 가져오는 방법에 대한 지침은 Notebook 가져오기를 참조하세요.

Databricks를 사용하여 첫 번째 기계 학습 모델 빌드

노트북 가져오기

자세한 정보

Databricks는 원시 데이터부터 제공된 모델에 대한 모든 요청 및 응답을 저장하는 유추 테이블에 이르기까지 ML 개발 및 배포의 모든 단계를 제공하는 단일 플랫폼을 제공합니다. 데이터 과학자, 데이터 엔지니어, ML 엔지니어 및 DevOps는 동일한 도구 집합과 데이터에 대한 단일 진리 소스를 사용하여 작업을 수행할 수 있습니다.

자세한 알아보려면 다음을 참조하세요.