직렬화된 파일을 통해 나만의 모델 유형 가져오기¶
Model Registry는 여러 가지 기본 제공 모델 유형 을 지원합니다. 또한 직렬화가 가능하고 snowflake.ml.model.custom_model.CustomModel
클래스를 확장하는 경우 외부 도구를 사용하여 학습하거나 오픈 소스 리포지토리에서 얻은 모델을 비롯한 다른 유형의 모델을 기록할 수도 있습니다.
이 가이드에서는 다음 방법을 설명합니다.
사용자 지정 모델을 만드는 방법.
Snowflake Model Registry의 로그에 모델을 기록하는 방법.
추론을 위해 배포하는 방법.
참고
이 빠른 시작 가이드 는 사용자 지정 PyCaret 모델을 로깅하는 예를 제공합니다.
키워드 인자로 모델 컨텍스트 정의하기¶
ML 에서는 ModelContext
클래스를 인스턴스화할 때 임의의 키워드 인자를 사용할 수 있으므로 사용자 지정 모델을 정의하고 초기화할 때 매개 변수, 구성 파일 또는 자체 모델 클래스의 인스턴스를 쉽게 포함할 수 있습니다.
모델 컨텍스트의 특성은 지원되는 모델 유형(예: 기본 제공 모델 유형) 또는 모델, 매개 변수 또는 구성 파일이 포함된 디렉터리 경로와 같은 경로일 수 있습니다.
다음은 모델 컨텍스트를 통해 키워드 인자를 제공하는 방법과 사용자 지정 모델 클래스에서 이를 사용하는 방법을 보여주는 예시입니다.
import json
import pandas as pd
from snowflake.ml.model import custom_model
# Initialize ModelContext with keyword arguments
# my_model can be any kind of model
mc = 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 'my_model' from the context to make predictions
model_output = self.context['my_model'].predict(input)
return pd.DataFrame({'output': model_output})
사용자 지정 모델 테스트 및 로그 기록하기¶
로컬에서 실행하여 사용자 지정 모델을 테스트할 수 있습니다.
my_model = ExampleBringYourOwnModel(mc)
output_df = my_model.predict(input_df)
모델이 의도한 대로 작동하면 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_pipeline,
model_name="my_custom_model_pipeline",
version_name="v1",
conda_dependencies=["scikit-learn"],
comment="My Custom ML Model Pipeline",
sample_input_data=train_features)
output_df = mv.run(input_df)
예: PyCaret 모델 로깅하기¶
PyCaret 은 로우코드, 고효율 서드 파티 패키지로 Snowflake가 기본적으로 지원하지 않습니다. 비슷한 방법으로 자신만의 모델 유형을 가져올 수 있습니다.
1단계: 모델 컨텍스트 정의하기¶
모델을 로깅하기 전에 ML 에서 기본적으로 지원되지 않는 자체 모델 유형을 참조하는 ModelContext
를 정의하십시오. 이 경우 컨텍스트의 model_file
특성을 사용하여 직렬화된(피클된) 모델의 경로를 지정합니다.
pycaret_mc = custom_model.ModelContext(
model_file = 'pycaret_best_model.pkl',
)
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']
})
참고
그림과 같이 모델의 메모리 디렉터리를 /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_mc)
output_df = my_pycaret_model.predict(test_df)
4단계: 모델 서명 정의하기¶
이 예에서는 샘플 데이터를 사용하여 입력 검증을 위해 모델 서명 을 추론합니다.
predict_signature = model_signature.infer_signature(input_data=test_df, output_data=output_df)
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'
)
6단계: 레지스트리에서 모델 확인하기¶
Model Registry에서 모델이 사용 가능한지 확인하려면 show_models
함수를 사용합니다.
snowml_registry.show_models()
7단계: 등록된 모델로 예측하기¶
run
함수를 사용하여 예측할 모델을 호출합니다.
snowpark_df = session.create_dataframe(test_data, schema=col_nms)
custom_mv.run(snowpark_df).show()
다음 단계¶
Snowflake Model Registry를 통해 PyCaret 모델을 배포한 후 Snowsight에서 해당 모델을 볼 수 있습니다. AI & ML 아래의 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;