

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

# Amazon SageMaker の推論パイプラインを使用して、前処理ロジックを単一エンドポイントの ML モデルにデプロイする
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker"></a>

*Mohan Gowda Purushothama、Gabriel Rodriguez Garcia、Mateusz Zaremba、Amazon Web Services*

## 概要
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker-summary"></a>

このパターンでは、Amazon SageMaker の[推論パイプライン](https://docs.aws.amazon.com/sagemaker/latest/dg/inference-pipelines.html)を使用して 1 つのエンドポイントに複数のパイプラインモデルオブジェクトをデプロイする方法を説明します。パイプラインモデルオブジェクトは、前処理、モデル推論、後処理など、さまざまな機械学習 (ML) ワークフローステージを表します。このパターンでは、シリアル接続されたパイプラインモデルオブジェクトのデプロイを説明するために、SageMaker に組み込まれている[線形学習アルゴリズム](https://docs.aws.amazon.com/sagemaker/latest/dg/linear-learner.html)に基づく前処理の [Scikit-learn](https://docs.aws.amazon.com/sagemaker/latest/dg/sklearn.html) コンテナとリグレッションモデルをデプロイする方法を示します。デプロイメントは SageMaker の単一のエンドポイントの背後でホストされます。

**注記**  
このパターンのデプロイメントは ml.m4.2xlarge インスタンスタイプを使用します。データサイズの要件とワークフローの複雑さに合ったインスタンスタイプを使用することをお勧めします。詳細については、「[Amazon SageMaker の料金](https://aws.amazon.com/sagemaker/pricing/)」を参照してください。このパターンでは [Scikit-Learn 用にビルド済みの Docker イメージ](https://docs.aws.amazon.com/sagemaker/latest/dg/pre-built-docker-containers-scikit-learn-spark.html)を使用しますが、独自の Docker コンテナを使用してワークフローに統合することもできます。

## 前提条件と制限事項
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker-prereqs"></a>

**前提条件**
+ アクティブな AWS アカウント
+ [Python 3.9](https://www.python.org/downloads/release/python-390/)
+ [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable/) と [Boto3 ライブラリ](https://boto3.amazonaws.com/v1/documentation/api/latest/index.html)
+ 基本的な SageMaker [権限](https://docs.aws.amazon.com/sagemaker/latest/dg/api-permissions-reference.html)と Amazon Simple Storage Service (Amazon S3) [権限](https://docs.aws.amazon.com/AmazonS3/latest/userguide/access-policy-language-overview.html)を持つ AWS Identity and Access Management (AWS IAM) [ロール](https://docs.aws.amazon.com/IAM/latest/UserGuide/id_roles.html)

**製品バージョン**
+ [Amazon SageMaker Python SDK 2.49.2](https://sagemaker.readthedocs.io/en/v2.49.2/)

## アーキテクチャ
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker-architecture"></a>

**ターゲットテクノロジースタック**
+ Amazon Elastic Container Registry (Amazon ECR)
+ Amazon SageMaker
+ Amazon SageMaker Studio
+ Amazon Simple Storage Service (Amazon S3)
+ Amazon SageMaker 用の[リアルタイム推論](https://docs.aws.amazon.com/sagemaker/latest/dg/realtime-endpoints.html)エンドポイント

**ターゲットアーキテクチャ**

次の図表は、Amazon SageMaker Pipelines モデルオブジェクトをデプロイするためのアーキテクチャを示します。

![\[SageMaker パイプラインモデルオブジェクトをデプロイするためのアーキテクチャ\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/images/pattern-img/1105d51b-752f-46d7-962c-acef1fb3399f/images/12f06715-b1c2-4de0-b277-99ce87308152.png)


この図表は、次のワークフローを示しています:

1. SageMaker ノートブックはパイプラインモデルをデプロイします。

1. S3 バケットにはモデルアーティファクトが格納されます。

1. Amazon ECR は S3 バケットからソースコンテナイメージを取得します。

## ツール
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker-tools"></a>

**AWS ツール**
+ [Amazon Elastic Container Registry (Amazon ECR)](https://docs.aws.amazon.com/AmazonECR/latest/userguide/what-is-ecr.html) は、セキュリティ、スケーラビリティ、信頼性を備えたマネージドコンテナイメージレジストリサービスです。
+ 「[Amazon SageMaker](https://docs.aws.amazon.com/sagemaker/latest/dg/whatis.html)」 は、ML モデルの構築とトレーニングを行うことができ、それらを稼働準備が整ったホストされている環境にデプロイするのに役立つマネージド型 ML サービスです。
+ [Amazon SageMaker Studio](https://docs.aws.amazon.com/sagemaker/latest/dg/studio.html) は、ML モデルの構築、トレーニング、デバッグ、デプロイ、モニタリングを可能にする、ウェブベースの ML 用統合開発環境 (IDE) です。
+ [Amazon Simple Storage Service (Amazon S3)](https://docs.aws.amazon.com/AmazonS3/latest/userguide/Welcome.html) は、あらゆる量のデータを保存、保護、取得できるクラウドベースのオブジェクトストレージサービスです。

**コード**

このパターンのコードは、GitHub 内の「[Inference Pipeline with Scikit-learn and Linear Learner](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker-python-sdk/scikit_learn_inference_pipeline/Inference%20Pipeline%20with%20Scikit-learn%20and%20Linear%20Learner.ipynb)」リポジトリで利用できます。

## エピック
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker-epics"></a>

### データセットの準備
<a name="prepare-the-dataset"></a>


| タスク | 説明 | 必要なスキル | 
| --- | --- | --- | 
| リグレッションタスク用のデータセットを準備します。 | Amazon SageMaker Studio で[ノートブックを開きます](https://docs.aws.amazon.com/sagemaker/latest/dg/notebooks-create-open.html#notebooks-open)。必要なライブラリをすべてインポートして作業環境を初期化するには、ノートブックで以下のサンプルコードを使用してください。<pre>import sagemaker<br />from sagemaker import get_execution_role<br /><br />sagemaker_session = sagemaker.Session()<br /><br /># Get a SageMaker-compatible role used by this Notebook Instance.<br />role = get_execution_role()<br /><br /># S3 prefix<br />bucket = sagemaker_session.default_bucket()<br />prefix = "Scikit-LinearLearner-pipeline-abalone-example"</pre>サンプルデータセットをダウンロードするには、以下のコードをノートブックに追加します。<pre>! mkdir abalone_data<br />! aws s3 cp s3://sagemaker-sample-files/datasets/tabular/uci_abalone/abalone.csv ./abalone_data</pre>** **このパターンの例では、UCI 機械学習のリポジトリの [Abalone データセット](https://archive.ics.uci.edu/ml/datasets/abalone)を使用しています。 | データサイエンティスト | 
| データセットを S3 バケットにアップロードします。 | 先にデータセットを準備したノートブックに、以下のコードを追加してサンプルデータを S3 バケットにアップロードします。<pre>WORK_DIRECTORY = "abalone_data"<br /><br />train_input = sagemaker_session.upload_data(<br />    path="{}/{}".format(WORK_DIRECTORY, "abalone.csv"),<br />    bucket=bucket,<br />    key_prefix="{}/{}".format(prefix, "train"),<br />)</pre> | データサイエンティスト | 

### SKLearn を使用してデータプリプロセッサを作成します。
<a name="create-the-data-preprocessor-using-sklearn"></a>


| タスク | 説明 | 必要なスキル | 
| --- | --- | --- | 
| preprocessor.py スクリプトを準備します。 | [\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/ja_jp/prescriptive-guidance/latest/patterns/deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker.html) | データサイエンティスト | 
| SKLearn プリプロセッサオブジェクトを作成します。 | 最終的な推論パイプラインに組み込むことができる SKLearn プリプロセッサオブジェクト (SKLearn Estimator と呼ばれる) を作成するには、SageMaker ノートブックで次のコードを実行します。<pre>from sagemaker.sklearn.estimator import SKLearn<br /><br />FRAMEWORK_VERSION = "0.23-1"<br />script_path = "sklearn_abalone_featurizer.py"<br /><br />sklearn_preprocessor = SKLearn(<br />    entry_point=script_path,<br />    role=role,<br />    framework_version=FRAMEWORK_VERSION,<br />    instance_type="ml.c4.xlarge",<br />    sagemaker_session=sagemaker_session,<br />)<br />sklearn_preprocessor.fit({"train": train_input})</pre> | データサイエンティスト | 
| プリプロセッサの推論をテストします。 | プリプロセッサが正しく定義されていることを確認するには、SageMaker ノートブックに次のコードを入力して[バッチ変換ジョブ](https://docs.aws.amazon.com/sagemaker/latest/dg/batch-transform.html)を起動します。<pre># Define a SKLearn Transformer from the trained SKLearn Estimator<br />transformer = sklearn_preprocessor.transformer(<br />    instance_count=1, instance_type="ml.m5.xlarge", assemble_with="Line", accept="text/csv"<br />)<br /><br /><br /># Preprocess training input<br />transformer.transform(train_input, content_type="text/csv")<br />print("Waiting for transform job: " + transformer.latest_transform_job.job_name)<br />transformer.wait()<br />preprocessed_train = transformer.output_path</pre> |  | 

### 機械学習モデルを作成する
<a name="create-a-machine-learning-model"></a>


| タスク | 説明 | 必要なスキル | 
| --- | --- | --- | 
| モデルオブジェクトを作成します。 | 線形学習器アルゴリズムに基づいてモデルオブジェクトを作成するには、SageMaker ノートブックに次のコードを入力します。<pre>import boto3<br />from sagemaker.image_uris import retrieve<br /><br />ll_image = retrieve("linear-learner", boto3.Session().region_name)<br />s3_ll_output_key_prefix = "ll_training_output"<br />s3_ll_output_location = "s3://{}/{}/{}/{}".format(<br />    bucket, prefix, s3_ll_output_key_prefix, "ll_model"<br />)<br /><br />ll_estimator = sagemaker.estimator.Estimator(<br />    ll_image,<br />    role,<br />    instance_count=1,<br />    instance_type="ml.m4.2xlarge",<br />    volume_size=20,<br />    max_run=3600,<br />    input_mode="File",<br />    output_path=s3_ll_output_location,<br />    sagemaker_session=sagemaker_session,<br />)<br /><br />ll_estimator.set_hyperparameters(feature_dim=10, predictor_type="regressor", mini_batch_size=32)<br /><br />ll_train_data = sagemaker.inputs.TrainingInput(<br />    preprocessed_train,<br />    distribution="FullyReplicated",<br />    content_type="text/csv",<br />    s3_data_type="S3Prefix",<br />)<br /><br />data_channels = {"train": ll_train_data}<br />ll_estimator.fit(inputs=data_channels, logs=True)</pre>上記のコードでは、パブリック Amazon ECR レジストリからモデルの関連する Amazon ECR Docker イメージを取得し、推定オブジェクトを作成し、そのオブジェクトを使用してリグレッションモデルをトレーニングします。 | データサイエンティスト | 

### 最後のパイプラインをデプロイする
<a name="deploy-the-final-pipeline"></a>


| タスク | 説明 | 必要なスキル | 
| --- | --- | --- | 
| パイプラインモデルをデプロイします。 | パイプラインモデルオブジェクト (つまり、プリプロセッサオブジェクト) を作成してオブジェクトをデプロイするには、SageMaker ノートブックに次のコードを入力します。<pre>from sagemaker.model import Model<br />from sagemaker.pipeline import PipelineModel<br />import boto3<br />from time import gmtime, strftime<br /><br />timestamp_prefix = strftime("%Y-%m-%d-%H-%M-%S", gmtime())<br /><br />scikit_learn_inferencee_model = sklearn_preprocessor.create_model()<br />linear_learner_model = ll_estimator.create_model()<br /><br />model_name = "inference-pipeline-" + timestamp_prefix<br />endpoint_name = "inference-pipeline-ep-" + timestamp_prefix<br />sm_model = PipelineModel(<br />    name=model_name, role=role, models= [scikit_learn_inferencee_model, linear_learner_model]<br />)<br /><br />sm_model.deploy(initial_instance_count=1, instance_type="ml.c4.xlarge", endpoint_name=endpoint_name)</pre>モデルオブジェクトで使用されるインスタンスタイプは、必要に応じて調整できます。 | データサイエンティスト | 
| 推論をテストします。 | エンドポイントが正しく動作していることを確認するには、SageMaker ノートブックで以下のサンプル推論コードを実行します。<pre>from sagemaker.predictor import Predictor<br />from sagemaker.serializers import CSVSerializer<br /><br />payload = "M, 0.44, 0.365, 0.125, 0.516, 0.2155, 0.114, 0.155"<br />actual_rings = 10<br />predictor = Predictor(<br />    endpoint_name=endpoint_name, sagemaker_session=sagemaker_session, serializer=CSVSerializer()<br />)<br /><br />print(predictor.predict(payload))</pre> | データサイエンティスト | 

## 関連リソース
<a name="deploy-preprocessing-logic-into-an-ml-model-in-a-single-endpoint-using-an-inference-pipeline-in-amazon-sagemaker-resources"></a>
+ [Preprocess input data before making predictions using Amazon SageMaker inference pipelines and Scikit-learn](https://aws.amazon.com/blogs/machine-learning/preprocess-input-data-before-making-predictions-using-amazon-sagemaker-inference-pipelines-and-scikit-learn/) (AWS 機械学習のブログ)
+ [End to end Machine Learning with Amazon SageMaker](https://github.com/aws-samples/amazon-sagemaker-build-train-deploy) (GitHub)