翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。
リアルタイムエンドポイントからデータをキャプチャする
Amazon SageMaker Model Monitor は新規顧客に公開されなくなりました。既存のお客様は、引き続き通常どおりサービスを使用できます。 は Model Monitor のセキュリティと可用性の向上に AWS 引き続き投資しますが、新機能を導入する予定はありません。詳細については、「Amazon SageMaker Model Monitor の可用性の変更」を参照してください。
推論リクエストへの影響を防ぐため、ディスク使用率のレベルが高くなると、データキャプチャはリクエストのキャプチャを停止します。データキャプチャがリクエストのキャプチャを続行できるように、ディスク使用率を 75% 未満に抑えることをお勧めします。
リアルタイムエンドポイントのデータをキャプチャするには、SageMaker AI ホスティングサービスを使用してモデルをデプロイする必要があります。これには、SageMaker AI モデルを作成し、エンドポイント設定を定義して、HTTPS エンドポイントを作成する必要があります。
データキャプチャを有効にするために必要な手順は、 AWS SDK for Python (Boto) と SageMaker Python SDK のどちらを使用する場合でも同様です。 AWS SDK を使用する場合は、CreateEndpointConfig メソッド内で DataCaptureConfig ディクショナリと必須フィールドを定義して、データキャプチャを有効にします。SageMaker Python SDK を使用する場合は、DataCaptureConfig クラスをインポートし、このクラスからインスタンスを初期化します。次に、このオブジェクトを sagemaker.model.Model.deploy() メソッドの DataCaptureConfig パラメータに渡します。
上のコードスニペットを使用するには、コード例のイタリック体のプレースホルダーテキストを独自の情報に置き換えます。
データキャプチャを有効にする方法
データキャプチャ設定を指定します。この設定では、要求ペイロード、応答ペイロード、またはその両方をキャプチャできます。前述のコードスニペットは、 AWS SDK for Python (Boto) と SageMaker AI Python SDK を使用してデータキャプチャを有効にする方法を示しています。
Model Monitor を使用してリクエストまたはレスポンスペイロードをキャプチャする必要はありません。
- AWS SDK for Python (Boto)
-
CreateEndpointConfig メソッドを使用してエンドポイントを作成するときに、DataCaptureConfig ディクショナリでキャプチャするデータを設定します。EnableCapture をブール値 True に設定します。また、以下の必須パラメータを指定します。
-
EndpointConfigName: エンドポイント設定の名前。この名前は、CreateEndpoint リクエストを行うときに使用します。
-
ProductionVariants: このエンドポイントでホストするモデルのリスト。モデルごとにディクショナリデータ型を定義します。
-
DataCaptureConfig: サンプリングするデータの初期パーセンテージ (InitialSamplingPercentage) に対応する整数値、キャプチャしたデータを保存する Amazon S3 URI、キャプチャオプション (CaptureOptions) リストを指定するディクショナリデータ型。CaptureOptions リスト内の CaptureMode に Input または Output のいずれかを指定します。
key-value ペアの引数を CaptureContentTypeHeader ディクショナリに渡すことで、SageMaker AI がキャプチャしたデータをどのようにエンコードするかを任意で指定できます。
# Create an endpoint config name.
endpoint_config_name = '<endpoint-config-name>'
# The name of the production variant.
variant_name = '<name-of-production-variant>'
# The name of the model that you want to host.
# This is the name that you specified when creating the model.
model_name = '<The_name_of_your_model>'
instance_type = '<instance-type>'
#instance_type='ml.m5.xlarge' # Example
# Number of instances to launch initially.
initial_instance_count = <integer>
# Sampling percentage. Choose an integer value between 0 and 100
initial_sampling_percentage = <integer>
# The S3 URI containing the captured data
s3_capture_upload_path = 's3://<bucket-name>/<data_capture_s3_key>'
# Specify either Input, Output, or both
capture_modes = [ "Input", "Output" ]
#capture_mode = [ "Input"] # Example - If you want to capture input only
endpoint_config_response = sagemaker_client.create_endpoint_config(
EndpointConfigName=endpoint_config_name,
# List of ProductionVariant objects, one for each model that you want to host at this endpoint.
ProductionVariants=[
{
"VariantName": variant_name,
"ModelName": model_name,
"InstanceType": instance_type, # Specify the compute instance type.
"InitialInstanceCount": initial_instance_count # Number of instances to launch initially.
}
],
DataCaptureConfig= {
'EnableCapture': True, # Whether data should be captured or not.
'InitialSamplingPercentage' : initial_sampling_percentage,
'DestinationS3Uri': s3_capture_upload_path,
'CaptureOptions': [{"CaptureMode" : capture_mode} for capture_mode in capture_modes] # Example - Use list comprehension to capture both Input and Output
}
)
その他のエンドポイント設定オプションの詳細については、「Amazon SageMaker AI サービス API リファレンスガイド」の「CreateEndpointConfig」API を参照してください。
- SageMaker Python SDK
-
sagemaker.model_monitor モジュールから DataCaptureConfig クラスをインポートします。 EnableCapture ブール値 True に設定してデータキャプチャを有効にします。
オプションで、以下のパラメータに引数を指定します。
-
SamplingPercentage: サンプリングするデータのパーセンテージに対応する整数値。サンプリング率を指定しない場合、SageMaker AI はデフォルトで 20 (20%) のデータをサンプリングします。
-
DestinationS3Uri: SageMaker AI がキャプチャしたデータを保存するために使用する Amazon S3 URI。指定しない場合、SageMaker AI はキャプチャしたデータを "s3://<default-session-bucket>/
model-monitor/data-capture" に保存します。
from sagemaker.model_monitor import DataCaptureConfig
# Set to True to enable data capture
enable_capture = True
# Optional - Sampling percentage. Choose an integer value between 0 and 100
sampling_percentage = <int>
# sampling_percentage = 30 # Example 30%
# Optional - The S3 URI of stored captured-data location
s3_capture_upload_path = 's3://<bucket-name>/<data_capture_s3_key>'
# Specify either Input, Output or both.
capture_modes = ['REQUEST','RESPONSE'] # In this example, we specify both
# capture_mode = ['REQUEST'] # Example - If you want to only capture input.
# Configuration object passed in when deploying Models to SM endpoints
data_capture_config = DataCaptureConfig(
enable_capture = enable_capture,
sampling_percentage = sampling_percentage, # Optional
destination_s3_uri = s3_capture_upload_path, # Optional
capture_options = ["REQUEST", "RESPONSE"],
)
モデルをデプロイする
モデルをデプロイし、DataCapture を有効にして HTTPS エンドポイントを作成します。
- AWS SDK for Python (Boto3)
-
SageMaker AI にエンドポイント設定を提供します。このサービスは、ML コンピューティングインスタンスを起動し、設定で指定された 1 つ以上のモデルをデプロイします。
モデルとエンドポイントの設定が完了したら、CreateEndpoint API を使用してエンドポイントを作成します。エンドポイント名は、 AWS アカウントの AWS リージョン内で一意である必要があります。
次が、リクエストで指定されたエンドポイント設定を使用してエンドポイントを作成します。Amazon SageMaker AI は、エンドポイントを使用してリソースをプロビジョンし、モデルをデプロイします。
# The name of the endpoint. The name must be unique within an AWS Region in your AWS account.
endpoint_name = '<endpoint-name>'
# The name of the endpoint configuration associated with this endpoint.
endpoint_config_name='<endpoint-config-name>'
create_endpoint_response = sagemaker_client.create_endpoint(
EndpointName=endpoint_name,
EndpointConfigName=endpoint_config_name)
詳細については、CreateEndpoint API を参照してください。
- SageMaker Python SDK
-
エンドポイントの名前を定義します。この手順は省略可能です。指定しない場合、SageMaker AI は一意の名前を作成します。
from datetime import datetime
endpoint_name = f"DEMO-{datetime.utcnow():%Y-%m-%d-%H%M}"
print("EndpointName =", endpoint_name)
Model オブジェクトの組み込みdeploy()メソッドを使用して、モデルをリアルタイムの HTTPS エンドポイントにデプロイします。このモデルをデプロイする Amazon EC2 インスタンスタイプの名前を instance_type フィールドに、エンドポイントを実行するインスタンスの初期数を initial_instance_count フィールドに指定します。
initial_instance_count=<integer>
# initial_instance_count=1 # Example
instance_type='<instance-type>'
# instance_type='ml.m4.xlarge' # Example
# Uncomment if you did not define this variable in the previous step
#data_capture_config = <name-of-data-capture-configuration>
model.deploy(
initial_instance_count=initial_instance_count,
instance_type=instance_type,
endpoint_name=endpoint_name,
data_capture_config=data_capture_config
)
キャプチャしたデータを表示する
SageMaker Python SDK からEndpointオブジェクトを作成します。Endpoint オブジェクトを使用して、今後のステップでエンドポイントを呼び出します。エンドポイントの名前を指定します (前に として定義)endpoint_name。
from sagemaker.core.resources import Endpoint
endpoint = Endpoint(endpoint_name=endpoint_name)
# Example
#from sagemaker.core.resources import Endpoint
#endpoint = Endpoint(endpoint_name=endpoint_name)
このコード例のシナリオでは、validation_with_predictions という名前の CSV ファイルにローカルに保存したサンプル検証データを使用してエンドポイントを呼び出します。サンプル検証セットには、各入力のラベルが含まれています。
with ステートメントの最初の数行では、まず検証セットの CSV ファイルを開き、次にファイル内の各行をカンマ文字 "," で分割し、返された 2 つのオブジェクトを label 変数と input_cols 変数に格納します。行ごとに、入力 (input_cols) がエンドポイント変数の (endpoint) 組み込みメソッド に渡されますinvoke()。
モデルが確率を返すと仮定します。確率の範囲は 0 から 1.0 までの整数値です。モデルから返される確率が 80% (0.8) を超える場合は、予測に 1 の整数値ラベルを割り当てます。それ以外の場合は、予測に 0 の整数値ラベルを割り当てます。
from time import sleep
validate_dataset = "validation_with_predictions.csv"
# Cut off threshold of 80%
cutoff = 0.8
limit = 200 # Need at least 200 samples to compute standard deviations
i = 0
with open(f"test_data/{validate_dataset}", "w") as validation_file:
validation_file.write("probability,prediction,label\n") # CSV header
with open("test_data/validation.csv", "r") as f:
for row in f:
(label, input_cols) = row.split(",", 1)
probability = float(endpoint.invoke(input_cols))
prediction = "1" if probability > cutoff else "0"
baseline_file.write(f"{probability},{prediction},{label}\n")
i += 1
if i > limit:
break
print(".", end="", flush=True)
sleep(0.5)
print()
print("Done!")
前のステップでデータキャプチャを有効にしたことにより、要求ペイロードと応答ペイロードは、追加のメタデータと共に、DataCaptureConfig で指定した Amazon S3 の場所に保存されます。キャプチャデータの Amazon S3 への配信には数分かかる場合があります。
Amazon S3 に保存されたデータキャプチャファイルを一覧表示して、キャプチャされたデータを表示します。Amazon S3 のパス形式は次のとおりです。s3:///{endpoint-name}/{variant-name}/yyyy/mm/dd/hh/filename.jsonl
呼び出しが発生した時間に基づいて編成された、異なる期間の異なるファイルが表示されます。以下を実行して 1 つのキャプチャファイルの内容を出力します。
print("\n".join(capture_file[-3:-1]))
これにより、SageMaker AI 固有の JSON 行形式のファイルが返されます。以下は、csv/text データを使用して呼び出したリアルタイムエンドポイントから取得した応答サンプルです。
{"captureData":{"endpointInput":{"observedContentType":"text/csv","mode":"INPUT",
"data":"69,0,153.7,109,194.0,105,256.1,114,14.1,6,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0\n",
"encoding":"CSV"},"endpointOutput":{"observedContentType":"text/csv; charset=utf-8","mode":"OUTPUT","data":"0.0254181120544672","encoding":"CSV"}},
"eventMetadata":{"eventId":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","inferenceTime":"2022-02-14T17:25:49Z"},"eventVersion":"0"}
{"captureData":{"endpointInput":{"observedContentType":"text/csv","mode":"INPUT",
"data":"94,23,197.1,125,214.5,136,282.2,103,9.5,5,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,0,1\n",
"encoding":"CSV"},"endpointOutput":{"observedContentType":"text/csv; charset=utf-8","mode":"OUTPUT","data":"0.07675473392009735","encoding":"CSV"}},
"eventMetadata":{"eventId":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","inferenceTime":"2022-02-14T17:25:49Z"},"eventVersion":"0"}
上の例では、capture_file オブジェクトはリストタイプです。リストの最初の要素にインデックスを付けると、1 つの推論リクエストが表示されます。
# The capture_file object is a list. Index the first element to view a single inference request
print(json.dumps(json.loads(capture_file[0]), indent=2))
これにより次のような応答が返されます。返される値は、エンドポイント設定、SageMaker AI モデル、キャプチャされたデータによって異なります。
{
"captureData": {
"endpointInput": {
"observedContentType": "text/csv", # data MIME type
"mode": "INPUT",
"data": "50,0,188.9,94,203.9,104,151.8,124,11.6,8,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,1,0\n",
"encoding": "CSV"
},
"endpointOutput": {
"observedContentType": "text/csv; charset=character-encoding",
"mode": "OUTPUT",
"data": "0.023190177977085114",
"encoding": "CSV"
}
},
"eventMetadata": {
"eventId": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
"inferenceTime": "2022-02-14T17:25:06Z"
},
"eventVersion": "0"
}