Keyboard shortcuts

Press ← or → to navigate between chapters

Press ? to show this help

Press Esc to hide this help

Jupyter에서 모델 학습과 게시

Jupyter Code Workspace에서 데이터를 읽고 모델을 학습한 뒤 어댑터로 게시할 수 있습니다. 작업 공간은 단일 노드에서 실행하므로 PyTorch, TensorFlow, XGBoost, LightGBM 또는 scikit-learn 같은 단일 노드 프레임워크를 권장합니다. Spark ML 학습은 Code Repositories의 Spark 경로를 사용합니다.

작업 공간 생성

프로젝트의 + New > Jupyter Code Workspace 또는 Code Workspaces 앱의 + New code workspace로 시작합니다. 작업 공간 종류를 JupyterLab으로 선택하고 Continue를 누릅니다. 모델에 맞는 이름을 지정합니다. Code Repository 단계의 Advanced에서 연산 자원과 네트워크 정책을 추가로 정할 수 있습니다. Continue 후 Create로 작업 공간을 시작합니다.

데이터와 패키지

새 노트북을 만들고 Data > Add dataset > Read existing datasets에서 학습 데이터셋을 선택합니다. 읽기 쉬운 별칭을 지정한 뒤 + Add dataset으로 추가합니다. Step 2에서 pandas DataFrame 같은 형식을 선택하고 생성한 코드를 복사한 뒤 Done을 선택합니다.

Launcher의 Python [user-default]로 노트북을 열어 코드를 붙이고 실행 버튼 또는 Run > Run Selected Cells로 읽습니다. my-alias는 실제 데이터셋 별칭입니다.

from foundry.transforms import Dataset

training_data = Dataset.get("my-alias").read_table(format="pandas")

Packages에서 Conda 또는 PyPi를 선택하여 필요한 패키지를 검색하고 Latest 또는 특정 버전 버튼으로 설치 명령을 실행할 터미널을 엽니다. scikit-learn을 설치한 뒤 아래 학습 코드를 사용할 수 있습니다.

여러 패키지는 관리 환경의 터미널에서 maestro env conda install 또는 maestro env pip install로 추가할 수 있습니다.

학습 코드

아래는 median_income, housing_median_age와 total_rooms로 median_house_value를 예측하는 선형 회귀입니다. 입력 training_data에는 해당 특성과 정답 열이 있어야 합니다. 결측값은 중앙값으로 대체하고 특성을 표준화합니다.

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_data[numeric_features]
y_train = training_data['median_house_value']
model.fit(X_train, y_train)

모델 출력과 어댑터

Models > Add model > Create new model에서 모델 이름과 저장 위치를 정합니다.

Publish a new model 패널의 Step 1에서 palantir_models 설치 코드를 복사하여 노트북에서 실행합니다. Step 2에서는 별도 .py 파일에 어댑터를 작성합니다. 어댑터를 노트북 셀에 직접 정의하지 않습니다. 아래 예제는 linear_regression_model_adapter.py에 저장합니다.

어댑터는 저장 및 로드, 입력/출력 API와 예측 로직을 제공합니다. auto_serialize가 저장과 로드를 처리하며 복잡한 형식은 직접 구현할 수 있습니다.

import palantir_models as pm
from palantir_models.serializers import DillSerializer

class LinearRegressionModelAdapter(pm.ModelAdapter):

    @pm.auto_serialize(
        model=DillSerializer()
    )
    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

학습 중 하이퍼파라미터와 지표는 선택적으로 Experiment에 기록하여 모델과 함께 게시할 수 있습니다.

모델 게시

Step 3: Publish your model의 코드를 노트북에서 실행합니다. 아래 linear_regression_model은 Models에 등록한 모델 별칭이며 앞에서 실제로 학습한 model을 어댑터에 전달합니다.

from palantir_models.code_workspaces import ModelOutput

# Model adapter has been defined in linear_regression_model_adapter.py
from linear_regression_model_adapter import LinearRegressionModelAdapter

# model is the fitted pipeline from the training cell
linear_regression_model_adapter = LinearRegressionModelAdapter(model)

# "linear_regression_model" is the alias for this example model
model_output = ModelOutput("linear_regression_model")
model_output.publish(linear_regression_model_adapter)

게시하면 Foundry가 어댑터, 환경과 모델 API를 사용하여 다른 앱에서 모델을 로드하고 실행할 수 있습니다.

소비 경로

Modeling Objective에 제출하면 자동 평가, 배치 파이프라인과 온라인 호스팅에 사용할 수 있습니다. 목표와 별도로 직접 모델 배포를 생성하는 경로도 있습니다. 배포 실습에서 릴리스와 운영 추론을 연결합니다.