本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
從即時端點擷取資料
為了避免對推論要求造成影響,資料擷取會停止擷取需要高磁碟使用量的要求。建議您將磁碟使用率保持在 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 啟用資料擷取。
- AWS SDK for Python (Boto)
-
使用 CreateEndpointConfig
方法建立端點時,使用 DataCaptureConfig 字典來設定要擷取的資料。設定 EnableCapture
為布林值 True。此外,提供下列必要參數:
-
EndpointConfigName
:端點組態的名稱。當您提出 CreateEndpoint
要求時,將使用此名稱。
-
ProductionVariants
:您希望在此端點上託管的模型清單。定義每個模型的字典資料類型。
-
DataCaptureConfig
:字典資料類型,您可以在其中指定與範例 (InitialSamplingPercentage
) 資料初始百分比對應的整數值、要存放擷取資料的 Amazon S3 URI,以及擷取選項 (CaptureOptions
) 清單。在 CaptureOptions
清單中指定 CaptureMode
的 Input
或 Output
。
您可以選擇性地指定 SageMaker AI 如何透過將鍵/值對引數傳遞到CaptureContentTypeHeader
字典來編碼擷取的資料。
# 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 Service API 參考指南》中的 CreateEndpointConfig API。 Amazon SageMaker
- SageMaker Python SDK
-
從 sagemaker.model_monitor 模組匯入 DataCaptureConfig
類別。透過將 EnableCapture
布林值設定為 True
以啟用資料擷取。
選擇性地提供下列參數的引數:
-
SamplingPercentage
:對應於要取樣的資料百分比的整數值。如果您未提供抽樣百分比,SageMaker AI 將抽樣預設 20 (20%) 的資料。
-
DestinationS3Uri
:Amazon S3 URI SageMaker AI 將使用 來存放擷取的資料。如果您不提供,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) 運算執行個體,接著進行模型部署。
取得模型和端點組態後,請使用 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 端點。提供要在 instance_type
現場部署這個模型的 Amazon EC2 執行個體類型名稱,以及為 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 SDKPredictor 類別建立預測器物件。您將使用 Predictor
類別傳回的物件,在未來的步驟中調用端點。提供端點的名稱 (先前定義為 endpoint_name
),以及序列化程式和還原序列化程式分別對應的序列化程式物件和還原序列化程式物件。如需序列化器類型的相關資訊,請參閱 SageMaker AI Python SDK 中的序列化器類別。
from sagemaker.predictor import Predictor
from sagemaker.serializers import <Serializer>
from sagemaker.deserializers import <Deserializers>
predictor = Predictor(endpoint_name=endpoint_name,
serializer = <Serializer_Class>
,
deserializer = <Deserializer_Class>
)
# Example
#from sagemaker.predictor import Predictor
#from sagemaker.serializers import CSVSerializer
#from sagemaker.deserializers import JSONDeserializer
#predictor = Predictor(endpoint_name=endpoint_name,
# serializer=CSVSerializer(),
# deserializer=JSONDeserializer())
在接下來的程式碼範例情境中,我們調用我們已本機儲存在名為 validation_with_predictions
的 CSV 檔案中的範例驗證資料的端點。我們的範例驗證集包含每個輸入的標籤。
with 陳述式的前幾行會先開啟驗證集 CSV 檔案,然後以逗號字元 ","
分割檔案中的每一列,然後將兩個傳回的物件儲存到標籤和 input_cols 變數中。對於每一列,輸入 (input_cols
) 會傳遞到預測變量的 (predictor
) 物件內建方法 Predictor.predict()
。
假設模型返回機率。機率範圍介於 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(predictor.predict(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
。
預期會看到來自不同時段的不同檔案 (根據調用的時間編排)。執行以下命令以列印出單一擷取檔案的內容:
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
物件為清單類型。索引清單中的第一個元素,以檢視單一推論要求。
# 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"
}