모델로 전처리 및 후처리하기¶
이 항목에서는 여러 모델 유형과 시나리오를 예로 들어 모델을 생성하고, 이를 Snowflake Model Registry에 기록하고, 배포하는 방법을 설명합니다. 다음과 같은 오브젝트가 이에 해당합니다.
인메모리 scikit-learn 모델 및 파이프라인.
자체 사용자 지정 모델.
두 개 이상의 모델.
인메모리 scikit-learn 모델 및 파이프라인¶
Snowflake ML 은 ModelContext
클래스와 함께 키워드 인자를 사용하여 인메모리 scikit-learn
모델을 Model Registry에 원활하게 통합할 수 있습니다. 아래는 인메모리 scikit-learn
모델을 키워드 인자로 모델 컨텍스트에 전달하고 사용자 지정 모델 클래스에서 호출하는 예입니다.
from sklearn import datasets, svm
import pandas as pd
from snowflake.ml.model import custom_model
# Step 1: Import the Iris dataset
iris_X, iris_y = datasets.load_iris(return_X_y=True)
# Step 2: Initialize a scikit-learn LinearSVC model and train it
svc = svm.LinearSVC()
svc.fit(iris_X, iris_y)
# Step 3: Initialize ModelContext with keyword arguments
mc = custom_model.ModelContext(
my_model=svc,
)
# Step 4: Define a custom model class to utilize the context
class ExampleSklearnModel(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 from the context for predictions
model_output = self.context['my_model'].predict(input)
# Return the predictions in a DataFrame
return pd.DataFrame({'output': model_output})
scikit-learn
파이프라인을 Snowflake ML과 함께 사용하기¶
아래는 Snowflake ML 내에서 scikit-learn 파이프라인을 사용하는 방법을 보여주는 예입니다. 여기에는 스케일링 또는 결측값 대체와 같은 전처리 단계와 예측 모델이 포함되며, 모두 ModelContext
를 사용하여 사용자 지정 모델 클래스 내에서 관리됩니다.
from sklearn import datasets
from sklearn.svm import SVC
from sklearn.pipeline import Pipeline
from sklearn.preprocessing import StandardScaler
from sklearn.impute import SimpleImputer
import pandas as pd
from snowflake.ml.model import custom_model
# Step 1: Load the Iris dataset
iris_X, iris_y = datasets.load_iris(return_X_y=True)
# Step 2: Create a scikit-learn pipeline
# The pipeline includes:
# - A SimpleImputer to handle missing values
# - A StandardScaler to standardize the data
# - A Support Vector Classifier (SVC) for predictions
pipeline = Pipeline([
('imputer', SimpleImputer(strategy='mean')),
('scaler', StandardScaler()),
('classifier', SVC(kernel='linear', probability=True))
])
# Step 3: Fit the pipeline to the dataset
pipeline.fit(iris_X, iris_y)
# Step 4: Initialize ModelContext with the pipeline
mc = custom_model.ModelContext(
pipeline_model=pipeline,
)
# Step 5: Define a custom model class to utilize the pipeline
class ExamplePipelineModel(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 pipeline from the context to process input and make predictions
predictions = self.context['pipeline_model'].predict(input)
probabilities = self.context['pipeline_model'].predict_proba(input)
# Return predictions and probabilities as a DataFrame
return pd.DataFrame({
'predictions': predictions,
'probability_class_0': probabilities[:, 0],
'probability_class_1': probabilities[:, 1]
})
# Example usage:
# Convert new input data into a DataFrame
new_input = pd.DataFrame(iris_X[:5]) # Using the first 5 samples for demonstration
# Initialize the custom model and run predictions
custom_pipeline_model = ExamplePipelineModel(context=mc)
result = custom_pipeline_model.predict(new_input)
print(result)
자체 모델 사용하기¶
다음 예에서는 자체 모델을 사용자 지정 모델로 사용합니다.
mc = custom_model.ModelContext(
my_model=your_own_model,
)
from snowflake.ml.model import custom_model
import pandas as pd
import json
class ExampleYourOwnModel(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:
model_output = self.context['my_model'].predict(features)
return pd.DataFrame({'output': model_output})
두 개 이상의 모델 사용하기¶
아래는 여러 모델을 결합하고 구성 파일을 사용하여 예측을 생성할 때 편향을 적용하는 사용자 지정 모델입니다.
mc = custom_model.ModelContext(
model1=model1,
model2=model2,
feature_preproc=preproc
}
)
참고
model1
및 model2
는 레지스트리에서 기본적으로 지원하는 모든 유형의 모델 오브젝트입니다. feature_preproc
는 scikit-learn pipeline
오브젝트입니다.
from snowflake.ml.model import custom_model
import pandas as pd
import json
class ExamplePipelineModel(custom_model.CustomModel):
@custom_model.inference_api
def predict(self, input: pd.DataFrame) -> pd.DataFrame:
...
return pd.DataFrame(...)
# Here is the fully-functional custom model that uses both model1 and model2
class ExamplePipelineModel(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:
features = self.context['feature_preproc'].transform(input)
model_output = self.context['model1'].predict(
self.context['model2'].predict(features)
)
return pd.DataFrame({'output': model_output})