직렬화된 파일을 통해 나만의 모델 유형 가져오기

Model Registry는 기본 제공 모델 유형 을 레지스트리에 직접 로깅할 수 있도록 지원합니다. 또한 다른 모델 유형을 snowflake.ml.model.custom_model.CustomModel 로 로깅하는 방법도 제공합니다. 외부 도구를 사용하여 학습하거나 오픈 소스 리포지토리에서 얻은 직렬화 가능한 모델은 CustomModel 과 함께 사용할 수 있습니다.

이 가이드에서는 다음 방법을 설명합니다.

  • 사용자 지정 모델을 만듭니다.

  • 파일 및 모델 오브젝트로 모델 컨텍스트를 생성합니다.

  • 사용자 지정 모델을 Snowflake Model Registry에 로깅합니다.

  • 추론을 위한 모델을 배포합니다.

참고

이 빠른 시작 가이드 는 사용자 지정 PyCaret 모델을 로깅하는 예를 제공합니다.

키워드 인자로 모델 컨텍스트 정의하기

``snowflake.ml.model.custom_model.ModelContext``는 사용자가 정의한 키워드 인자로 인스턴스화할 수 있습니다. 값은 문자열 파일 경로 또는 :doc:`지원되는 모델 타입</developer-guide/snowflake-ml/model-registry/built-in-models/overview>`의 인스턴스일 수 있습니다.. 파일과 직렬화된 모델은 모델 추론 논리에서 사용할 수 있도록 모델과 함께 패키징됩니다.

인메모리 모델 오브젝트 사용하기

:doc:`기본 제공 모델 유형</developer-guide/snowflake-ml/model-registry/built-in-models/overview>`을 사용하는 경우 권장되는 접근 방식은 인메모리 모델 오브젝트를 ``ModelContext``에 직접 전달하는 것입니다. 이를 통해 Snowflake ML은 직렬화를 자동으로 처리합니다.

import pandas as pd
from snowflake.ml.model import custom_model

# Initialize ModelContext with an in-memory model object
# my_model can be any supported model type (e.g., sklearn, xgboost, lightgbm, and others)
model_context = custom_model.ModelContext(
    my_model=my_model,
)

# Define a custom model class that utilizes the context
class ExampleBringYourOwnModel(custom_model.CustomModel):
    def __init__(self, context: custom_model.ModelContext) -> None:
        super().__init__(context)

    @custom_model.inference_api
    def predict(self, input: pd.DataFrame) -> pd.DataFrame:
        # Use the model with key 'my_model' from the context to make predictions
        model_output = self.context['my_model'].predict(input)
        return pd.DataFrame({'output': model_output})

# Instantiate the custom model with the model context. This instance can be logged in the model registry.
my_model = ExampleBringYourOwnModel(model_context)
Copy

참고

사용자 지정 모델 클래스에서 항상 모델 컨텍스트를 통해 모델 오브젝트에 액세스합니다. 예를 들어, ``self.model = model``을 직접 할당하는 대신 ``self.model = self.context[‘my_model’]``을 사용합니다(여기서, ``model``은 메모리 내 모델 오브젝트임). 모델에 직접 액세스하면 클로저에 모델의 두 번째 복사본이 캡처되므로 직렬화 중에 모델 파일이 상당히 커집니다.

직렬화된 파일 사용하기

Python pickle이나 JSON과 같은 직렬화된 파일에 저장된 모델 또는 데이터의 경우 ``ModelContext``에 대한 파일 경로를 제공할 수 있습니다. 파일은 직렬화된 모델, 구성 파일 또는 매개 변수가 포함된 파일일 수 있습니다. 이는 디스크 또는 구성 데이터에 저장된 사전 학습된 모델로 작업할 때 유용합니다.

import pickle
import pandas as pd
from snowflake.ml.model import custom_model

# Initialize ModelContext with a file path
# my_file_path is a local pickle file path
model_context = custom_model.ModelContext(
    my_file_path='/path/to/file.pkl',
)

# Define a custom model class that loads the pickled object
class ExampleBringYourOwnModel(custom_model.CustomModel):
    def __init__(self, context: custom_model.ModelContext) -> None:
        super().__init__(context)

        # Use 'my_file_path' key from the context to load the pickled object
        with open(self.context['my_file_path'], 'rb') as f:
            self.obj = pickle.load(f)

    @custom_model.inference_api
    def predict(self, input: pd.DataFrame) -> pd.DataFrame:
        # Use the loaded object to make predictions
        model_output = self.obj.predict(input)
        return pd.DataFrame({'output': model_output})

# Instantiate the custom model with the model context. This instance can be logged in the model registry.
my_model = ExampleBringYourOwnModel(model_context)
Copy

중요

When you combine a supported model type (such as XGBoost) with unsupported models or data, you don’t need to serialize the supported model yourself. Set the supported model object directly in the context (e.g., base_model = my_xgb_model) and it is serialized automatically.

사용자 지정 모델 테스트 및 로그 기록하기

로컬에서 실행하여 사용자 지정 모델을 테스트할 수 있습니다.

my_model = ExampleBringYourOwnModel(model_context)
output_df = my_model.predict(input_df)
Copy

모델이 의도한 대로 작동하면 Snowflake Model Registry에 기록합니다. 다음 코드 예제에서와 같이 conda_dependencies (또는 pip_requirements)를 제공하여 모델 클래스에 필요한 라이브러리를 지정합니다. 모델에 대한 입력 서명을 추론하려면 sample_input_data (pandas 또는 Snowpark DataFrame)를 제공합니다. 또는 모델 서명 을 제공합니다.

reg = Registry(session=sp_session, database_name="ML", schema_name="REGISTRY")
mv = reg.log_model(my_model,
            model_name="my_custom_model",
            version_name="v1",
            conda_dependencies=["scikit-learn"],
            comment="My Custom ML Model",
            sample_input_data=train_features)
output_df = mv.run(input_df)
Copy

예: PyCaret 모델 로깅하기

PyCaret 은 로우코드, 고효율 서드 파티 패키지로 Snowflake가 기본적으로 지원하지 않습니다. 비슷한 방법으로 자신만의 모델 유형을 가져올 수 있습니다.

1단계: 모델 컨텍스트 정의하기

모델을 로깅하기 전에 ML 에서 기본적으로 지원되지 않는 자체 모델 유형을 참조하는 ModelContext 를 정의하십시오. 이 경우 컨텍스트의 model_file 특성을 사용하여 직렬화된(피클된) 모델의 경로를 지정합니다. 해당 이름이 다른 용도로 사용되지 않는 한 특성에 대해 어떤 이름이라도 선택할 수 있습니다.

pycaret_model_context = custom_model.ModelContext(
  model_file = 'pycaret_best_model.pkl',
)
Copy

2단계: 사용자 지정 모델 클래스 만들기

네이티브 지원 없이 모델 유형을 로깅하려면 사용자 지정 모델 클래스를 정의합니다. 이 예에서는 CustomModel 에서 파생된 PyCaretModel 클래스를 정의하여 모델을 레지스트리에 로깅할 수 있도록 합니다.

from pycaret.classification import load_model, predict_model

class PyCaretModel(custom_model.CustomModel):
    def __init__(self, context: custom_model.ModelContext) -> None:
        super().__init__(context)
        model_dir = self.context["model_file"][:-4]  # Remove '.pkl' suffix
        self.model = load_model(model_dir, verbose=False)
        self.model.memory = '/tmp/'  # Update memory directory

    @custom_model.inference_api
    def predict(self, X: pd.DataFrame) -> pd.DataFrame:
        model_output = predict_model(self.model, data=X)
        return pd.DataFrame({
            "prediction_label": model_output['prediction_label'],
            "prediction_score": model_output['prediction_score']
        })
Copy

참고

그림과 같이 모델의 메모리 디렉터리를 /tmp/ 로 설정합니다. /tmp 는 항상 쓰기 가능하므로 모델이 파일을 작성할 장소가 필요한 경우 안전하게 선택할 수 있는 위치입니다. 다른 유형의 모델에는 필요하지 않을 수 있습니다.

3단계: 사용자 지정 모델 테스트하기

다음과 같은 코드를 사용하여 로컬에서 PyCaret 모델을 테스트합니다.

test_data = [
    [1, 237, 1, 1.75, 1.99, 0.00, 0.00, 0, 0, 0.5, 1.99, 1.75, 0.24, 'No', 0.0, 0.0, 0.24, 1],
    # Additional test rows...
]
col_names = ['Id', 'WeekofPurchase', 'StoreID', 'PriceCH', 'PriceMM', 'DiscCH', 'DiscMM',
            'SpecialCH', 'SpecialMM', 'LoyalCH', 'SalePriceMM', 'SalePriceCH',
            'PriceDiff', 'Store7', 'PctDiscMM', 'PctDiscCH', 'ListPriceDiff', 'STORE']

test_df = pd.DataFrame(test_data, columns=col_names)

my_pycaret_model = PyCaretModel(pycaret_model_context)
output_df = my_pycaret_model.predict(test_df)
Copy

4단계: 모델 서명 정의하기

이 예에서는 샘플 데이터를 사용하여 입력 검증을 위해 모델 서명 을 추론합니다.

predict_signature = model_signature.infer_signature(input_data=test_df, output_data=output_df)
Copy

5단계: 모델 로깅하기

다음 코드는 Snowflake Model Registry에 모델을 로깅(등록)합니다.

snowml_registry = Registry(session)

custom_mv = snowml_registry.log_model(
    my_pycaret_model,
    model_name="my_pycaret_best_model",
    version_name="version_1",
    conda_dependencies=["pycaret==3.0.2", "scipy==1.11.4", "joblib==1.2.0"],
    options={"relax_version": False},
    signatures={"predict": predict_signature},
    comment = 'My PyCaret classification experiment using the CustomModel API'
)
Copy

6단계: 레지스트리에서 모델 확인하기

Model Registry에서 모델이 사용 가능한지 확인하려면 show_models 함수를 사용합니다.

snowml_registry.show_models()
Copy

7단계: 등록된 모델로 예측하기

run 함수를 사용하여 예측할 모델을 호출합니다.

snowpark_df = session.create_dataframe(test_data, schema=col_nms)

custom_mv.run(snowpark_df).show()
Copy

다음 단계

Snowflake Model Registry를 통해 PyCaret 모델을 배포한 후 Snowsight에서 해당 모델을 볼 수 있습니다. 탐색 메뉴에서 AI & ML » :ui:`Models`를 선택합니다. 여기에 표시되지 않는 경우 ACCOUNTADMIN 역할 또는 모델을 로깅하는 데 사용한 역할을 사용하고 있는지 확인하세요.

SQL 의 모델을 사용하려면 다음과 같이 SQL 을 사용하십시오.

SELECT
    my_pycaret_model!predict(*) AS predict_dict,
    predict_dict['prediction_label']::text AS prediction_label,
    predict_dict['prediction_score']::double AS prediction_score
from pycaret_input_data;
Copy