

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 從即時端點擷取資料
<a name="model-monitor-data-capture-endpoint"></a>

**注意**  
為了避免對推論要求造成影響，資料擷取會停止擷取需要高磁碟使用量的要求。建議您將磁碟使用率保持在 75% 以下，以確保資料擷取持續擷取要求。

若要擷取即時端點的資料，您必須使用 SageMaker AI 託管服務來部署模型。這需要您建立 SageMaker AI 模型、定義端點組態，以及建立 HTTPS 端點。

無論您使用 適用於 Python (Boto) 的 AWS SDK 或 SageMaker Python SDK，開啟資料擷取所需的步驟都類似。如果您使用 AWS SDK，請在 [CreateEndpointConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html) 方法中定義 [DataCaptureConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataCaptureConfig.html) 字典以及必要欄位，以開啟資料擷取。如果您使用 SageMaker Python SDK，請匯入 [DataCaptureConfig](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html#sagemaker.model_monitor.data_capture_config.DataCaptureConfig) 類別，並從此類別初始化執行個體。然後，將此物件傳遞給 `sagemaker.model.Model.deploy()` 方法中的 `DataCaptureConfig` 參數。

如果要使用接下來的程式碼片段，請用您的資訊取代範例程式碼中的*斜體預留位置文字*。

## 如何啟用資料擷取
<a name="model-monitor-data-capture-defing.title"></a>

指定資料擷取組態。您可以使用此組態擷取請求承載、回應承載或兩者。程序程式碼片段示範如何使用 適用於 Python (Boto) 的 AWS SDK 和 SageMaker AI Python SDK 啟用資料擷取。

**注意**  
您不需要使用模型監控來擷取要求或回應承載。

------
#### [ 適用於 Python (Boto) 的 AWS SDK ]

使用 `CreateEndpointConfig` 方法建立端點時，使用 [DataCaptureConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataCaptureConfig.html) 字典來設定要擷取的資料。設定 `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 服務 API 參考指南](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_Operations_Amazon_SageMaker_Service.html)中的 [CreateEndpointConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html) API。

------
#### [ SageMaker Python SDK ]

從 [sagemaker.model\$1monitor](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html) 模組匯入 `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"],
)
```

------

## 部署模型
<a name="model-monitor-data-capture-deploy"></a>

在啟用 `DataCapture` 的情況下部署模型並建立 HTTPS 端點。

------
#### [ 適用於 Python (Boto3) 的 AWS SDK ]

將端點組態提供給 SageMaker AI。此服務便會啟動組態所指定的機器學習 (ML) 運算執行個體，接著進行模型部署。

取得模型和端點組態後，請使用 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpoint.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpoint.html) 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)
```

如需詳細資訊，請參閱 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpoint.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpoint.html) 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
)
```

------

## 檢視擷取的資料
<a name="model-monitor-data-capture-view"></a>

從 SageMaker Python SDK[Predictor](https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html) 類別建立預測器物件。您將使用 `Predictor` 類別傳回的物件，在未來的步驟中調用端點。提供端點的名稱 (先前定義為 `endpoint_name`)，以及序列化程式和還原序列化程式分別對應的序列化程式物件和還原序列化程式物件。如需序列化程式類型的詳細資訊，請參閱 [SageMaker AI Python SDK](https://sagemaker.readthedocs.io/en/stable/index.html) 中的 [Serializers](https://sagemaker.readthedocs.io/en/stable/api/inference/serializers.html) 類別。

```
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\$1cols 變數中。對於每一列，輸入 (`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"
}
```