직렬화된 파일을 통해 나만의 모델 유형 가져오기¶
Model Registry는 기본 제공 모델 유형 을 레지스트리에 직접 로깅할 수 있도록 지원합니다. 또한 다른 모델 유형을 snowflake.ml.model.custom_model.CustomModel 로 로깅하는 방법도 제공합니다. 외부 도구를 사용하여 학습하거나 오픈 소스 리포지토리에서 얻은 직렬화 가능한 모델은 CustomModel 과 함께 사용할 수 있습니다.
이 가이드에서는 다음 방법을 설명합니다.
사용자 지정 모델을 만듭니다.
파일 및 모델 오브젝트로 모델 컨텍스트를 생성합니다.
``code_paths``를 사용하여 모델에 추가 코드를 포함합니다.
사용자 지정 모델을 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)
직렬화된 파일 사용하기¶
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)
중요
지원되는 모델 유형(예: XGBoost)을 지원되지 않는 모델 또는 데이터와 결합하는 경우 지원되는 모델을 직접 직렬화할 필요가 없습니다. 컨텍스트에서 지원되는 모델 오브젝트를 직접 설정하면(예: base_model = my_xgb_model) 자동으로 직렬화됩니다.
사용자 지정 모델 테스트 및 로그 기록하기¶
로컬에서 실행하여 사용자 지정 모델을 테스트할 수 있습니다.
my_model = ExampleBringYourOwnModel(model_context)
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,
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)
code_paths로 추가 코드 포함하기¶
Registry.log_model<https://docs.snowflake.com/developer-guide/snowpark-ml/reference/latest/api/registry/snowflake.ml.registry.Registry#snowflake.ml.registry.Registry.log_model>`_의 ``code_paths` 매개 변수를 사용하여 도우미 모듈, 유틸리티, 구성 파일과 같은 Python 코드를 모델과 함께 패키징합니다. 로컬에서와 마찬가지로 이 코드를 가져올 수 있습니다.
파일 또는 디렉터리를 복사하기 위한 문자열 경로 또는 CodePath 오브젝트를 제공할 수 있습니다. 오브젝트는 포함되는 하위 디렉터리 또는 파일과 모델에서 사용할 가져오기 경로에 대한 더 많은 제어 기능을 제공합니다.
문자열 경로 사용하기¶
파일 또는 디렉터리를 포함할 문자열 경로 목록을 전달합니다. 각 경로의 마지막 구성 요소는 가져올 수 있는 모듈 이름이 됩니다.
mv = reg.log_model(
my_model,
model_name="my_model",
version_name="v1",
code_paths=["src/mymodule"], # import with: import mymodule
)
필터로 CodePath 사용하기¶
디렉터리 트리의 일부만 패키징하거나 모델에서 사용하는 가져오기 경로를 제어하려는 경우 ~snowflake.ml.model.CodePath 클래스를 사용합니다.
from snowflake.ml.model import CodePath
``CodePath``에는 두 개의 매개 변수가 있습니다.
root: 디렉터리 또는 파일 경로입니다.filter``(선택 사항): 하위 디렉터리 또는 파일을 선택하는 ``root아래의 상대 경로입니다.
filter``가 제공되는 경우 소스는 ``root/filter``이며, ``filter 값에 따라 가져오기 경로가 결정됩니다. 예를 들어, ``filter=”utils”``를 사용하면 ``import utils``를 수행할 수 있고 ``filter=”pkg/subpkg”``를 사용하면 ``import pkg.subpkg``를 수행할 수 있습니다.
예제: 다음의 프로젝트 구조를 가정해 보겠습니다.
my_project/src/
├── utils/
│ └── preprocessing.py
├── models/
│ └── classifier.py
└── tests/ # Not needed for inference
tests/``를 제외한 ``utils/ 및 ``models/``만 패키징하려면 다음을 수행합니다.
mv = reg.log_model(
my_model,
model_name="my_model",
version_name="v1",
code_paths=[
CodePath("my_project/src/", filter="utils/"),
CodePath("my_project/src/", filter="models/"),
],
)
단일 파일을 필터링할 수도 있습니다.
code_paths=[
CodePath("my_project/src/", filter="utils/preprocessing.py"),
]
# Import with: import utils.preprocessing
예: PyCaret 모델 로깅하기¶
다음 예제에서는 PyCaret을 사용하여 사용자 지정 모델 유형을 기록합니다. PyCaret은 Snowflake가 기본적으로 지원하지 않는 로우 코드의 고효율 서드 파티 패키지입니다. 유사한 방법을 사용하여 고유한 모델 유형을 가져올 수 있습니다.
1단계: 모델 컨텍스트 정의하기¶
모델을 로깅하기 전에 모델 컨텍스트를 정의합니다. 모델 컨텍스트는 고유한 사용자 지정 모델 유형을 참조합니다. 다음 예제에서는 컨텍스트의 model_file 특성을 사용하여 직렬화된(피클된) 모델의 경로를 지정합니다. 이름이 다른 용도로 사용되지 않는 한 특성의 이름을 선택할 수 있습니다.
pycaret_model_context = 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_model_context)
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 » :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;