Keyboard shortcuts

Press ← or → to navigate between chapters

Press ? to show this help

Press Esc to hide this help

Code Repositories에서 모델 학습

프로젝트 준비 후 학습 및 추론을 재현 가능한 파이프라인으로 작성합니다. 빠른 대화형 실험은 Jupyter 경로를 사용할 수 있으며 여기서는 커밋된 코드의 빌드를 사용합니다.

저장소 생성

code 폴더에서 + New > Code repository를 선택합니다. 이름은 median_house_price_model_repo, Repository type은 Model Integration, Language template은 Model Training으로 정하고 Initialize repository를 선택합니다.

학습과 시험 데이터 분리

feature_engineering.py에 다음 변환을 작성합니다. <YOUR_PROJECT_PATH>를 실습 루트로 바꾸면 라벨 데이터를 seed 0으로 80% 학습 및 20% 시험 집합으로 나눕니다.

from transforms.api import transform, Input, Output


@transform.spark.using(
    features_and_labels_input=Input("<YOUR_PROJECT_PATH>/data/housing_features_and_labels"),
    training_output=Output("<YOUR_PROJECT_PATH>/data/housing_training_data"),
    testing_output=Output("<YOUR_PROJECT_PATH>/data/housing_test_data"),
)
def compute(features_and_labels_input, training_output, testing_output):
    # Converts this TransformInput to a PySpark DataFrame
    features_and_labels = features_and_labels_input.dataframe()

    # Randomly split the PySpark dataframe with 80% training data and 20% testing data
    training_data, testing_data = features_and_labels.randomSplit([0.8, 0.2], seed=0)

    # Write training and testing data back to Foundry
    training_output.write_dataframe(training_data)
    testing_output.write_dataframe(testing_data)

CBAC가 활성화된 환경에서는 변환이 없는 출력 리소스를 스스로 생성할 수 없습니다. 빌드 전에 data 폴더에 housing_training_data, housing_test_data, housing_testing_data_inferences 데이터셋을, models에 linear_regression_model을 + New로 만들고 필요한 파일 보안 분류를 설정합니다. 이후 코드는 기존 경로를 가리키게 합니다.

Build로 전체 변환을 실행하고 필요하면 Preview에서 일부 입력으로 먼저 확인합니다.

의존성과 어댑터

Libraries에서 scikit-learn, pandas와 dill을 추가하고 Commit하여 Python 환경을 해결합니다. 모델에는 해결된 의존성을 함께 패키징합니다.

model_adapters/adapter.py에 다음 어댑터를 둡니다. 저장 및 로드는 auto_serialize가 처리하고 api가 입력/출력 열을 정의하며 predict가 실제 모델 예측을 호출합니다.

import palantir_models as pm


class SklearnRegressionAdapter(pm.ModelAdapter):

    @pm.auto_serialize
    def __init__(self, model):
        self.model = model

    @classmethod
    def api(cls):
        columns = [
            ('median_income', float),
            ('housing_median_age', float),
            ('total_rooms', float),
        ]
        return {"df_in": pm.Pandas(columns)}, \
               {"df_out": pm.Pandas(columns + [('prediction', float)])}

    def predict(self, df_in):
        df_in['prediction'] = self.model.predict(
            df_in[['median_income', 'housing_median_age', 'total_rooms']]
        )
        return df_in

학습 로직

model_training/model_training.py에 결측값 중앙값 대체, 표준화와 선형 회귀를 학습하는 코드를 넣습니다. 입력과 모델 출력 경로를 맞추고 Build합니다.

from transforms.api import transform, Input
from palantir_models.transforms import ModelOutput
from main.model_adapters.adapter import SklearnRegressionAdapter


def train_model(training_df):
    from sklearn.impute import SimpleImputer
    from sklearn.linear_model import LinearRegression
    from sklearn.pipeline import Pipeline
    from sklearn.preprocessing import StandardScaler

    numeric_features = ['median_income', 'housing_median_age', 'total_rooms']
    numeric_transformer = Pipeline(
        steps=[
            ("imputer", SimpleImputer(strategy="median")),
            ("scaler", StandardScaler())
        ]
    )

    model = Pipeline(
        steps=[
            ("preprocessor", numeric_transformer),
            ("classifier", LinearRegression())
        ]
    )
    X_train = training_df[numeric_features]
    y_train = training_df['median_house_value']
    model.fit(X_train, y_train)

    return model

@transform.using(
    training_data_input=Input("<YOUR_PROJECT_PATH>/data/housing_training_data"),
    model_output=ModelOutput("<YOUR_PROJECT_PATH>/models/linear_regression_model"),
)
def compute(training_data_input, model_output):
    training_df = training_data_input.pandas()
    model = train_model(training_df)

    # Wrap the trained model in a ModelAdapter
    foundry_model = SklearnRegressionAdapter(model)

    # Publish and write the trained model to Foundry
    model_output.publish(
        model_adapter=foundry_model
    )

반복 개발 중에는 Preview로 입력 부분집합에 대한 동작을 볼 수 있습니다. 필요하면 실험 지표를 모델과 함께 기록합니다.

배치 추론

학습이 끝나면 model_training/run_inference.py에서 시험 데이터에 모델을 적용합니다. 단일 Pandas 입력을 선언한 어댑터는 변환 입력을 해당 형식으로 변환하여 transform에 제공합니다.

from transforms.api import transform, Input, Output, LightweightInput, LightweightOutput
from palantir_models.transforms import ModelInput
from palantir_models import ModelAdapter

@transform.using(
    testing_data_input=Input("<YOUR_PROJECT_PATH>/data/housing_test_data"),
    model_input=ModelInput("<YOUR_PROJECT_PATH>/models/linear_regression_model"),
    predictions_output=Output("<YOUR_PROJECT_PATH>/data/housing_testing_data_inferences")
)
def compute(
        testing_data_input: LightweightInput,
        model_input: ModelAdapter,
        predictions_output: LightweightOutput
    ):
    inference_outputs = model_input.transform(testing_data_input)
    predictions_output.write_pandas(inference_outputs.df_out)

다른 저장소에서 만든 모델을 소비하려면 ModelInput의 use_sidecar=True로 해당 어댑터와 의존성을 분리 환경에 로드할 수 있습니다. 경량 @transform.using에서 sidecar를 사용하려면 palantir_models 0.2010.0 이상이 필요합니다. sidecar를 쓰지 않으면 현재 저장소에 모델 어댑터 및 의존성이 있어야 합니다.

모델은 Pipeline Builder의 배치 및 스트리밍 경로 또는 직접 온라인 추론 배포에서도 사용할 수 있습니다.

모델 확인과 제출

코드의 linear_regression_model 링크나 models 폴더에서 모델을 엽니다.

모델 보기에는 학습 원천, 데이터, 모델 API와 어댑터가 나옵니다. 같은 모델에 여러 버전을 게시하고 사이드바 선택기로 볼 수 있습니다. 이 실습의 어댑터 수정은 모델을 다시 게시하는 빌드에 반영해야 기존 게시 버전과 구분됩니다.

Submit to a Modeling Objective에서 준비한 목표를 선택합니다. 제출 이름을 linear_regression_model로 정하고 소유자를 지정한 뒤 평가와 배포로 진행합니다.