

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

# 使用 Amazon SageMaker Model Monitor 進行資料和模型品質監控
<a name="model-monitor"></a>

Amazon SageMaker Model Monitor 會監控生產中 Amazon SageMaker AI 機器學習模型的品質。使用 Model Monitor，您可以設定：
+ 使用即時端點進行持續監控。
+ 使用定期執行的批次轉換任務進行持續監控。
+ 針對非同步批次轉換任務進行排程監控。

使用模型監控，您可以設定警示在模型品質出現偏差時通知您。及早主動偵測這些偏差可讓您採取更正動作。您可以採取重新訓練模型、稽核上游系統或修正品質問題等動作，而無需手動監控模型或建置額外的工具。您可以使用預先建置監控功能的模型監控，不需要撰寫程式碼。您也可以撰寫程式碼來提供自訂分析，靈活地監控模型。

模型監控會提供下列類型的監控：
+ [資料品質](model-monitor-data-quality.md) - 監控資料品質的偏離。
+ [模型品質](model-monitor-model-quality.md) - 監控模型品質指標中的偏離，例如準確性。
+ [生產中模型的偏差偏離](clarify-model-monitor-bias-drift.md) - 監控模型預測中的偏差。
+ [生產中模型的特徵屬性偏離](clarify-model-monitor-feature-attribution-drift.md) - 監控功能屬性的偏離。

**Topics**
+ [監控生產環境中的模型](how-it-works-model-monitor.md)
+ [Amazon SageMaker Model Monitor 的運作方式](#model-monitor-how-it-works)
+ [資料擷取](model-monitor-data-capture.md)
+ [資料品質](model-monitor-data-quality.md)
+ [模型品質](model-monitor-model-quality.md)
+ [生產中模型的偏差偏離](clarify-model-monitor-bias-drift.md)
+ [生產中模型的特徵屬性偏離](clarify-model-monitor-feature-attribution-drift.md)
+ [排定監控工作](model-monitor-scheduling.md)
+ [Amazon SageMaker Model Monitor 預建容器](model-monitor-pre-built-container.md)
+ [解讀結果](model-monitor-interpreting-results.md)
+ [在 Amazon SageMaker Studio 中以視覺化方式呈現即時端點的結果](model-monitor-interpreting-visualize-results.md)
+ [進階主題](model-monitor-advanced-topics.md)
+ [模型監控常見問答集](model-monitor-faqs.md)

# 監控生產環境中的模型
<a name="how-it-works-model-monitor"></a>

將模型部署到生產環境後，使用 Amazon SageMaker Model Monitor 來持續監控即時機器學習模型的品質。Amazon SageMaker Model Monitor 可讓您設定自動警示觸發系統，在模型品質偏差 (例如資料偏離和異常) 時發出警示。Amazon CloudWatch Logs 會收集監控模型狀態的日誌檔，並在模型品質達到您預設的特定閾值時提出通知。CloudWatch 會將日誌檔案存放於您指定的 Amazon S3 儲存貯體。透過模型監控產品的早期和主動偵測 AWS 模型偏差，可讓您立即採取行動，以維護和改善已部署模型的品質。

如需 SageMaker 模型監控產品的詳細資訊，請參閱[使用 Amazon SageMaker Model Monitor 進行資料和模型品質監控](model-monitor.md)。

若要使用 SageMaker AI 開始您的機器學習旅程，請在[設定 SageMaker AI](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-set-up.html) 註冊 AWS 帳戶。

## Amazon SageMaker Model Monitor 的運作方式
<a name="model-monitor-how-it-works"></a>

Amazon SageMaker Model Monitor 會自動監控生產環境中的機器學習 (ML) 模型，並在發生品質問題時通知您。模型監控會使用規則來偵測模型中的偏離，並在發生偏離時向您提出警示。下圖顯示在將模型部署到即時端點的情況下，此程序如何運作。

![\[使用 Amazon SageMaker Model Monitor 進行模型監控程序。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model_monitor/mmv2-architecture.png)


您也可以使用模型監控來監控批次轉換工作，而不是即時端點。在這種情況下，Model Monitor 將監控推論輸入和輸出，而不是接收端點的請求並追蹤預測。下圖顯示監控批次轉換工作的程序。

![\[使用 Amazon SageMaker Model Monitor 進行模型監控程序。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model_monitor/mmv2-architecture-batch.png)


若要啟用模型監控，請採取下列步驟。這些步驟會循著資料的路徑通過各種資料收集、監控和分析程序。
+ 對於即時端點，啟用端點將傳入請求中的資料擷取到受過訓練的機器學習 (ML) 模型，以及產生的模型預測。
+ 對於批次轉換工作，啟用批次轉換輸入和輸出的資料擷取。
+ 從用來訓練模型的資料集建立基準。基準會計算指標，並建議指標的限制條件。來自模型的即時或批次預測會與限制條件進行比較。如果它們超出限制值，則會將其報告為違規。
+ 建立監控排程，指定要收集哪些資料、收集資料的頻率、如何分析資料，以及要產生哪些報告。
+ 檢查將最新資料與基準進行比較的報告。留意來自 Amazon CloudWatch 的任何回報違規、指標和通知。

**備註**  
模型監控只會計算表格式資料的模型指標和統計資料。例如，將影像做為輸入並根據該影像輸出標籤的影像分類模型仍可受監控。模型監控能夠計算輸出的指標和統計資料，而不是輸入。
模型監控目前僅支援託管單一模型的端點，不支援監控多模型端點。如需有關使用多模型端點的資訊，請參閱[多模型端點](multi-model-endpoints.md)。
Model Monitor 支援監控推論管道。不過，擷取和分析資料是針對整個管道完成的，而不是針對管道中的單個容器。
為了避免對推論要求造成影響，資料擷取會停止擷取需要高磁碟使用量的要求。我們建議您將磁碟使用率保持在 75% 以下，以確保資料擷取持續擷取請求。
如果您在自訂 Amazon VPC 中啟動 SageMaker Studio，則必須建立 VPC 端點，讓 Model Monitor 可與 Amazon S3 和 CloudWatch 進行通訊。如需有關 VPC 端點的詳細資訊，請參閱 *Amazon Virtual Private Cloud 使用者指南*中的 [VPC 端點](https://docs.aws.amazon.com/vpc/latest/privatelink/concepts.html)。如需有關在自訂 VPC 中啟動 SageMaker Studio 的資訊，請參閱[將 VPC 中的 Studio 筆記本連線至外部資源](studio-notebooks-and-internet-access.md)。

### Model Monitor 範例筆記本
<a name="model-monitor-sample-notebooks"></a>

如需逐步說明使用 Model Monitor 搭配即時端點進行端對端工作流程的範例筆記本，請參閱 [Amazon SageMaker Model Monitor 簡介](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_model_monitor/introduction/SageMaker-ModelMonitoring.html)。

如需可針對監控排程中所選執行來視覺化 statistics.json 檔案的範例筆記本，請參閱 [Model Monitor 視覺化](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_model_monitor/visualization/SageMaker-Model-Monitor-Visualize.html)。

如需如何建立並存取 Jupyter 筆記本執行個體以用來執行 SageMaker 中範例的指示，請參閱[Amazon SageMaker 筆記本執行個體](nbi.md)。建立並開啟筆記本執行個體後，請選擇 **SageMaker AI 範例**索引標籤，查看所有 SageMaker AI 範例清單。若要開啟筆記本，請選擇筆記本的**使用**索引標籤，然後選擇**建立複本**。

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

若要將端點的輸入和從部署模型的推論輸出記錄到 Amazon S3，您可以啟用名為*資料擷取*的功能。*資料擷取*通常用來記錄可用於訓練、偵錯和監控的資訊。Amazon SageMaker Model Monitor 會自動剖析此擷取的資料，並將此資料中的指標與您為模型建立的基準進行比較。如需有關模型監控的更多相關資訊，請參閱[使用 Amazon SageMaker Model Monitor 進行資料和模型品質監控](model-monitor.md)。

您可以使用 適用於 Python (Boto) 的 AWS SDK 或 SageMaker Python SDK，為即時和批次模型監控模式實作*資料擷取*。如果是即時端點，您將在建立端點時指定*資料擷取*組態。由於即時端點的持續性質，您可以設定額外選項以在特定時間開啟或關閉資料擷取，或變更取樣頻率。您也可以選擇加密推論資料。

對於批次轉換工作，如果您想要針對一般、定期的批次轉換工作執行排程模型監控或持續模型監控，則可以啟用*資料擷取*。您將在建立批次轉換工作時指定*資料擷取*組態。在此組態中，您可以選擇開啟加密或在輸出中產生推論 ID，以協助您將擷取的資料與 Ground Truth 資料比對。

# 從即時端點擷取資料
<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"
}
```

# 從批次轉換工作擷取資料
<a name="model-monitor-data-capture-batch"></a>

 無論您使用 適用於 Python (Boto) 的 AWS SDK 或 SageMaker Python SDK，開啟批次轉換任務的資料擷取所需的步驟都很類似。如果您使用 AWS SDK，請在 `CreateTransformJob`方法中定義 [DataCaptureConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataCaptureConfig.html) 字典以及必要欄位，以開啟資料擷取。如果您使用 SageMaker AI Python SDK，請匯入 `BatchDataCaptureConfig` 類別，並從此類別初始化執行個體。然後，將此物件傳遞給轉換工作執行個體的 `batch_data_capture_config` 參數。

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

## 如何啟用資料擷取
<a name="data-capture-batch-enable"></a>

 在啟動轉換工作時指定資料擷取組態。無論您使用 適用於 Python (Boto3) 的 AWS SDK 或 SageMaker Python SDK，都必須提供 `DestinationS3Uri`引數，這是您希望轉換任務記錄擷取資料的目錄。您也可以選擇指定以下參數：
+  `KmsKeyId`：用來加密擷取資料的 AWS KMS 金鑰。
+  `GenerateInferenceId`：布林值標記，用於在擷取資料時，指出轉換工作是否要將推論 ID 和時間附加至輸出。這對於需要擷取 Ground Truth 資料的模型品質監控非常有用。推論 ID 和時間有助於將擷取資料與您的 Ground Truth 資料進行比對。

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

 使用 `CreateTransformJob` 方法建立轉換工作時，使用 [DataCaptureConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataCaptureConfig.html) 字典來設定要擷取的資料。

```
input_data_s3_uri = "s3://input_S3_uri"
output_data_s3_uri = "s3://output_S3_uri"
data_capture_destination = "s3://captured_data_S3_uri"

model_name = "model_name"

sm_client.create_transform_job(
    TransformJobName="transform_job_name",
    MaxConcurrentTransforms=2,
    ModelName=model_name,
    TransformInput={
        "DataSource": {
            "S3DataSource": {
                "S3DataType": "S3Prefix",
                "S3Uri": input_data_s3_uri,
            }
        },
        "ContentType": "text/csv",
        "CompressionType": "None",
        "SplitType": "Line",
    },
    TransformOutput={
        "S3OutputPath": output_data_s3_uri,
        "Accept": "text/csv",
        "AssembleWith": "Line",
    },
    TransformResources={
        "InstanceType": "ml.m4.xlarge",
        "InstanceCount": 1,
    },
    DataCaptureConfig={
       "DestinationS3Uri": data_capture_destination,
       "KmsKeyId": "kms_key",
       "GenerateInferenceId": True,
    }
    )
```

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

 從 [sagemaker.model\$1monitor](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html) 匯入 `BatchDataCaptureConfig` 類別。

```
from sagemaker.transformer import Transformer
from sagemaker.inputs import BatchDataCaptureConfig

# Optional - The S3 URI of where to store captured data in S3
data_capture_destination = "s3://captured_data_S3_uri"

model_name = "model_name"

transformer = Transformer(model_name=model_name, ...)
transform_arg = transformer.transform(
    batch_data_capture_config=BatchDataCaptureConfig(
        destination_s3_uri=data_capture_destination,
        kms_key_id="kms_key",
        generate_inference_id=True,
    ),
    ...
)
```

------

## 如何檢視擷取的資料
<a name="data-capture-batch-view"></a>

 轉換工作完成後，擷取的資料就會記錄在您於資料擷取組態提供的 `DestinationS3Uri` 下。在 `DestinationS3Uri` 下有兩個子目錄 `/input` 和 `/output`。如果 `DestinationS3Uri` 是 `s3://my-data-capture`，則轉換工作會建立下列目錄：
+  `s3://my-data-capture/input`：轉換工作擷取的輸入資料。
+  `s3://my-data-capture/output`：轉換工作擷取的輸出資料。

 為了避免資料重複，前兩個目錄下擷取的資料是清單檔案。每個清單檔案都是 JSONL 檔案，其中包含來源物件的 Amazon S3 位置。清單檔案看起來可能與以下範例相似：

```
# under "/input" directory
[
    {"prefix":"s3://input_S3_uri/"},
    "dummy_0.csv",
    "dummy_1.csv",
    "dummy_2.csv",
    ...
]

# under "/output" directory
[
    {"prefix":"s3://output_S3_uri/"},
    "dummy_0.csv.out",
    "dummy_1.csv.out",
    "dummy_2.csv.out",
    ...
]
```

 轉換工作會使用 *yyyy/mm/dd/hh* S3 前置詞來組織這些清單檔案並加上標籤，以指出擷取的時間。這有助於模型監控確定要分析的資料的適當部分。例如，如果您在世界協調時間 (UTC) 2022 年 8 月 26 日下午 1 點開始轉換工作，則擷取的資料會以 `2022/08/26/13/` 前置字串標示。

## 推論 ID 產生
<a name="data-capture-batch-inferenceid"></a>

 設定 `DataCaptureConfig` 轉換工作時，您可以開啟布林值標記 `GenerateInferenceId`。當您需要執行模型品質和模型偏差監控工作時，需要使用者擷取的 Ground Truth 資料，這時此功能特別有用。模型監控仰賴推論 ID 來比對擷取的資料和 Ground Truth 資料。如需 Ground Truth 擷取的其他詳細資料，請參閱[擷取 Ground Truth 標籤並將其與預測合併](model-monitor-model-quality-merge.md)。開啟 `GenerateInferenceId` 時，轉換輸出會附加推論 ID (隨機 UUID)，以及每筆記錄的轉換工作開始時間 (以世界協調時間計算)。您需要這兩個值才能執行模型品質和模型偏差監控。當您建構 Ground Truth 資料時，您需要提供相同的推論 ID 以符合輸出資料。目前，此功能支援 CSV、JSON 和 JSONL 格式的轉換輸出。

 如果轉換輸出為 CSV 格式，輸出檔案看起來會像下列範例：

```
0, 1f1d57b1-2e6f-488c-8c30-db4e6d757861,2022-08-30T00:49:15Z
1, 22445434-0c67-45e9-bb4d-bd1bf26561e6,2022-08-30T00:49:15Z
...
```

 最後兩個欄位是推論 ID 和轉換工作開始時間。請勿修改這些欄位。其餘欄位是您的轉換工作輸出。

 如果轉換輸出為 JSON 或 JSONL 格式，輸出檔案看起來會像下列範例：

```
{"output": 0, "SageMakerInferenceId": "1f1d57b1-2e6f-488c-8c30-db4e6d757861", "SageMakerInferenceTime": "2022-08-30T00:49:15Z"}
{"output": 1, "SageMakerInferenceId": "22445434-0c67-45e9-bb4d-bd1bf26561e6", "SageMakerInferenceTime": "2022-08-30T00:49:15Z"}
...
```

 有兩個保留的附加欄位 `SageMakerInferenceId` 和 `SageMakerInferenceTime`。如果您需要執行模型品質或模型偏差監控，請勿修改這些欄位，因為合併工作時需要這些欄位。

# 資料品質
<a name="model-monitor-data-quality"></a>

資料品質會自動監控生產環境中的機器學習 (ML) 模型，並在發生資料品質問題時通知您。生產環境中的機器學習 (ML) 模型必須對實際資料進行預測，這些資料不像大多數訓練資料集那樣仔細策劃。在生產環境中，如果模型收到的資料的統計性質偏離其訓練基準資料的本質，則模型的預測準確度會開始下降。Amazon SageMaker Model Monitor 使用規則來偵測資料偏離，並在發生偏離時向您提出警示。若要監控資料品質，請依照下列步驟執行：
+ 啟用資料擷取。這會擷取即時推論端點或批次轉換工作的推論輸入和輸出，並將資料存放在 Amazon S3 中。如需詳細資訊，請參閱[資料擷取](model-monitor-data-capture.md)。
+ 建立基準。在此步驟中，您需執行基準工作來分析您提供的輸入資料集。基準使用 [Deequ](https://github.com/awslabs/deequ) (採用 Apache Spark 架構的開放原始碼程式庫，用於測量大型資料集的資料品質)，計算每個功能的基準結構描述限制條件和統計資料。如需詳細資訊，請參閱[建立基準](model-monitor-create-baseline.md)。
+ 定義和排程資料品質監控工作。如需資料品質監控工作的特定資訊和程式碼範例，請參閱[排程資料品質監控工作](model-monitor-schedule-data-monitor.md)。如需監控工作的一般資訊，請參閱[排定監控工作](model-monitor-scheduling.md)。
  + 選擇性地使用預先處理和後製處理指令碼，來轉換資料品質分析中的資料。如需詳細資訊，請參閱[預處理和後處理](model-monitor-pre-and-post-processing.md)。
+ 檢視資料品質指標。如需詳細資訊，請參閱[統計資料的結構描述 (statistics.json 檔案)](model-monitor-interpreting-statistics.md)。
+ 整合資料品質監控與 Amazon CloudWatch。如需詳細資訊，請參閱[CloudWatch Metrics](model-monitor-interpreting-cloudwatch.md)。
+ 解譯監控工作的結果。如需詳細資訊，請參閱[解讀結果](model-monitor-interpreting-results.md)。
+ 如果您使用的是即時端點，請使用 SageMaker Studio 啟用資料品質監控和視覺化結果。如需詳細資訊，請參閱[在 Amazon SageMaker Studio 中以視覺化方式呈現即時端點的結果](model-monitor-interpreting-visualize-results.md)。

**注意**  
模型監控只會計算表格式資料的模型指標和統計資料。例如，將影像做為輸入並根據該影像輸出標籤的影像分類模型仍可受監控。模型監控能夠計算輸出的指標和統計資料，而不是輸入。

**Topics**
+ [建立基準](model-monitor-create-baseline.md)
+ [排程資料品質監控工作](model-monitor-schedule-data-monitor.md)
+ [統計資料的結構描述 (statistics.json 檔案)](model-monitor-interpreting-statistics.md)
+ [CloudWatch Metrics](model-monitor-interpreting-cloudwatch.md)
+ [違規的結構描述 (constraint\$1violations.json 檔案)](model-monitor-interpreting-violations.md)

# 建立基準
<a name="model-monitor-create-baseline"></a>

需要計算統計資料和限制條件的基準，作為偵測資料漂移和其他資料品質問題時的標準。模型監控提供內建的容器，能夠針對 CSV 和單層 JSON 輸入，自動建議限制條件。此 *sagemaker-model-monitor-analyzer* 容器也提供一系列模型監控功能，包括根據基準來驗證限制條件，以及發出 Amazon CloudWatch 指標。此容器根據 Spark 3.3.0 版，並使用 [Deequ](https://github.com/awslabs/deequ) 2.0.2 版建置。基準資料集中的所有欄位名稱都必須與 Spark 相容。對於欄位名稱，僅限使用小寫字元，且 `_` 為唯一的特殊字元。

您用來訓練模型的訓練資料集，通常就是適合的基準資料集。訓練資料集資料結構描述和推論資料集結構描述，應該完全相符 (特徵數目和順序)。請注意，預測/輸出欄假定為訓練資料集的第一欄。您可以要求 SageMaker AI 根據訓練資料集，建議一組基準限制條件，並產生描述性統計資料，以利於您探索資料。針對此範例，請上傳訓練資料集 (原先用來訓練此範例中預先訓練的模型)。如果您已將訓練資料集存放在 Amazon S3 中，則可以直接指向其位置。

**從訓練資料集建立基準** 

當您準備好訓練資料並將其存放在 Amazon S3 時，透過 `DefaultModelMonitor.suggest_baseline(..)` 使用 [Amazon SageMaker Python SDK ](https://sagemaker.readthedocs.io/en/stable) 開始基準處理工作。這會使用 [Amazon SageMaker Model Monitor 預建容器](model-monitor-pre-built-container.md)，以針對資料集產生基準統計資料和建議基準限制條件，並寫入您指定的 `output_s3_uri` 位置。

```
from sagemaker.model_monitor import DefaultModelMonitor
from sagemaker.model_monitor.dataset_format import DatasetFormat

my_default_monitor = DefaultModelMonitor(
    role=role,
    instance_count=1,
    instance_type='ml.m5.xlarge',
    volume_size_in_gb=20,
    max_runtime_in_seconds=3600,
)

my_default_monitor.suggest_baseline(
    baseline_dataset=baseline_data_uri+'/training-dataset-with-header.csv',
    dataset_format=DatasetFormat.csv(header=True),
    output_s3_uri=baseline_results_uri,
    wait=True
)
```

**注意**  
如果您在訓練資料集提供功能/欄位名稱當作第一列，並如上述程式碼範例來設定 `header=True` 選項，SageMaker AI 會在限制條件和統計資料檔案中使用該功能名稱。

資料集的基準統計資料放在 statistics.json 檔案，而建議的基準限制條件放在 constraints.json 檔案 (在您以 `output_s3_uri` 指定的位置中)。

表格式資料集統計資料和限制條件的輸出檔案


| 檔案名稱 | Description | 
| --- | --- | 
| statistics.json |  針對所分析資料集的每個特徵，此檔案會有單欄式統計資料。如需有關此檔案的結構描述的更多相關資訊，請參閱[統計資料的結構描述 (statistics.json 檔案)](model-monitor-byoc-statistics.md)。  | 
| constraints.json |  針對所觀察的特徵，此檔案會有限制條件。如需有關此檔案的結構描述的更多相關資訊，請參閱[限制條件的結構描述 (constraints.json 檔案)](model-monitor-byoc-constraints.md)。  | 

[Amazon SageMaker Python SDK ](https://sagemaker.readthedocs.io/en/stable) 提供方便的函式，可用來產生基準統計資料和限制條件。但是，如果您想為此目的改為直接呼叫處理工作，則需要設定 `Environment` 對應，如以下範例所示：

```
"Environment": {
    "dataset_format": "{\"csv\”: { \”header\”: true}",
    "dataset_source": "/opt/ml/processing/sm_input",
    "output_path": "/opt/ml/processing/sm_output",
    "publish_cloudwatch_metrics": "Disabled",
}
```

# 排程資料品質監控工作
<a name="model-monitor-schedule-data-monitor"></a>

建立基準之後，您可以呼叫 `DefaultModelMonitor` 類別執行個體的 `create_monitoring_schedule()` 方法來排程每小時的資料品質監控。以下各節說明如何為部署到即時端點的模型以及批次轉換工作建立資料品質監控。

**重要**  
在建立監控排程時，您可以指定批次轉換輸入或端點輸入，但不能同時指定兩者。

## 部署至即時端點的模型的資料品質監控
<a name="model-monitor-data-quality-rt"></a>

若要為即時端點排程資料品質監控，請將 `EndpointInput` 執行個體傳遞至 `DefaultModelMonitor` 執行個體的 `endpoint_input` 引數，如下列程式碼範例所示：

```
from sagemaker.model_monitor import CronExpressionGenerator
                
data_quality_model_monitor = DefaultModelMonitor(
   role=sagemaker.get_execution_role(),
   ...
)

schedule = data_quality_model_monitor.create_monitoring_schedule(
   monitor_schedule_name=schedule_name,
   post_analytics_processor_script=s3_code_postprocessor_uri,
   output_s3_uri=s3_report_path,
   schedule_cron_expression=CronExpressionGenerator.hourly(),
   statistics=data_quality_model_monitor.baseline_statistics(),
   constraints=data_quality_model_monitor.suggested_constraints(),
   schedule_cron_expression=CronExpressionGenerator.hourly(),
   enable_cloudwatch_metrics=True,
   endpoint_input=EndpointInput(
        endpoint_name=endpoint_name,
        destination="/opt/ml/processing/input/endpoint",
   )
)
```

## 批次轉換工作的資料品質監控
<a name="model-monitor-data-quality-bt"></a>

若要為批次轉換工作排程資料品質監控，請將 `BatchTransformInput` 執行個體傳遞至 `DefaultModelMonitor` 執行個體的 `batch_transform_input` 引數，如下列程式碼範例所示：

```
from sagemaker.model_monitor import CronExpressionGenerator
                
data_quality_model_monitor = DefaultModelMonitor(
   role=sagemaker.get_execution_role(),
   ...
)

schedule = data_quality_model_monitor.create_monitoring_schedule(
    monitor_schedule_name=mon_schedule_name,
    batch_transform_input=BatchTransformInput(
        data_captured_destination_s3_uri=s3_capture_upload_path,
        destination="/opt/ml/processing/input",
        dataset_format=MonitoringDatasetFormat.csv(header=False),
    ),
    output_s3_uri=s3_report_path,
    statistics= statistics_path,
    constraints = constraints_path,
    schedule_cron_expression=CronExpressionGenerator.hourly(),
    enable_cloudwatch_metrics=True,
)
```

# 統計資料的結構描述 (statistics.json 檔案)
<a name="model-monitor-interpreting-statistics"></a>

Amazon SageMaker Model Monitor 預先建置的容器會根據欄位/功能統計資料進行計算。計算的統計資料以基準資料集和目前正在分析的資料集為對象。

```
{
    "version": 0,
    # dataset level stats
    "dataset": {
        "item_count": number
    },
    # feature level stats
    "features": [
        {
            "name": "feature-name",
            "inferred_type": "Fractional" | "Integral",
            "numerical_statistics": {
                "common": {
                    "num_present": number,
                    "num_missing": number
                },
                "mean": number,
                "sum": number,
                "std_dev": number,
                "min": number,
                "max": number,
                "distribution": {
                    "kll": {
                        "buckets": [
                            {
                                "lower_bound": number,
                                "upper_bound": number,
                                "count": number
                            }
                        ],
                        "sketch": {
                            "parameters": {
                                "c": number,
                                "k": number
                            },
                            "data": [
                                [
                                    num,
                                    num,
                                    num,
                                    num
                                ],
                                [
                                    num,
                                    num
                                ][
                                    num,
                                    num
                                ]
                            ]
                        }#sketch
                    }#KLL
                }#distribution
            }#num_stats
        },
        {
            "name": "feature-name",
            "inferred_type": "String",
            "string_statistics": {
                "common": {
                    "num_present": number,
                    "num_missing": number
                },
                "distinct_count": number,
                "distribution": {
                    "categorical": {
                         "buckets": [
                                {
                                    "value": "string",
                                    "count": number
                                }
                          ]
                     }
                }
            },
            #provision for custom stats
        }
    ]
}
```

注意下列事項：
+ 預先建置的容器會計算 [KLL 草圖](https://datasketches.apache.org/docs/KLL/KLLSketch.html) (簡潔的分位數草圖)。
+ 依預設，我們分成 10 個儲存貯體將分佈具體化。這目前無法設定。

# CloudWatch Metrics
<a name="model-monitor-interpreting-cloudwatch"></a>

您可以針對 CloudWatch 指標使用內建的 Amazon SageMaker Model Monitor 容器。當 `emit_metrics` 選項在基準限制條件檔案中為 `Enabled` 時，SageMaker AI 會以下列命名空間針對在資料集中觀察到的每個特徵/欄位發出這些指標：
+ 具有 `EndpointName` 和 `ScheduleName` 維度的 `For real-time endpoints: /aws/sagemaker/Endpoints/data-metric` 命名空間。
+ 具有 `MonitoringSchedule` 維度的 `For batch transform jobs: /aws/sagemaker/ModelMonitoring/data-metric` 命名空間。

對於數字欄位，內建容器會發出下列 CloudWatch 指標：
+ 指標：Max → 查詢 `MetricName: feature_data_{feature_name}, Stat: Max`
+ 指標：Min → 查詢 `MetricName: feature_data_{feature_name}, Stat: Min`
+ 指標：Sum → 查詢 `MetricName: feature_data_{feature_name}, Stat: Sum`
+ 指標：SampleCount → 查詢 `MetricName: feature_data_{feature_name}, Stat: SampleCount`
+ 指標：Average → 查詢 `MetricName: feature_data_{feature_name}, Stat: Average`

對於數字欄位和字串欄位，內建容器會發出下列 CloudWatch 指標：
+ 指標：Completeness → 查詢 `MetricName: feature_non_null_{feature_name}, Stat: Sum`
+ 指標：Baseline Drift → 查詢 `MetricName: feature_baseline_drift_{feature_name}, Stat: Sum`

# 違規的結構描述 (constraint\$1violations.json 檔案)
<a name="model-monitor-interpreting-violations"></a>

`MonitoringExecution` 的輸出為違規檔案，其中列出針對目前所分析資料集來評估限制條件 (在 constraints.json 檔案中指定) 的結果。Amazon SageMaker Model Monitor 預先建置容器提供下列違規檢查。

```
{
    "violations": [{
      "feature_name" : "string",
      "constraint_check_type" :
              "data_type_check",
            | "completeness_check",
            | "baseline_drift_check",
            | "missing_column_check",
            | "extra_column_check",
            | "categorical_values_check"
      "description" : "string"
    }]
}
```

監控的違規類型 


| 違規檢查類型 | Description  | 
| --- | --- | 
| data\$1type\$1check | 如果目前執行與基準資料集的資料類型不相同，則會標記此違規。 在基準步驟期間，產生的限制條件會針對每個欄，建議推斷的資料類型。您可以調校 `monitoring_config.datatype_check_threshold` 參數，以調整何時標記為違規的臨界值。  | 
| completeness\$1check | 如果在目前執行中觀察到的完整度 (非 null 項目的百分比)，超過在每個特徵指定的完整度臨界值中指定的臨界值，則會標記此違規。 在基準步驟期間，產生的限制條件會建議完整度值。  | 
| baseline\$1drift\$1check | 如果目前與基準資料集之間計算的分佈距離大於 `monitoring_config.comparison_threshold` 中指定的臨界值，則會標記此違規。  | 
| missing\$1column\$1check | 如果目前資料集的欄數少於基準資料集的欄數，則會標記此違規。  | 
| extra\$1column\$1check | 如果目前資料集的欄數超過基準的欄數，則會標記此違規。  | 
| categorical\$1values\$1check | 如果目前資料集的未知值比基準資料集更多，則會標記此違規。此值由 `monitoring_config.domain_content_threshold` 中的臨界值決定。  | 

# 模型品質
<a name="model-monitor-model-quality"></a>

模型品質監控工作會將模型所做的預測與模型嘗試預測的實際 Ground Truth 標籤進行比較，以監控模型的效能。為了這麼做，模型品質監控會將從即時或批次推論擷取的資料與存放在 Amazon S3 儲存貯體的實際標籤合併，然後將預測與實際標籤進行比較。

為了測量模型品質，模型監控會使用取決於機器學習 (ML) 問題類型的指標。例如，如果您的模型是針對迴歸問題，則評估的其中一個指標是均方誤差 (mse)。如需用於不同機器學習 (ML) 問題類型之所有指標的相關資訊，請參閱[模型品質指標和 Amazon CloudWatch 監控](model-monitor-model-quality-metrics.md)。

模型品質監控按照與資料品質監控相同的步驟，但新增額外步驟以合併 Amazon S3 實際標籤與從即時推論端點或批次轉換工作擷取的預測結果。若要監控模型品質，請依照下列步驟執行：
+ 啟用資料擷取。這會擷取即時推論端點或批次轉換工作的推論輸入和輸出，並將資料存放在 Amazon S3 中。如需詳細資訊，請參閱[資料擷取](model-monitor-data-capture.md)。
+ 建立基準。在此步驟中，您會執行基準工作，將模型的預測結果與基準資料集中的 Ground Truth 標籤進行比較。基準工作會自動建立基準統計規則和限制，以定義評估模型效能的閾值。如需詳細資訊，請參閱[建立模型品質基準](model-monitor-model-quality-baseline.md)。
+ 定義和排程模型品質監控工作。如需模型品質監控任務的特定資訊和程式碼範例，請參閱[排程模型品質監控任務](model-monitor-model-quality-schedule.md)。如需監控工作的一般資訊，請參閱[排定監控工作](model-monitor-scheduling.md)。
+ 擷取 Ground Truth 標籤，模型監控會將其與從即時推論端點或批次轉換工作擷取的預測資料合併。如需詳細資訊，請參閱[擷取 Ground Truth 標籤並將其與預測合併](model-monitor-model-quality-merge.md)。
+ 整合模型品質監控與 Amazon CloudWatch。如需詳細資訊，請參閱[使用 CloudWatch 指標監控模型品質](model-monitor-model-quality-metrics.md#model-monitor-model-quality-cw)。
+ 解譯監控工作的結果。如需詳細資訊，請參閱[解讀結果](model-monitor-interpreting-results.md)。
+ 使用 SageMaker Studio 以啟用模型品質監控並視覺化結果。如需詳細資訊，請參閱[在 Amazon SageMaker Studio 中以視覺化方式呈現即時端點的結果](model-monitor-interpreting-visualize-results.md)。

**Topics**
+ [建立模型品質基準](model-monitor-model-quality-baseline.md)
+ [排程模型品質監控任務](model-monitor-model-quality-schedule.md)
+ [擷取 Ground Truth 標籤並將其與預測合併](model-monitor-model-quality-merge.md)
+ [模型品質指標和 Amazon CloudWatch 監控](model-monitor-model-quality-metrics.md)

# 建立模型品質基準
<a name="model-monitor-model-quality-baseline"></a>

建立基準工作，將模型預測與 Amazon S3 中已存放的基準資料集中的 Ground Truth 標籤進行比較。一般而言，您會使用訓練資料集做為基準資料集。基準工作會計算模型的指標，並建議用於監控模型品質偏離的限制。

若要建立基準工作，您需要有一個資料集，其中包含來自模型的預測以及代表您資料 Ground Truth 的標籤。

若要建立基準工作，請使用 SageMaker Python SDK 提供的 `ModelQualityMonitor` 類別，並完成下列步驟。

**建立模型品質基準工作**

1.  首先，建立 `ModelQualityMonitor` 類別的執行個體。下列程式碼片段顯示其做法。

   ```
   from sagemaker import get_execution_role, session, Session
   from sagemaker.model_monitor import ModelQualityMonitor
                   
   role = get_execution_role()
   session = Session()
   
   model_quality_monitor = ModelQualityMonitor(
       role=role,
       instance_count=1,
       instance_type='ml.m5.xlarge',
       volume_size_in_gb=20,
       max_runtime_in_seconds=1800,
       sagemaker_session=session
   )
   ```

1. 現在，呼叫 `ModelQualityMonitor` 物件的 `suggest_baseline` 方法來執行基準工作。下列程式碼片段假設您有一個基準資料集，其中包含儲存在 Amazon S3 中的預測和標籤。

   ```
   baseline_job_name = "MyBaseLineJob"
   job = model_quality_monitor.suggest_baseline(
       job_name=baseline_job_name,
       baseline_dataset=baseline_dataset_uri, # The S3 location of the validation dataset.
       dataset_format=DatasetFormat.csv(header=True),
       output_s3_uri = baseline_results_uri, # The S3 location to store the results.
       problem_type='BinaryClassification',
       inference_attribute= "prediction", # The column in the dataset that contains predictions.
       probability_attribute= "probability", # The column in the dataset that contains probabilities.
       ground_truth_attribute= "label" # The column in the dataset that contains ground truth labels.
   )
   job.wait(logs=False)
   ```

1. 在基準工作完成後，您便可以看到工作產生的限制條件。首先，呼叫 `ModelQualityMonitor` 物件的 `latest_baselining_job` 方法，取得基準工作的結果。

   ```
   baseline_job = model_quality_monitor.latest_baselining_job
   ```

1. 基準工作會建議限制條件，限制條件是模型監控測量之指標的閾值。如果指標超出建議的閾值，模型監控會報告違規。若要檢視基準工作所產生的限制條件，請呼叫基準工作的 `suggested_constraints` 方法。以下程式碼片段將二進制分類模型的限制條件載入至 Pandas 資料框中。

   ```
   import pandas as pd
   pd.DataFrame(baseline_job.suggested_constraints().body_dict["binary_classification_constraints"]).T
   ```

   建議您先檢視所產生的限制條件並視需要進行修改，然後再將其用於監控。例如，如果限制條件過於嚴格，您收到的違規警示可能會比您想要的多。

   如果限制條件包含以科學符號表示的數字，則需要將其轉換為浮點數。以下 Python [預先處理指令碼](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-pre-and-post-processing.html#model-monitor-pre-processing-script)範例顯示如何將科學符號的數字轉換為浮點數。

   ```
   import csv
   
   def fix_scientific_notation(col):
       try:
           return format(float(col), "f")
       except:
           return col
   
   def preprocess_handler(csv_line):
       reader = csv.reader([csv_line])
       csv_record = next(reader)
       #skip baseline header, change HEADER_NAME to the first column's name
       if csv_record[0] == “HEADER_NAME”:
          return []
       return { str(i).zfill(20) : fix_scientific_notation(d) for i, d in enumerate(csv_record)}
   ```

   您可以如[模型監控](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html)文件中的定義，將預先處理指令碼新增至基準或監控排程為 `record_preprocessor_script`。

1. 當您滿意限制條件時，在建立監控排程時將這些限制條件傳遞為 `constraints` 參數。如需詳細資訊，請參閱[排程模型品質監控任務](model-monitor-model-quality-schedule.md)。

建議的基準限制條件包含在您使用 `output_s3_uri` 指定的位置中的限制條件 constraints.json 檔案中。如需有關此檔案的結構描述的詳細資訊，請參閱[限制條件的結構描述 (constraints.json 檔案)](model-monitor-byoc-constraints.md)。

# 排程模型品質監控任務
<a name="model-monitor-model-quality-schedule"></a>

建立基準之後，您可以呼叫 `ModelQualityMonitor` 類別執行個體的 `create_monitoring_schedule()` 方法來排程每小時的模型品質監控。以下各節說明如何為部署到即時端點的模型以及批次轉換工作建立模型品質監控。

**重要**  
在建立監控排程時，您可以指定批次轉換輸入或端點輸入，但不能同時指定兩者。

與資料品質監控不同，如果要監控模型品質，需要提供 Ground Truth 標籤。但是，Ground Truth 標籤可能會延遲。若要解決此問題，請在建立監控排程時指定偏移。

## 模型監控偏移
<a name="model-monitor-model-quality-schedule-offsets"></a>

模型品質工作包括 `StartTimeOffset` 和 `EndTimeOffset`，這些是 `create_model_quality_job_definition` 方法的 `ModelQualityJobInput` 參數欄位，其運作方式如下：
+ `StartTimeOffset` - 如果指定，工作會從開始時間減去這個時間。
+ `EndTimeOffset` - 如果指定，工作會從結束時間減去這個時間。

例如，偏移的格式為 -PT7H，其中 7H 為 7 小時。您可以使用 -PT\$1H 或 -P\$1D，其中 H = 小時、D = 天、M = 分鐘和 \$1 是數字。此外，偏移應採用 [ISO 8601 持續時間格式](https://en.wikipedia.org/wiki/ISO_8601#Durations)。

例如，如果您的 Ground Truth 在 1 天後開始出現，但在一周內未完成，則將 `StartTimeOffset`設為 `-P8D`，並將 `EndTimeOffset` 設為 `-P1D`。然後，如果您排定在 `2020-01-09T13:00` 要執行的工作，會分析 `2020-01-01T13:00` 至 `2020-01-08T13:00` 之間的資料。

**重要**  
排程節奏應該讓一個執行在下一個執行開始之前完成，讓執行的 Ground Truth 合併工作和監控工作可以完成。執行的執行期上限會分配在兩個工作之間，因此對於每小時的模型品質監控工作，指定為一部分 `StoppingCondition` 的 `MaxRuntimeInSeconds` 值不應超過 1800。

## 部署至即時端點的模型的模型品質監控
<a name="model-monitor-data-quality-schedule-rt"></a>

若要為即時端點排程模型品質監控，請將 `EndpointInput` 執行個體傳遞至 `ModelQualityMonitor` 執行個體的 `endpoint_input` 引數，如下列程式碼範例所示：

```
from sagemaker.model_monitor import CronExpressionGenerator
                    
model_quality_model_monitor = ModelQualityMonitor(
   role=sagemaker.get_execution_role(),
   ...
)

schedule = model_quality_model_monitor.create_monitoring_schedule(
   monitor_schedule_name=schedule_name,
   post_analytics_processor_script=s3_code_postprocessor_uri,
   output_s3_uri=s3_report_path,
   schedule_cron_expression=CronExpressionGenerator.hourly(),    
   statistics=model_quality_model_monitor.baseline_statistics(),
   constraints=model_quality_model_monitor.suggested_constraints(),
   schedule_cron_expression=CronExpressionGenerator.hourly(),
   enable_cloudwatch_metrics=True,
   endpoint_input=EndpointInput(
        endpoint_name=endpoint_name,
        destination="/opt/ml/processing/input/endpoint",
        start_time_offset="-PT2D",
        end_time_offset="-PT1D",
    )
)
```

## 批次轉換工作的模型品質監控
<a name="model-monitor-data-quality-schedule-tt"></a>

若要為批次轉換工作排程模型品質監控，請將 `BatchTransformInput` 執行個體傳遞至 `ModelQualityMonitor` 執行個體的 `batch_transform_input` 引數，如下列程式碼範例所示：

```
from sagemaker.model_monitor import CronExpressionGenerator

model_quality_model_monitor = ModelQualityMonitor(
   role=sagemaker.get_execution_role(),
   ...
)

schedule = model_quality_model_monitor.create_monitoring_schedule(
    monitor_schedule_name=mon_schedule_name,
    batch_transform_input=BatchTransformInput(
        data_captured_destination_s3_uri=s3_capture_upload_path,
        destination="/opt/ml/processing/input",
        dataset_format=MonitoringDatasetFormat.csv(header=False),
        # the column index of the output representing the inference probablity
        probability_attribute="0",
        # the threshold to classify the inference probablity to class 0 or 1 in 
        # binary classification problem
        probability_threshold_attribute=0.5,
        # look back 6 hour for transform job outputs.
        start_time_offset="-PT6H",
        end_time_offset="-PT0H"
    ),
    ground_truth_input=gt_s3_uri,
    output_s3_uri=s3_report_path,
    problem_type="BinaryClassification",
    constraints = constraints_path,
    schedule_cron_expression=CronExpressionGenerator.hourly(),
    enable_cloudwatch_metrics=True,
)
```

# 擷取 Ground Truth 標籤並將其與預測合併
<a name="model-monitor-model-quality-merge"></a>

模型品質監控會將模型所做的預測與 Ground Truth 標籤進行比較，以測量模型的品質。為了這麼做，您可以定期標籤端點或批次轉換工作擷取的資料，並將其上傳到 Amazon S3。

為了讓 Ground Truth 標籤與擷取的預測資料相符，資料集中的每個記錄都必須有唯一識別碼。Ground Truth 資料的每個記錄結構如下：

```
{
  "groundTruthData": {
    "data": "1",
    "encoding": "CSV"
  },
  "eventMetadata": {
    "eventId": "aaaa-bbbb-cccc"
  },
  "eventVersion": "0"
}
```

在 `groundTruthData` 結構中，`eventId` 可以是以下其中一項：
+ `eventId` – 當使用者調用端點時，會自動產生此 ID。
+ `inferenceId` – 呼叫者在調用端點時會提供此 ID。

如果 `inferenceId` 存在於擷取的資料記錄中，模型監控會使用它與 Ground Truth 記錄合併擷取的資料。您有責任確保 Ground Truth 記錄中的 `inferenceId` 與擷取記錄中的 `inferenceId` 相符。如果擷取的資料中不存在 `inferenceId`，模型監控會使用擷取的資料記錄中的 `eventId` 與 Ground Truth 記錄進行比對。

您必須將 Ground Truth 資料上傳到路徑格式與擷取資料相同的 Amazon S3 儲存貯體。

**資料格式要求**  
當您將資料儲存到 Amazon S3 時，它必須使用 jsonlines 格式 (.jsonl)，並使用下列命名結構儲存。若要進一步了解 jsonline 要求，請參閱[使用輸入和輸出資料](sms-data.md)。

```
s3://amzn-s3-demo-bucket1/prefix/yyyy/mm/dd/hh
```

此路徑中的日期是收集 Ground Truth 標籤的日期，而不必與產生推論的日期相符。

建立並上傳 Ground Truth 標籤後，在建立監控工作時將標籤的位置納入為參數。如果您使用的是 適用於 Python (Boto3) 的 AWS SDK，請指定 Ground Truth 標籤的位置做為呼叫 `create_model_quality_job_definition`方法的 `GroundTruthS3Input` 參數`S3Uri`欄位來執行此操作。如果您使用的是 SageMaker Python SDK，在呼叫 `ModelQualityMonitor` 物件的 `create_monitoring_schedule` 時，指定 Ground Truth 標籤的位置為 `ground_truth_input` 參數。

# 模型品質指標和 Amazon CloudWatch 監控
<a name="model-monitor-model-quality-metrics"></a>

模型品質監控任務會計算不同的指標，以評估機器學習模型的品質和效能。計算的特定指標取決於 ML 問題的類型：迴歸、二進制分類或多類別分類。監控這些指標對於偵測模型隨時間的偏離至關重要。下列各節涵蓋每種問題類型的關鍵模型品質指標，以及如何使用 CloudWatch 設定自動監控和警示，以持續追蹤您模型的效能。

**注意**  
只有在至少有 200 個樣本時，才會提供指標的標準差。模型監控會計算標準差，方法是透過隨機取樣 80% 的資料五次、計算指標，並取得這些結果的標準差。

## 迴歸指標
<a name="model-monitor-model-quality-metrics-regression"></a>

以下顯示模型品質監控針對迴歸問題所計算的指標範例。

```
"regression_metrics" : {
    "mae" : {
      "value" : 0.3711832061068702,
      "standard_deviation" : 0.0037566388129940394
    },
    "mse" : {
      "value" : 0.3711832061068702,
      "standard_deviation" : 0.0037566388129940524
    },
    "rmse" : {
      "value" : 0.609248066149471,
      "standard_deviation" : 0.003079253267651125
    },
    "r2" : {
      "value" : -1.3766111872212665,
      "standard_deviation" : 0.022653980022771227
    }
  }
```

## 二進制分類指標
<a name="model-monitor-model-quality-metrics-binary"></a>

以下顯示模型品質監控針對二進制分類問題所計算的指標範例。

```
"binary_classification_metrics" : {
    "confusion_matrix" : {
      "0" : {
        "0" : 1,
        "1" : 2
      },
      "1" : {
        "0" : 0,
        "1" : 1
      }
    },
    "recall" : {
      "value" : 1.0,
      "standard_deviation" : "NaN"
    },
    "precision" : {
      "value" : 0.3333333333333333,
      "standard_deviation" : "NaN"
    },
    "accuracy" : {
      "value" : 0.5,
      "standard_deviation" : "NaN"
    },
    "recall_best_constant_classifier" : {
      "value" : 1.0,
      "standard_deviation" : "NaN"
    },
    "precision_best_constant_classifier" : {
      "value" : 0.25,
      "standard_deviation" : "NaN"
    },
    "accuracy_best_constant_classifier" : {
      "value" : 0.25,
      "standard_deviation" : "NaN"
    },
    "true_positive_rate" : {
      "value" : 1.0,
      "standard_deviation" : "NaN"
    },
    "true_negative_rate" : {
      "value" : 0.33333333333333337,
      "standard_deviation" : "NaN"
    },
    "false_positive_rate" : {
      "value" : 0.6666666666666666,
      "standard_deviation" : "NaN"
    },
    "false_negative_rate" : {
      "value" : 0.0,
      "standard_deviation" : "NaN"
    },
    "receiver_operating_characteristic_curve" : {
      "false_positive_rates" : [ 0.0, 0.0, 0.0, 0.0, 0.0, 1.0 ],
      "true_positive_rates" : [ 0.0, 0.25, 0.5, 0.75, 1.0, 1.0 ]
    },
    "precision_recall_curve" : {
      "precisions" : [ 1.0, 1.0, 1.0, 1.0, 1.0 ],
      "recalls" : [ 0.0, 0.25, 0.5, 0.75, 1.0 ]
    },
    "auc" : {
      "value" : 1.0,
      "standard_deviation" : "NaN"
    },
    "f0_5" : {
      "value" : 0.3846153846153846,
      "standard_deviation" : "NaN"
    },
    "f1" : {
      "value" : 0.5,
      "standard_deviation" : "NaN"
    },
    "f2" : {
      "value" : 0.7142857142857143,
      "standard_deviation" : "NaN"
    },
    "f0_5_best_constant_classifier" : {
      "value" : 0.29411764705882354,
      "standard_deviation" : "NaN"
    },
    "f1_best_constant_classifier" : {
      "value" : 0.4,
      "standard_deviation" : "NaN"
    },
    "f2_best_constant_classifier" : {
      "value" : 0.625,
      "standard_deviation" : "NaN"
    }
  }
```

## 多類別指標
<a name="model-monitor-model-quality-metrics-multi"></a>

以下顯示模型品質監控針對多類別分類問題所計算的指標範例。

```
"multiclass_classification_metrics" : {
    "confusion_matrix" : {
      "0" : {
        "0" : 1180,
        "1" : 510
      },
      "1" : {
        "0" : 268,
        "1" : 138
      }
    },
    "accuracy" : {
      "value" : 0.6288167938931297,
      "standard_deviation" : 0.00375663881299405
    },
    "weighted_recall" : {
      "value" : 0.6288167938931297,
      "standard_deviation" : 0.003756638812994008
    },
    "weighted_precision" : {
      "value" : 0.6983172269629505,
      "standard_deviation" : 0.006195912915307507
    },
    "weighted_f0_5" : {
      "value" : 0.6803947317178771,
      "standard_deviation" : 0.005328406973561699
    },
    "weighted_f1" : {
      "value" : 0.6571162346664904,
      "standard_deviation" : 0.004385008075019733
    },
    "weighted_f2" : {
      "value" : 0.6384024354394601,
      "standard_deviation" : 0.003867109755267757
    },
    "accuracy_best_constant_classifier" : {
      "value" : 0.19370229007633588,
      "standard_deviation" : 0.0032049848450732355
    },
    "weighted_recall_best_constant_classifier" : {
      "value" : 0.19370229007633588,
      "standard_deviation" : 0.0032049848450732355
    },
    "weighted_precision_best_constant_classifier" : {
      "value" : 0.03752057718081697,
      "standard_deviation" : 0.001241536088657851
    },
    "weighted_f0_5_best_constant_classifier" : {
      "value" : 0.04473443104152011,
      "standard_deviation" : 0.0014460485504284792
    },
    "weighted_f1_best_constant_classifier" : {
      "value" : 0.06286421244683643,
      "standard_deviation" : 0.0019113576884608862
    },
    "weighted_f2_best_constant_classifier" : {
      "value" : 0.10570313141262414,
      "standard_deviation" : 0.002734216826748117
    }
  }
```

## 使用 CloudWatch 指標監控模型品質
<a name="model-monitor-model-quality-cw"></a>

如果您在建立監控排程時，將 `enable_cloudwatch_metrics` 的值設為 `True`，模型品質監控工作會將所有指標傳送至 CloudWatch。

模型品質指標使用下列命名空間顯示：
+ 對於即時端點：`aws/sagemaker/Endpoints/model-metrics`
+ 對於批次轉換工作：`aws/sagemaker/ModelMonitoring/model-metrics`

如需所發出指標的清單，請參閱此頁面的上一節。

當特定指標不符合您指定的閾值時，您可以使用 CloudWatch 指標來建立警示。如需如何建立 CloudWatch 警示的相關指示，請參閱《CloudWatch 使用者指南》**中的[建立以靜態閾值為基礎的 CloudWatch 警示](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ConsoleAlarms.html)。

# 生產中模型的偏差偏離
<a name="clarify-model-monitor-bias-drift"></a>

Amazon SageMaker Clarify 偏差監控可協助資料科學家和機器學習 (ML) 工程師定期監控偏差的預測。當模型受到監控時，客戶可以在 SageMaker Studio 中檢視可匯出的報告和圖表以了解偏差詳細資料，並在 Amazon CloudWatch 中設定警示以便在偵測到超出特定閾值的偏差時接收通知。當訓練資料與部署期間模型所看到的資料 (也就是即時資料) 不同時，可能會在部署的機器學習 (ML) 模型中導致或加劇偏差。即時資料分佈中這些類型的變更可能是暫時性的 (例如，由於某些短暫、真實世界的事件)或永久性的。無論哪種情況，偵測這些變更都很重要。例如，如果用於訓練模型的抵押貸款利率與目前真實世界的抵押貸款利率不同，則用於預測房屋價格的模型輸出可能會變得偏差。透過 Model Monitor 中的偏差偵測功能，當 SageMaker AI 偵測到超過特定閾值的偏差時，會自動產生您在 SageMaker Studio 中以及透過 Amazon CloudWatch 警示可以檢視的指標。

一般而言，僅在訓練和部署階段測量偏差可能不足。部署模型之後，部署模型所看到的資料分佈 (也就是即時資料) 可能與訓練資料集中的資料分佈不同。在一段時間後，此變更可能會導致模型中的偏差。即時資料分佈的變更可能是暫時的 (例如，由於某些短暫的行為，如假期節日) 或永久性的。無論哪種情況，偵測這些變更並在適當時採取措施以減少偏差很重要。

為了偵測這些變更，SageMaker Clarify 提供持續監控已部署模型的偏差指標的功能，並在指標超過閾值時提出自動警示。例如，考量 DPPL 偏差指標。指定允許的值範圍 A=(amin​,amax​)，例如 DPPL 在部署期間應屬於的間隔 (-0.1, 0.1)。此範圍之間的任何偏差都應提出*偵測到偏差*的警示。使用 SageMaker Clarify，您可以定期執行這些檢查。

例如，您可以將檢查頻率設為 2 天。這表示 SageMaker Clarify 會根據 2 天期間內收集的資料來計算 DPPL 指標。在此範例中，Dwin 是模型在過去 2 天期間內處理的資料。如果在 Dwin​ 上計算的 DPPL 值 bwin​ 超出允許的範圍 A，則會發出警示。檢查 bwin 是否超出 A 的這種方法可能會有些嘈雜。Dwin​ 可能由極少數樣本組成，並且可能不代表即時資料分佈。小型樣本意味著在 Dwin​ 上計算的偏差 bwin​ 值可能不是非常強大的估計值。事實上，非常高 (或低) 的 bwin 值可能純粹是由於機會而觀察到的。為了確保從觀察到的資料 Dwin 得出的結論在統計上具有顯著性，SageMaker Clarify 使用信賴區間。具體而言，它會使用一般引導區間方法來建構區間 C=(cmin​,cmax​)，如此 SageMaker Clarify 可確信透過完整即時資料計算的真正偏差值會以高可能性包含在 C 中。現在，如果信賴區間 C 與允許的範圍 A 重疊，SageMaker Clarify 會將其解譯為 “即時資料分佈的偏差指標值很可能落在允許的範圍內”。如果 C 和 A 是脫離的，則 SageMaker Clarify 可確信偏差指標不在 A 中並提出警示。

## 模型監控取樣筆記本
<a name="clarify-model-monitor-sample-notebooks-bias-drift"></a>

Amazon SageMaker Clarify 提供下列取樣筆記本，其中顯示如何擷取即時端點的推論資料、建立基準以監控不斷發展的偏差，以及檢查結果：
+ [監控偏差偏離和功能屬性偏離 Amazon SageMaker Clarify](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_model_monitor/fairness_and_explainability/SageMaker-Model-Monitor-Fairness-and-Explainability.html) – 使用 Amazon SageMaker Model Monitor 來監控一段時間後的偏差偏離和功能屬性偏離。

此筆記本已通過驗證，只能在 Amazon SageMaker Studio 中執行。如果您需要有關如何在 Amazon SageMaker Studio 中打開筆記本的說明，請參閱[建立或開啟 Amazon SageMaker Studio Classic 筆記本](notebooks-create-open.md)。如果系統提示您選擇核心，請選擇 **Python 3 (資料科學)**。下列主題包含最後兩個步驟的重點內容，其中包含範例筆記本的程式碼範例。

**Topics**
+ [模型監控取樣筆記本](#clarify-model-monitor-sample-notebooks-bias-drift)
+ [建立偏差偏離基準](clarify-model-monitor-bias-drift-baseline.md)
+ [偏差偏離違規](clarify-model-monitor-bias-drift-violations.md)
+ [要監控偏差偏離的參數](clarify-config-json-monitor-bias-parameters.md)
+ [排定偏差偏離監控工作](clarify-model-monitor-bias-drift-schedule.md)
+ [檢查報告中的資料偏差偏離](clarify-model-monitor-bias-drift-report.md)
+ [偏差偏離分析的 CloudWatch 指標](clarify-model-monitor-bias-drift-cw.md)

# 建立偏差偏離基準
<a name="clarify-model-monitor-bias-drift-baseline"></a>

將應用程式設定為擷取即時或批次轉換推論資料之後，監控偏差偏離的第一項任務是建立基準。這包括設定資料輸入、哪些群組是敏感的、如何擷取預測，以及模型及其訓練後的偏差指標。然後，您需要開始進行基準工作。

模型偏差監控可定期偵測機器學習 (ML) 模型的偏差偏離。與其他監控類型相似，建立模型偏差監控的標準程序首先是基準化，然後再建立監控排程。

```
model_bias_monitor = ModelBiasMonitor(
    role=role,
    sagemaker_session=sagemaker_session,
    max_runtime_in_seconds=1800,
)
```

`DataConfig` 會儲存要分析之資料集的相關資訊 (例如，資料集檔案)、其格式 (亦即 CSV 或 JSON 行)、標題 (如果有的話) 和標籤。

```
model_bias_baselining_job_result_uri = f"{baseline_results_uri}/model_bias"
model_bias_data_config = DataConfig(
    s3_data_input_path=validation_dataset,
    s3_output_path=model_bias_baselining_job_result_uri,
    label=label_header,
    headers=all_headers,
    dataset_type=dataset_type,
)
```

`BiasConfig` 是資料集中敏感群組的組態。一般而言，偏差是透過計算指標並跨群組進行比較來衡量。感興趣的群組稱為*構面*。對於訓練後的偏差，您還應該考慮正面的標籤。

```
model_bias_config = BiasConfig(
    label_values_or_threshold=[1],
    facet_name="Account Length",
    facet_values_or_threshold=[100],
)
```

`ModelPredictedLabelConfig` 會指定如何從模型輸出擷取預測標籤。在此範例中，選擇 0.8 截止值是為了預期客戶會經常流動。對於更複雜的輸出，還有幾個選項，例如 “label” 是索引、名稱或 JMESPath，以在端點回應承載中定位預測標籤。

```
model_predicted_label_config = ModelPredictedLabelConfig(
    probability_threshold=0.8,
)
```

`ModelConfig` 是與要用於推論的模型相關的組態。為了計算訓練後的偏差指標，計算需要取得所提供的模型名稱的推論。為了完成此作業，處理任務會使用模型來建立暫時性端點 (也稱為*陰影端點*)。處理任務會在計算完成後刪除陰影端點。可解釋性監控也會使用此組態。

```
model_config = ModelConfig(
    model_name=model_name,
    instance_count=endpoint_instance_count,
    instance_type=endpoint_instance_type,
    content_type=dataset_type,
    accept_type=dataset_type,
)
```

現在，您可以開始基準工作。

```
model_bias_monitor.suggest_baseline(
    model_config=model_config,
    data_config=model_bias_data_config,
    bias_config=model_bias_config,
    model_predicted_label_config=model_predicted_label_config,
)
print(f"ModelBiasMonitor baselining job: {model_bias_monitor.latest_baselining_job_name}")
```

排程的監控會自動挑選基準作業名稱，並等待它，然後再開始監控。

# 偏差偏離違規
<a name="clarify-model-monitor-bias-drift-violations"></a>

偏差偏離工作會根據目前 `MonitoringExecution` 的分析結果，評估[基準組態](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelBiasJobDefinition.html#sagemaker-CreateModelBiasJobDefinition-request-ModelBiasBaselineConfig)提供的基準限制條件。如果偵測到違規，工作會將其列於執行輸出位置中的 *constraint\$1violations.json* 檔案，並將執行狀態標記為 [解讀結果](model-monitor-interpreting-results.md)。

以下是偏差偏離違規檔案的結構描述。
+ `facet` – 構面的名稱，由監控工作分析組態構面 `name_or_index` 提供。
+ `facet_value` – 構面的值，由監控工作分析組態構面 `value_or_threshold` 提供。
+ `metric_name` – 偏差指標的簡短名稱。例如，“CI” 表示類別不平衡。如需每個訓練前偏差指標的簡短名稱，請參閱[訓練前偏差指標](clarify-measure-data-bias.md)，如需每個訓練後偏差指標的簡短名稱，請參閱[訓練後資料和模型偏差指標](clarify-measure-post-training-bias.md)。
+ `constraint_check_type` – 監控的違規類型。目前僅支援 `bias_drift_check`。
+ `description` – 說明違規的描述訊息。

```
{
    "version": "1.0",
    "violations": [{
        "facet": "string",
        "facet_value": "string",
        "metric_name": "string",
        "constraint_check_type": "string",
        "description": "string"
    }]
}
```

偏差指標用於測量分佈中的相等程度。接近零的值表示分佈較為平衡。如果工作分析結果檔案 (analysis.json) 中偏差指標的值低於其在基準限制檔案中的對應值，則會記錄違規。例如，如果 DPPL 偏差指標的基準限制條件為 `0.2`，且分析結果為 `0.1`，則不會記錄違規，因為 `0.1` 比 `0.2` 更接近 `0`。但是，如果分析結果為 `-0.3`，則會記錄違規，因為比 `0.2` 的基準限制條件更遠於 `0`。

```
{
    "version": "1.0",
    "violations": [{
        "facet": "Age",
        "facet_value": "40",
        "metric_name": "CI",
        "constraint_check_type": "bias_drift_check",
        "description": "Value 0.0751544567666083 does not meet the constraint requirement"
    }, {
        "facet": "Age",
        "facet_value": "40",
        "metric_name": "DPPL",
        "constraint_check_type": "bias_drift_check",
        "description": "Value -0.0791244970125596 does not meet the constraint requirement"
    }]
}
```

# 要監控偏差偏離的參數
<a name="clarify-config-json-monitor-bias-parameters"></a>

Amazon SageMaker Clarify 偏差監控會重複使用 [分析組態檔案](clarify-processing-job-configure-analysis.md) 的分析組態中使用的參數子集。說明組態參數之後，本主題將提供 JSON 檔案的範例。這些檔案可用來設定 CSV 和 JSON 行資料集，在機器學習模型進行生產時監控是否有偏差偏離。

JSON 檔案必須提供下列參數。此 JSON 檔案的路徑必須在 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelBiasAppSpecification](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelBiasAppSpecification) API 的 `ConfigUri` 參數中提供。
+ `"version"` –(選用) 組態檔案的結構描述版本。如果未提供，則會使用最新的支援版本。
+ `"headers"` –(選用) 資料集中的欄位名稱清單。如果 `dataset_type` 為 `"label"` 並已指定 `"application/jsonlines"`，則最後一個標題將成為標籤欄的標題。
+ `"label"` –(選用) 要用於*偏差指標*之模型的目標屬性。指定為資料欄名稱或索引 (如果資料集格式為 CSV)，或指定為 JMESPath( 如果資料集格式為 JSON 行)。
+ `"label_values_or_threshold"` –(選用) 標籤值或閾值的清單。表示用於偏差指標的正面結果。
+ `"facet"` –(選用) 屬於敏感屬性的功能清單，稱為構面。構面以配對形式用於*偏差指標*，並包括以下內容：
  + `"name_or_index"` – 構面欄名稱或索引。
  + `"value_or_threshold"` –(選用) 構面欄可採用的值或閾值清單。表示敏感群組，例如用來測量偏差的群組。如果未提供，偏差指標會將每個唯一值 (而非所有值) 計算為一個群組。如果構面欄為數值，則會套用此閾值為下限以選取敏感群組。
+ `"group_variable"` – (選用) 欄名稱或索引，用來指出要用於*偏差指標**條件人口統計差異*的群組變數。

其他參數應在 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelBiasJobInput](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelBiasJobInput) API 的 `EndpointInput` (用於即時端點) 或 `BatchTransformInput` (用於批次轉換工作) 中提供。
+ `FeaturesAttribute` – 如果端點輸入資料格式為 `"application/jsonlines"`，則此參數是必要項目。如果資料集格式是 JSON 行，它是用於定位功能欄的 JMESPath。
+ `InferenceAttribute` – 目標屬性的模型輸出中的索引或 JMESPath 位置，用於使用偏差指標來監控偏差。如果在 CSV `accept_type` 案例中未提供，則假設模型輸出是對應於分數或機率的單一數值。
+ `ProbabilityAttribute` – 機率的模型輸出中的索引或 JMESPath 位置。例如，如果模型輸出是含有標籤和機率清單的 JSON 行，則會選擇對應於最大機率的標籤進行偏差運算。
+ `ProbabilityThresholdAttribute` –(選用) 浮點值，用來指示在二進制分類的情況下選取二進位標籤的閾值。預設值為 0.5。

## CSV 和 JSON 行資料集的 JSON 組態檔案範例
<a name="clarify-config-json-monitor-bias-parameters-examples"></a>

以下是 JSON 檔案的範例，用來設定 CSV 和 JSON 行資料集以監控偏差偏離。

**Topics**
+ [CSV 資料集](#clarify-config-json-monitor-bias-parameters-example-csv)
+ [JSON 行資料集](#clarify-config-json-monitor-bias-parameters-example-jsonlines)

### CSV 資料集
<a name="clarify-config-json-monitor-bias-parameters-example-csv"></a>

考慮有四個功能欄和一個標籤欄的資料集，其中第一個功能和標籤是二進位，如下列範例所示。

```
0, 0.5814568701544718, 0.6651538910132964, 0.3138080342665499, 0
1, 0.6711642728531724, 0.7466687034026017, 0.1215477472819713, 1
0, 0.0453256543003371, 0.6377430803264152, 0.3558625219713576, 1
1, 0.4785191813363956, 0.0265841045263860, 0.0376935084990697, 1
```

假設模型輸出有兩欄，其中第一個是預測標籤，第二個是機率，如下列範例所示。

```
1, 0.5385257417814224
```

接著，下列 JSON 組態檔案會顯示如何設定此 CSV 資料集的範例。

```
{
    "headers": [
        "feature_0",
        "feature_1",
        "feature_2",
        "feature_3",
        "target"
    ],
    "label": "target",
    "label_values_or_threshold": [1],
    "facet": [{
        "name_or_index": "feature_1",
        "value_or_threshold": [1]
    }]
}
```

預測標籤由 `"InferenceAttribute"` 參數選取。使用從零開始的編號，因此 0 表示模型輸出的首欄，

```
"EndpointInput": {
    ...
    "InferenceAttribute": 0
    ...
}
```

或者，您可以使用不同的參數將機率值轉換為二進位預測標籤。使用從零開始的編號：1 表示第二欄；`ProbabilityThresholdAttribute` 值 0.6 表示大於 0.6 的機率會將二進位標籤預測為 1。

```
"EndpointInput": {
    ...
    "ProbabilityAttribute": 1,
    "ProbabilityThresholdAttribute": 0.6
    ...
}
```

### JSON 行資料集
<a name="clarify-config-json-monitor-bias-parameters-example-jsonlines"></a>

考慮有四個功能欄和一個標籤欄的資料集，其中第一個功能和標籤是二進位，如下列範例所示。

```
{"features":[0, 0.5814568701544718, 0.6651538910132964, 0.3138080342665499], "label":0}
{"features":[1, 0.6711642728531724, 0.7466687034026017, 0.1215477472819713], "label":1}
{"features":[0, 0.0453256543003371, 0.6377430803264152, 0.3558625219713576], "label":1}
{"features":[1, 0.4785191813363956, 0.0265841045263860, 0.0376935084990697], "label":1}
```

假設模型輸出有兩欄，其中第一個是預測標籤，第二個是機率。

```
{"predicted_label":1, "probability":0.5385257417814224}
```

下列 JSON 組態檔案會顯示如何設定此 JSON 行資料集的範例。

```
{
    "headers": [
        "feature_0",
        "feature_1",
        "feature_2",
        "feature_3",
        "target"
    ],
    "label": "label",
    "label_values_or_threshold": [1],
    "facet": [{
        "name_or_index": "feature_1",
        "value_or_threshold": [1]
    }]
}
```

然後，`EndpointInput` 中的 `"features"` 參數值 (針對即時端點) 或 `BatchTransformInput` (針對批次轉換工作) 用於訂位資料集中的功能，而 `"predicted_label"` 參數值會從模型輸出中選取預測標籤。

```
"EndpointInput": {
    ...
    "FeaturesAttribute": "features",
    "InferenceAttribute": "predicted_label"
    ...
}
```

或者，您可以使用 `ProbabilityThresholdAttribute` 參數值將機率值轉換為預測的二進位標籤。例如，0.6 的值表示大於 0.6 的的機率會預測二進位標籤為 1。

```
"EndpointInput": {
    ...
    "FeaturesAttribute": "features",
    "ProbabilityAttribute": "probability",
    "ProbabilityThresholdAttribute": 0.6
    ...
}
```

# 排定偏差偏離監控工作
<a name="clarify-model-monitor-bias-drift-schedule"></a>

建立基準之後，您可以呼叫 `ModelBiasModelMonitor` 類別執行個體的 `create_monitoring_schedule()` 方法來排程每小時的偏差偏離監控。以下各節說明如何為部署到即時端點的模型以及批次轉換工作建立偏差偏離監控。

**重要**  
在建立監控排程時，您可以指定批次轉換輸入或端點輸入，但不能同時指定兩者。

與資料品質監控不同，如果要監控模型品質，需要提供 Ground Truth 標籤。但是，Ground Truth 標籤可能會延遲。若要解決此問題，請在建立監控排程時指定偏移。如需有關如何建立時間位移的詳細資訊，請參閱[模型監控偏移](model-monitor-model-quality-schedule.md#model-monitor-model-quality-schedule-offsets)。

如果您已提交基準工作，監控會自動從基準工作中挑選分析組態。如果您略過基準步驟，或擷取資料集的性質與訓練資料集的性質不同，則必須提供分析組態。

## 部署至即時端點的模型的偏差偏離監控
<a name="model-monitor-bias-quality-rt"></a>

若要為即時端點排程偏差偏離監控，請將 `EndpointInput` 執行個體傳遞至 `ModelBiasModelMonitor` 執行個體的 `endpoint_input` 引數，如下列程式碼範例所示：

```
from sagemaker.model_monitor import CronExpressionGenerator
            
model_bias_monitor = ModelBiasModelMonitor(
    role=sagemaker.get_execution_role(),
    ...
)

model_bias_analysis_config = None
if not model_bias_monitor.latest_baselining_job:
    model_bias_analysis_config = BiasAnalysisConfig(
        model_bias_config,
        headers=all_headers,
        label=label_header,
    )

model_bias_monitor.create_monitoring_schedule(
    monitor_schedule_name=schedule_name,
    post_analytics_processor_script=s3_code_postprocessor_uri,
    output_s3_uri=s3_report_path,
    statistics=model_bias_monitor.baseline_statistics(),
    constraints=model_bias_monitor.suggested_constraints(),
    schedule_cron_expression=CronExpressionGenerator.hourly(),
    enable_cloudwatch_metrics=True,
    analysis_config=model_bias_analysis_config,
    endpoint_input=EndpointInput(
        endpoint_name=endpoint_name,
        destination="/opt/ml/processing/input/endpoint",
        start_time_offset="-PT1H",
        end_time_offset="-PT0H",
        probability_threshold_attribute=0.8,
    ),
)
```

## 批次轉換工作的偏差偏離監控
<a name="model-monitor-bias-quality-bt"></a>

若要為批次轉換工作排程偏差偏離監控，請將 `BatchTransformInput` 執行個體傳遞至 `ModelBiasModelMonitor` 執行個體的 `batch_transform_input` 引數，如下列程式碼範例所示：

```
from sagemaker.model_monitor import CronExpressionGenerator
                
model_bias_monitor = ModelBiasModelMonitor(
    role=sagemaker.get_execution_role(),
    ...
)

model_bias_analysis_config = None
if not model_bias_monitor.latest_baselining_job:
    model_bias_analysis_config = BiasAnalysisConfig(
        model_bias_config,
        headers=all_headers,
        label=label_header,
    )
    
schedule = model_bias_monitor.create_monitoring_schedule(
   monitor_schedule_name=schedule_name,
   post_analytics_processor_script=s3_code_postprocessor_uri,
   output_s3_uri=s3_report_path,
   statistics=model_bias_monitor.baseline_statistics(),
   constraints=model_bias_monitor.suggested_constraints(),
   schedule_cron_expression=CronExpressionGenerator.hourly(),
   enable_cloudwatch_metrics=True,
   analysis_config=model_bias_analysis_config,
   batch_transform_input=BatchTransformInput(
        destination="opt/ml/processing/input",
        data_captured_destination_s3_uri=s3_capture_path,
        start_time_offset="-PT1H",
        end_time_offset="-PT0H",
        probability_threshold_attribute=0.8
   ),
)
```

# 檢查報告中的資料偏差偏離
<a name="clarify-model-monitor-bias-drift-report"></a>

如果您無法在 SageMaker Studio 中所產生的報告中檢查監控結果，您可以將其列印出來，如下所示：

```
schedule_desc = model_bias_monitor.describe_schedule()
execution_summary = schedule_desc.get("LastMonitoringExecutionSummary")
if execution_summary and execution_summary["MonitoringExecutionStatus"] in ["Completed", "CompletedWithViolations"]:
    last_model_bias_monitor_execution = model_bias_monitor.list_executions()[-1]
    last_model_bias_monitor_execution_report_uri = last_model_bias_monitor_execution.output.destination
    print(f'Report URI: {last_model_bias_monitor_execution_report_uri}')
    last_model_bias_monitor_execution_report_files = sorted(S3Downloader.list(last_model_bias_monitor_execution_report_uri))
    print("Found Report Files:")
    print("\n ".join(last_model_bias_monitor_execution_report_files))
else:
    last_model_bias_monitor_execution = None
    print("====STOP==== \n No completed executions to inspect further. Please wait till an execution completes or investigate previously reported failures.")
```

 如果與基準相比存在違規，則會在此列出：

```
if last_model_bias_monitor_execution:
    model_bias_violations = last_model_bias_monitor_execution.constraint_violations()
    if model_bias_violations:
        print(model_bias_violations.body_dict)
```

如果您的模型部署到即時端點，您可以選擇**端點**索引標籤，然後按兩下端點，在 SageMaker AI Studio 中查看分析結果和 CloudWatch 指標的視覺效果。

# 偏差偏離分析的 CloudWatch 指標
<a name="clarify-model-monitor-bias-drift-cw"></a>

本指南顯示可在 SageMaker Clarify 中用於偏差偏離分析的 CloudWatch 指標及其屬性。偏差偏離監控工作會計算[訓練前偏差指標](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-measure-data-bias.html)和[訓練後偏差指標](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-measure-post-training-bias.html)，並將其發佈到下列 CloudWatch 命名空間：
+ 對於即時端點：`aws/sagemaker/Endpoints/bias-metrics`
+ 對於批次轉換工作：`aws/sagemaker/ModelMonitoring/bias-metrics`

CloudWatch 指標名稱會將指標的簡短名稱附加至 `bias_metric`。

例如，`bias_metric_CI` 是類別不平衡 (CI) 的偏差指標。

**注意**  
`+/- infinity` 發佈為浮點數 `+/- 2.348543e108`，而包括 null 值的錯誤不會發佈。

每個指標都具有下列屬性：
+ `Endpoint`：受監控端點的名稱(如果適用)。
+ `MonitoringSchedule`：監控工作排程的名稱。
+ `BiasStage`：偏差偏離監控工作的階段名稱。選擇 `Pre-training` 或 `Post-Training`。
+ `Label`：目標功能的名稱，由監控工作分析組態 `label` 提供。
+ `LabelValue`：目標功能的值，由監控工作分析組態 `label_values_or_threshold` 提供。
+ `Facet`：構面的名稱，由監控工作分析組態構面 `name_of_index` 提供。
+ `FacetValue`：構面的值，由監控工作分析組態構面 `nvalue_or_threshold` 提供。

若要停止發佈指標的監控工作，請在[模型偏差工作](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelBiasJobDefinition.html)定義的 `Environment` 對應中將 `publish_cloudwatch_metrics` 設定為 `Disabled`。

# 生產中模型的特徵屬性偏離
<a name="clarify-model-monitor-feature-attribution-drift"></a>

生產中模型的即時資料分佈偏離可能會導致功能屬性值中對應的偏離，就像在監控偏差指標時可能會導致偏差偏離一樣。Amazon SageMaker Clarify 功能屬性監控可協助資料科學家和機器學習 (ML) 工程師定期監控功能屬性偏離的預測。當模型受到監控時，客戶可以在 SageMaker Studio 中檢視可匯出的報告和圖表以詳細說明功能屬性，並在 Amazon CloudWatch 中設定警示以便在偵測到屬性值偏離超過特定閾值時接收通知。

為了用具體情況來說明這一點，請假設一個大學入學的情況。假設我們在訓練資料和即時資料中觀察到下列 (彙總) 功能屬性值：

大學入學假設情況


| 功能 | 訓練資料中的屬性 | 即時資料中的屬性 | 
| --- | --- | --- | 
| SAT 分數 | 0.70 | 0.10 | 
| GPA | 0.50 | 0.20 | 
| 班級排名 | 0.05 | 0.70 | 

從訓練資料到即時資料的變更看起來顯著。功能排名已完全顛倒。與偏差偏離類似，功能屬性偏離可能是由於即時資料分佈的變更所造成，並保證仔細研究即時資料上的模型行為。同樣地，在這些情況下的第一步是提出偏離已發生的警示。

我們可以透過比較從訓練資料到即時資料的各個功能排名如何變更來偵測偏離。除了對排名順序的變更敏感之外，我們還希望對功能的原始屬性分數敏感。舉例來說，假設在排名中的兩個功能從訓練到即時資料的名次都相同，則我們希望對訓練資料中屬性分數較高的功能更加敏感。考慮到這些屬性，我們會使用標準化折扣累計收益 (NDCG) 分數來比較訓練和即時資料的功能屬性排名。

具體來說，假設我們有以下情況：
+ *F=[f1​,…,fm​] * 是在訓練資料中根據其屬性分數排序的功能清單，其中 *m* 是功能總數。例如，在我們的情況下，*F*=[SAT 分數, GPA, 班級排名]。
+ *a(f)* 是在特定功能 *f* 的訓練資料上傳回功能屬性分數的函式。例如，*a*(SAT 分數) = 0.70。
+ *F′=[f′​1​, …, f′​m​] *是根據即時資料中的屬性分數排序的功能清單。例如，*F*′= [班級排名, GPA, SAT 分數]。

然後，我們可以將 NDCG 計算為：

        NDCG=DCG/iDCG​

取代為 
+ DCG = ∑1m*a*(*f'i*)/log2​(*i*\$11)
+ iDCG = ∑1m*a*(*fi*)/log2​(*i*\$11)

數量 DCG 會測量訓練資料中具有高屬性的功能是否也會在即時資料中計算的功能屬性中排名較高。數量 iDCG 會測量*理想分數*，它只是一個正常化係數，以確保最終數量駐留在範圍 [0, 1] 內，其中 1 是最佳的可能值。NDCG 值為 1 表示即時資料中的功能屬性排名與訓練資料中的功能屬性排名相同。在此特定範例中，由於排名變更了很多，因此 NDCG 值為 0.69。

在 SageMaker Clarify 中，如果 NDCG 值低於 0.90，我們會自動提出警示。

## 模型監控範例筆記本
<a name="clarify-model-monitor-sample-notebooks-feature-drift"></a>

SageMaker Clarify 提供下列範例筆記本，其中顯示如何擷取即時端點的推論資料、建立基準以監控不斷發展的偏差，以及檢查結果：
+ [監控偏差偏離和功能屬性偏離 Amazon SageMaker Clarify](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_model_monitor/fairness_and_explainability/SageMaker-Model-Monitor-Fairness-and-Explainability.html) – 使用 Amazon SageMaker Model Monitor 來監控一段時間後的偏差偏離和功能屬性偏離。

此筆記本已通過驗證，只能在 SageMaker Studio 中執行。如果您需要有關如何在 SageMaker Studio 中打開筆記本的說明，請參閱[建立或開啟 Amazon SageMaker Studio Classic 筆記本](notebooks-create-open.md)。如果系統提示您選擇核心，請選擇 **Python 3 (資料科學)**。下列主題包含最後兩個步驟的重點內容，其中包含範例筆記本的程式碼範例。

**Topics**
+ [模型監控範例筆記本](#clarify-model-monitor-sample-notebooks-feature-drift)
+ [為生產中的模型建立 SHAP 基準](clarify-model-monitor-shap-baseline.md)
+ [模型功能屬性偏離違規](clarify-model-monitor-model-attribution-drift-violations.md)
+ [要監控屬性偏離的參數](clarify-config-json-monitor-model-explainability-parameters.md)
+ [排程功能屬性偏離監控工作](clarify-model-monitor-feature-attribute-drift-schedule.md)
+ [檢查生產模型中功能屬性偏離的報告](clarify-feature-attribute-drift-report.md)
+ [功能偏離分析的 CloudWatch 指標](clarify-feature-attribute-drift-cw.md)

# 為生產中的模型建立 SHAP 基準
<a name="clarify-model-monitor-shap-baseline"></a>

解釋通常是相反的 (也就是說，它們說明偏離基準的情況)。如需可解釋性基準的資訊，請參閱[用於可解釋性的 SHAP 基準](clarify-feature-attribute-shap-baselines.md)。

除了針對每個執行個體推論提供說明之外，SageMaker Clarify 也支援機器學習 (ML) 模型的全域說明，協助您根據模型的功能來瞭解整個模型的行為。SageMaker Clarify 透過彙總多個執行個體的 Shapley 值，產生機器學習 (ML) 模型的全域說明。SageMaker Clarify 支援下列不同的彙總方式，您可以使用這些方式來定義基準：
+ `mean_abs` – 所有執行個體的絕對 SHAP 值的平均值。
+ `median` – 所有執行個體的 SHAP 值的中間值。
+ `mean_sq` – 所有執行個體的平方 SHAP 值的平均值。

將應用程式設定為擷取即時或批次轉換推論資料之後，監控功能屬性偏離的第一項任務就是建立要比較的基準。這包括設定資料輸入、哪些群組是敏感的、如何擷取預測，以及模型及其訓練後的偏差指標。然後，您需要開始進行基準工作。模型可解釋性監控可以解釋已部署模型的預測，該模型會產生推論並定期偵測功能屬性偏離。

```
model_explainability_monitor = ModelExplainabilityMonitor(
    role=role,
    sagemaker_session=sagemaker_session,
    max_runtime_in_seconds=1800,
)
```

在這個範例中，可解釋性基準工作與偏差基準工作共用測試資料集，因此它使用相同的 `DataConfig`，唯一的差異是任務輸出 URI。

```
model_explainability_baselining_job_result_uri = f"{baseline_results_uri}/model_explainability"
model_explainability_data_config = DataConfig(
    s3_data_input_path=validation_dataset,
    s3_output_path=model_explainability_baselining_job_result_uri,
    label=label_header,
    headers=all_headers,
    dataset_type=dataset_type,
)
```

目前 SageMaker Clarify 解釋器提供了 SHAP 的可擴展性和高效，因此可解釋性組態是 ShapConfig，包括以下內容：
+ `baseline` – 要在核心 SHAP 演算法中用作基準資料集的資料列 (至少一個) 或 S3 物件 URI 的清單。此格式應與資料集格式相同。每一列應該只包含功能欄/值，並省略標籤欄/值。
+ `num_samples` – 要在核心 SHAP 演算法中使用的樣本數。此數字決定產生的合成資料集的大小來計算 SHAP 值。
+ agg\$1method — 全域 SHAP 值的彙總方法。以下為有效值：
  + `mean_abs` – 所有執行個體的絕對 SHAP 值的平均值。
  + `median` – 所有執行個體的 SHAP 值的中間值。
  + `mean_sq` – 所有執行個體的平方 SHAP 值的平均值。
+ `use_logit` – 是否將 logit 函式套用於模型預測的指示器。預設值為 `False`。如果 `use_logit` 是 `True`，SHAP 值將有對數機率單位。
+ `save_local_shap_values` (bool) – 是否將本機 SHAP 值儲存在輸出位置的指示器。預設值為 `False`。

```
# Here use the mean value of test dataset as SHAP baseline
test_dataframe = pd.read_csv(test_dataset, header=None)
shap_baseline = [list(test_dataframe.mean())]

shap_config = SHAPConfig(
    baseline=shap_baseline,
    num_samples=100,
    agg_method="mean_abs",
    save_local_shap_values=False,
)
```

開始基準工作。需要相同的 `model_config`，因為可解釋性基準工作需要建立陰影端點以取得產生的合成資料集的預測。

```
model_explainability_monitor.suggest_baseline(
    data_config=model_explainability_data_config,
    model_config=model_config,
    explainability_config=shap_config,
)
print(f"ModelExplainabilityMonitor baselining job: {model_explainability_monitor.latest_baselining_job_name}")
```

# 模型功能屬性偏離違規
<a name="clarify-model-monitor-model-attribution-drift-violations"></a>

功能屬性偏離工作會根據目前 `MonitoringExecution` 的分析結果，評估[基準組態](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelExplainabilityJobDefinition.html#sagemaker-CreateModelExplainabilityJobDefinition-request-ModelExplainabilityBaselineConfig)提供的基準限制條件。如果偵測到違規，工作會將其列於執行輸出位置中的 *constraint\$1violations.json* 檔案，並將執行狀態標記為 [解讀結果](model-monitor-interpreting-results.md)。

以下是功能屬性偏離違規檔案的結構描述。
+ `label` – 標籤名稱、工作分析組態 `label_headers` 或預留位置，例如 `"label0"`。
+ `metric_name` – 可解釋性分析方法的名稱。目前僅支援 `shap`。
+ `constraint_check_type` – 監控的違規類型。目前僅支援 `feature_attribution_drift_check`。
+ `description` – 說明違規的描述訊息。

```
{
    "version": "1.0",
    "violations": [{
        "label": "string",
        "metric_name": "string",
        "constraint_check_type": "string",
        "description": "string"
    }]
}
```

對於 `explanations` 區段中的每個標籤，監控工作會計算其在基準限制檔案和工作分析結果檔案 (*analysis.json*) 中的全域 SHAP 值的 [nDCG 分數](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.ndcg_score.html)。如果分數小於 0.9，會記錄違規。會評估合併的全域 SHAP 值，因此違規項目中沒有 `“feature”` 欄位。下列輸出提供幾個記錄違規的範例。

```
{
    "version": "1.0",
    "violations": [{
        "label": "label0",
        "metric_name": "shap",
        "constraint_check_type": "feature_attribution_drift_check",
        "description": "Feature attribution drift 0.7639720923277322 exceeds threshold 0.9"
    }, {
        "label": "label1",
        "metric_name": "shap",
        "constraint_check_type": "feature_attribution_drift_check",
        "description": "Feature attribution drift 0.7323763972092327 exceeds threshold 0.9"
    }]
}
```

# 要監控屬性偏離的參數
<a name="clarify-config-json-monitor-model-explainability-parameters"></a>

Amazon SageMaker Clarify 可解釋性監控會重複使用 [分析組態檔案](clarify-processing-job-configure-analysis.md) 的分析組態中使用的參數子集。下列參數必須在 JSON 檔案中提供，且必須在 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelExplainabilityAppSpecification](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelExplainabilityAppSpecification) 的 `ConfigUri` 參數中提供路徑。
+ `"version"` –(選用) 組態檔案的結構描述版本。如果未提供，則會使用最新的支援版本。
+ `"headers"` –(選用) 資料集中的功能名稱清單。可解釋性分析不需要標籤。
+ `"methods"` – 用於分析和報告的方法及其參數的清單。如果省略了任何區段，則不列入計算。
  + `"shap"` –(選用) SHAP 值計算的區段。
    + `"baseline"` –(選用) 資料列清單(至少一個)，或 Amazon Simple Storage Service Amazon S3 物件 URI。用作核心 SHAP 演算法中的基準資料集 (也稱為背景資料集)。此格式應與資料集格式相同。每一列應該只包含功能欄 (或值)。在將每一列傳送至模型之前，省略必須排除的任何欄。
    + `"num_samples"` – 要在核心 SHAP 演算法中使用的樣本數。此數字決定產生的合成資料集的大小來計算 SHAP 值。如果未提供，則 SageMaker Clarify 工作會根據功能計數來選擇值。
    + `"agg_method"` – 全域 SHAP 值的彙總方法。有效值如下：
      + `"mean_abs"` – 所有執行個體的絕對 SHAP 值的平均值。
      + `"median"` – 所有執行個體的 SHAP 值的中間值。
      + `"mean_sq"` – 所有執行個體的平方 SHAP 值的平均值。
    + `"use_logit"` –(選用) 布林值，指出 logit 函式是否要套用至模型預測。如果 `"use_logit"` 是 `true`，則 SHAP 值有對數機率單位。預設值為 `false`。
    + `"save_local_shap_values"` –(選用) 布林值，指示是否要將本機 SHAP 值儲存在輸出位置。使用 `true` 以儲存。使用 `false` 不要儲存。預設值為 `false`。
+ `"predictor"` – (即時端點為選用，批次轉換為必要) 模型參數的區段，如果 `"shap"` 和 `"post_training_bias"` 區段存在，則為必要。
  + `"model_name"` – 由 `CreateModel` API 建立的模型名稱，容器模式為 `SingleModel`。
  + `"instance_type"` – 陰影端點的執行個體類型。
  + `"initial_instance_count"` – 陰影端點的執行個體計數。
  + `"content_type"` –(選用) 用於透過陰影端點取得推論的模型輸入格式。有效值為 `"text/csv"` (對於 CSV)、`"application/jsonlines"` (對於 JSON 行)、`application/x-parquet` (對於 Apache Parquet)，以及 `application/x-image` 以啟用電腦視覺可解釋性。預設值與 `dataset_type` 格式相同。
  + `"accept_type"` –(選用) 用於透過陰影端點取得推論的模型*輸出*格式。有效值為 `"text/csv"` (對於 CSV)、`"application/jsonlines"` (對於 JSON 行)。如果省略，SageMaker Clarify 會使用擷取資料的回應資料類型。
  + `"content_template"` –(選用) 用來建構資料集執行個體之模型輸入的範本字串。只有在 `"content_type"` 為 `"application/jsonlines"` 時才會使用。該範本應只有一個預留位置 `$features`，它在執行期時被功能清單取代。例如，指定 `"content_template":"{\"myfeatures\":$features}"`，如果執行個體 (無標籤) 是 `1,2,3`，則模型輸入變為 JSON 行 `'{"myfeatures":[1,2,3]}'`。
  + `"label_headers"` –(選用) 資料集中 `"label"` 接收的值清單。將模型端點或批次轉換工作傳回的分數與其對應的標籤值相關聯。如果有提供，則分析報告會使用標題，而不是像 `“label0”` 的預留位置。

其他參數應在 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelExplainabilityJobInput](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelExplainabilityJobInput) API 的 `EndpointInput` (用於即時端點)或 `BatchTransformInput` (用於批次轉換工作)中提供。
+ `FeaturesAttribute` – 如果端點或批次工作輸入資料格式為 `"application/jsonlines"`，則此參數是必要項目。如果資料集格式是 JSON 行，它是用於定位功能欄的 JMESPath。
+ `ProbabilityAttribute` – 機率的模型輸出中的索引或 JMESPath 位置。例如，如果模型輸出是含有標籤和機率清單的 JSON 行，則會選擇對應於最大機率的標籤進行偏差運算。

## CSV 和 JSON 行資料集的 JSON 組態檔案範例
<a name="clarify-config-json-monitor-model-explainability-parameters-examples"></a>

以下是 JSON 檔案的範例，用來設定 CSV 和 JSON 行資料集以監控功能屬性偏離。

**Topics**
+ [CSV 資料集](#clarify-config-json-monitor-model-explainability-parameters-example-csv)
+ [JSON 行資料集](#clarify-config-json-monitor-model-explainability-parameters-example-jsonlines)

### CSV 資料集
<a name="clarify-config-json-monitor-model-explainability-parameters-example-csv"></a>

考慮有三個數值特徵欄的資料集，如下列範例所示。

```
0.5814568701544718, 0.6651538910132964, 0.3138080342665499
0.6711642728531724, 0.7466687034026017, 0.1215477472819713
0.0453256543003371, 0.6377430803264152, 0.3558625219713576
0.4785191813363956, 0.0265841045263860, 0.0376935084990697
```

假設模型輸出有兩欄，其中第一個是預測標籤，第二個是機率，如下列範例所示。

```
1, 0.5385257417814224
```

下列 JSON 組態檔案會顯示如何設定此 CSV 資料集。

```
{
                    
    "headers": [
        "feature_1",
        "feature_2",
        "feature_3"
    ],
    "methods": {
        "shap": {
            "baseline": [
                [0.4441164946610942, 0.5190374448171748, 0.20722795300473712]
            ],
            "num_samples": 100,
            "agg_method": "mean_abs"
        }
    },
    "predictor": {
        "model_name": "my_model",
        "instance_type": "ml.m5.xlarge",
        "initial_instance_count": 1
    }
}
```

預測標籤由 `"ProbabilityAttribute"` 參數選取。使用從零開始的編號，因此 1 表示模型輸出的第二欄。

```
"EndpointInput": {
    ...
    "ProbabilityAttribute": 1
    ...
}
```

### JSON 行資料集
<a name="clarify-config-json-monitor-model-explainability-parameters-example-jsonlines"></a>

考慮有四個功能欄和一個標籤欄的資料集，其中第一個功能和標籤是二進位，如下列範例所示。

```
{"features":[0, 0.5814568701544718, 0.6651538910132964, 0.3138080342665499], "label":0}
{"features":[1, 0.6711642728531724, 0.7466687034026017, 0.1215477472819713], "label":1}
{"features":[0, 0.0453256543003371, 0.6377430803264152, 0.3558625219713576], "label":1}
{"features":[1, 0.4785191813363956, 0.0265841045263860, 0.0376935084990697], "label":1}
```

模型輸入與資料集格式相同，模型輸出為 JSON 行，如下列範例所示。

```
{"predicted_label":1, "probability":0.5385257417814224}
```

在下面的範例中，JSON 組態檔案會顯示如何設定此 JSON 行資料集。

```
{
    "headers": [
        "feature_1",
        "feature_2",
        "feature_3"
    ],
    "methods": {
        "shap": {
            "baseline": [
                {"features":[0.4441164946610942, 0.5190374448171748, 0.20722795300473712]}
            ],
            "num_samples": 100,
            "agg_method": "mean_abs"
        }
    },
    "predictor": {
        "model_name": "my_model",
        "instance_type": "ml.m5.xlarge",
        "initial_instance_count": 1,
        "content_template":"{\"features\":$features}"
    }
}
```

然後，`EndpointInput` 中的 `"features"` 參數值 (針對即時端點) 或 `BatchTransformInput` (針對批次轉換工作) 用於訂位資料集中的功能，而 `"probability"` 參數值會從模型輸出中選取機率值。

```
"EndpointInput": {
    ...
    "FeaturesAttribute": "features",
    "ProbabilityAttribute": "probability",
    ...
}
```

# 排程功能屬性偏離監控工作
<a name="clarify-model-monitor-feature-attribute-drift-schedule"></a>

建立基準之後，您可以呼叫 `ModelExplainabilityMonitor` 類別執行個體的 `create_monitoring_schedule()` 方法來排程每小時的模型可解釋性監控。以下各節說明如何為部署到即時端點的模型以及批次轉換工作建立模型可解釋性監控。

**重要**  
在建立監控排程時，您可以指定批次轉換輸入或端點輸入，但不能同時指定兩者。

如果已提交基準工作，監控會自動從基準工作中挑選分析組態。不過，如果您略過基準步驟，或擷取資料集的性質與訓練資料集的性質不同，您必須提供分析組態。`ModelConfig` 需要 `ExplainabilityAnalysisConfig` 與基準工作需要它的原因相同。請注意，只有在計算功能屬性時才需要功能，因此您應排除 Ground Truth 標籤。

## 部署至即時端點的模型的功能屬性偏離監控
<a name="model-monitor-explain-quality-rt"></a>

若要為即時端點排程模型可解釋性監控，請將 `EndpointInput` 執行個體傳遞至 `ModelExplainabilityMonitor` 執行個體的 `endpoint_input` 引數，如下列程式碼範例所示：

```
from sagemaker.model_monitor import CronExpressionGenerator

model_exp_model_monitor = ModelExplainabilityMonitor(
   role=sagemaker.get_execution_role(),
   ... 
)

schedule = model_exp_model_monitor.create_monitoring_schedule(
   monitor_schedule_name=schedule_name,
   post_analytics_processor_script=s3_code_postprocessor_uri,
   output_s3_uri=s3_report_path,
   statistics=model_exp_model_monitor.baseline_statistics(),
   constraints=model_exp_model_monitor.suggested_constraints(),
   schedule_cron_expression=CronExpressionGenerator.hourly(),
   enable_cloudwatch_metrics=True,
   endpoint_input=EndpointInput(
        endpoint_name=endpoint_name,
        destination="/opt/ml/processing/input/endpoint",
    )
)
```

## 批次轉換工作的功能屬性偏離監控
<a name="model-monitor-explain-quality-bt"></a>

若要為批次轉換工作排程模型可解釋性監控，請將 `BatchTransformInput` 執行個體傳遞至 `ModelExplainabilityMonitor` 執行個體的 `batch_transform_input` 引數，如下列程式碼範例所示：

```
from sagemaker.model_monitor import CronExpressionGenerator

model_exp_model_monitor = ModelExplainabilityMonitor(
   role=sagemaker.get_execution_role(),
   ... 
)

schedule = model_exp_model_monitor.create_monitoring_schedule(
   monitor_schedule_name=schedule_name,
   post_analytics_processor_script=s3_code_postprocessor_uri,
   output_s3_uri=s3_report_path,
   statistics=model_exp_model_monitor.baseline_statistics(),
   constraints=model_exp_model_monitor.suggested_constraints(),
   schedule_cron_expression=CronExpressionGenerator.hourly(),
   enable_cloudwatch_metrics=True,
   batch_transform_input=BatchTransformInput(
        destination="opt/ml/processing/data",
        model_name="batch-fraud-detection-model",
        input_manifests_s3_uri="s3://amzn-s3-demo-bucket/batch-fraud-detection/on-schedule-monitoring/in/",
        excludeFeatures="0",
   )
)
```

# 檢查生產模型中功能屬性偏離的報告
<a name="clarify-feature-attribute-drift-report"></a>

在您設定的排程依預設開始之後，您必須等待其第一次執行以開始，然後停止排程以避免產生費用。

若要檢查報告，請使用以下程式碼：

```
schedule_desc = model_explainability_monitor.describe_schedule()
execution_summary = schedule_desc.get("LastMonitoringExecutionSummary")
if execution_summary and execution_summary["MonitoringExecutionStatus"] in ["Completed", "CompletedWithViolations"]:
    last_model_explainability_monitor_execution = model_explainability_monitor.list_executions()[-1]
    last_model_explainability_monitor_execution_report_uri = last_model_explainability_monitor_execution.output.destination
    print(f'Report URI: {last_model_explainability_monitor_execution_report_uri}')
    last_model_explainability_monitor_execution_report_files = sorted(S3Downloader.list(last_model_explainability_monitor_execution_report_uri))
    print("Found Report Files:")
    print("\n ".join(last_model_explainability_monitor_execution_report_files))
else:
    last_model_explainability_monitor_execution = None
    print("====STOP==== \n No completed executions to inspect further. Please wait till an execution completes or investigate previously reported failures.")
```

 如果與基準相比存在任何違規，則會在此列出：

```
if last_model_explainability_monitor_execution:
    model_explainability_violations = last_model_explainability_monitor_execution.constraint_violations()
    if model_explainability_violations:
        print(model_explainability_violations.body_dict)
```

如果您的模型部署到即時端點，您可以選擇**端點**索引標籤，然後按兩下端點，在 SageMaker Studio 中查看分析結果和 CloudWatch 指標的視覺效果。

# 功能偏離分析的 CloudWatch 指標
<a name="clarify-feature-attribute-drift-cw"></a>

本指南顯示可在 SageMaker Clarify 中用於功能屬性偏離分析的 CloudWatch 指標及其屬性。功能屬性偏離監控工作會計算並發佈兩種類型的指標：
+ 每個功能的全域 SHAP 值。
**注意**  
此指標的名稱會將工作分析組態提供的功能名稱附加至 `feature_`。例如，`feature_X` 是功能 `X` 的全域 SHAP 值。
+ 指標的 `ExpectedValue`。

這些指標會發佈到以下 CloudWatch 命名空間：
+ 對於即時端點：`aws/sagemaker/Endpoints/explainability-metrics`
+ 對於批次轉換工作：`aws/sagemaker/ModelMonitoring/explainability-metrics`

每個指標都具有下列屬性：
+ `Endpoint`：受監控端點的名稱 (如果適用)。
+ `MonitoringSchedule`：監控工作排程的名稱。
+ `ExplainabilityMethod`：用來計算 Shapley 值的方法。選擇 `KernelShap`。
+ `Label`：工作分析組態 `label_headers` 提供的名稱，或類似 `label0` 的預留位置。
+ `ValueType`：指標傳回的值類型。選擇 `GlobalShapValues` 或 `ExpectedValue`。

若要停止發佈指標的監控工作，請在[模型可解釋性工作](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelExplainabilityJobDefinition.html)定義的 `Environment` 對應中將 `publish_cloudwatch_metrics` 設定為 `Disabled`。

# 排定監控工作
<a name="model-monitor-scheduling"></a>

Amazon SageMaker Model Monitor 可讓您監控從即時端點收集到的資料。您可以按照週期性排程來監控資料，也可以立即監控一次資料。您可以使用 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateMonitoringSchedule.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateMonitoringSchedule.html) API 建立監控排程。

透過監控排程，SageMaker AI 可以開始處理任務，以分析在指定期間收集的資料。在處理任務中，SageMaker AI 會比較目前分析的資料集與基準統計資料和提供的限制條件。然後，SageMaker AI 產生違規報告。此外，也會針對所分析的每個特徵發出 CloudWatch 指標。

SageMaker AI 會提供預先建置的容器，對表格式資料集執行分析。或者，您可以選擇使用自有容器，如[使用 Amazon SageMaker Model Monitor 支援您自己的容器](model-monitor-byoc-containers.md)主題所述。

您可以為即時端點或批次轉換工作建立模型監控排程。使用基準資源 (限制條件和統計資料)，與即時流量或批次工作輸入進行比較。

**Example 基準指派**  
在下列範例中，用來訓練模型的訓練資料集已上傳至 Amazon S3。如果您在 Amazon S3 中已有此資料集，則可以直接指向它。  

```
# copy over the training dataset to Amazon S3 (if you already have it in Amazon S3, you could reuse it)
baseline_prefix = prefix + '/baselining'
baseline_data_prefix = baseline_prefix + '/data'
baseline_results_prefix = baseline_prefix + '/results'

baseline_data_uri = 's3://{}/{}'.format(bucket,baseline_data_prefix)
baseline_results_uri = 's3://{}/{}'.format(bucket, baseline_results_prefix)
print('Baseline data uri: {}'.format(baseline_data_uri))
print('Baseline results uri: {}'.format(baseline_results_uri))
```

```
training_data_file = open("test_data/training-dataset-with-header.csv", 'rb')
s3_key = os.path.join(baseline_prefix, 'data', 'training-dataset-with-header.csv')
boto3.Session().resource('s3').Bucket(bucket).Object(s3_key).upload_fileobj(training_data_file)
```

**Example 週期性分析的排程**  
如果正在為即時端點排程模型監控，使用基準限制條件和統計資料，與即時流量進行比較。下列程式碼片段顯示您用來為即時端點排程模型監控的一般格式。此範例將模型監控排程為每小時執行一次。  

```
from sagemaker.model_monitor import CronExpressionGenerator
from time import gmtime, strftime

mon_schedule_name = 'my-model-monitor-schedule-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
my_default_monitor.create_monitoring_schedule(
    monitor_schedule_name=mon_schedule_name,
    endpoint_input=EndpointInput(
        endpoint_name=endpoint_name,
        destination="/opt/ml/processing/input/endpoint"
    ),
    post_analytics_processor_script=s3_code_postprocessor_uri,
    output_s3_uri=s3_report_path,
    statistics=my_default_monitor.baseline_statistics(),
    constraints=my_default_monitor.suggested_constraints(),
    schedule_cron_expression=CronExpressionGenerator.hourly(),
    enable_cloudwatch_metrics=True,
)
```

**Example 排程一次性分析**  
您也可以將下列引數傳遞至 `create_monitoring_schedule` 方法，將分析排程為執行一次而非週期性執行：  

```
    schedule_cron_expression=CronExpressionGenerator.now(),
    data_analysis_start_time="-PT1H",
    data_analysis_end_time="-PT0H",
```
在這些引數中，`schedule_cron_expression` 參數會將分析排程為使用值 `CronExpressionGenerator.now()` 立即執行一次。對於透過此設定的任何排程，`data_analysis_start_time` 和 `data_analysis_end_time` 參數都為必要。這些參數會設定分析時段的開始時間和結束時間。將這些時間定義為相對於目前時間的偏移，並使用 ISO 8601 持續時間格式。在這個範例中，時間 `-PT1H` 和 `-PT0H` 定義在過去一小時和目前時間之間的時段。透過此排程，分析只會評估在指定時段期間收集的資料。

**Example 排程批次轉換工作**  
下列程式碼片段顯示您用來排程批次轉換工作之模型監控的一般格式。  

```
from sagemaker.model_monitor import (
    CronExpressionGenerator,
    BatchTransformInput, 
    MonitoringDatasetFormat, 
)
from time import gmtime, strftime

mon_schedule_name = 'my-model-monitor-schedule-' + strftime("%Y-%m-%d-%H-%M-%S", gmtime())
my_default_monitor.create_monitoring_schedule(
    monitor_schedule_name=mon_schedule_name,
    batch_transform_input=BatchTransformInput(
        destination="opt/ml/processing/input",
        data_captured_destination_s3_uri=s3_capture_upload_path,
        dataset_format=MonitoringDatasetFormat.csv(header=False),
    ),
    post_analytics_processor_script=s3_code_postprocessor_uri,
    output_s3_uri=s3_report_path,
    statistics=my_default_monitor.baseline_statistics(),
    constraints=my_default_monitor.suggested_constraints(),
    schedule_cron_expression=CronExpressionGenerator.hourly(),
    enable_cloudwatch_metrics=True,
)
```

```
desc_schedule_result = my_default_monitor.describe_schedule()
print('Schedule status: {}'.format(desc_schedule_result['MonitoringScheduleStatus']))
```

# 監控排程的 cron 運算式
<a name="model-monitor-schedule-expression"></a>

若要提供監控排程的詳細資訊，請使用 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ScheduleConfig.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ScheduleConfig.html)，此為描述監控排程詳細資訊的 `cron` 運算式。

Amazon SageMaker Model Monitor 支援以下 `cron` 運算式：
+ 若要設定工作每小時開始一次，請使用以下內容：

  `Hourly: cron(0 * ? * * *)`
+ 若要每天執行工作，請使用以下內容：

  `cron(0 [00-23] ? * * *)`
+ 若要立即執行工作一次，請使用以下關鍵字：

  `NOW`

例如，下列是有效的 `cron` 運算式：
+ 每日下午 12 點 (UTC)：`cron(0 12 ? * * *)`
+ 每日上午 12 點 (UTC)：`cron(0 0 ? * * *)`

為了支援每 6、12 小時執行一次，模型監控支援下列運算式：

`cron(0 [00-23]/[01-24] ? * * *)`

例如，下列是有效的 `cron` 運算式：
+ 每 12 小時，從下午 5 點 (UTC) 開始：`cron(0 17/12 ? * * *)`
+ 每兩小時，從上午 12 點 (UTC) 開始：`cron(0 0/2 ? * * *)`

**備註**  
雖然 `cron` 運算式設定為下午 5 點 (UTC) 開始，但請注意，從實際要求的時間到真正執行之間可能延遲 0-20 分鐘。
如果您想要按照每日排程執行，請勿提供此參數。SageMaker AI 會選擇每天執行的時間。
目前，SageMaker AI 僅支援 1 小時到 24 小時之間的每小時整數速率。

# 設定監控排程的服務控制政策
<a name="model-monitor-scp-rules"></a>

 當您分別使用 [CreateMonitoringSchedule](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateMonitoringSchedule.html) API 或 [UpdateMonitoringSchedule](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateMonitoringSchedule.html) API 來建立或更新排程時，您必須指定監控工作的參數。視您的使用案例而定，您可採用下列其中一種方式這麼做：
+  當您調用 `CreateMonitoringSchedule` 或 `UpdateMonitoringSchedule` 時，您可以指定 [MonitoringScheduleConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_MonitoringScheduleConfig.html) 的 [MonitoringJobDefinition](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_MonitoringJobDefinition.html) 欄位。您只能使用此功能來建立或更新資料品質監控工作的排程。
+  在調用 `CreateMonitoringSchedule` 或 `UpdateMonitoringSchedule` 時，您可以為 `MonitoringScheduleConfig` 的 `MonitoringJobDefinitionName` 欄位指定已建立的監控工作定義名稱。您可以將此功能用於透過下列其中一個 API 建立的任何工作定義：
  +  [CreateDataQualityJobDefinition](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateDataQualityJobDefinition.html) 
  +  [CreateModelQualityJobDefinition](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelQualityJobDefinition.html) 
  +  [CreateModelBiasJobDefinition](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelBiasJobDefinition.html) 
  +  [CreateModelExplainabilityJobDefinition](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelExplainabilityJobDefinition.html) 

   如果您想要使用 SageMaker Python SDK 來建立或更新排程，則必須使用此程序。

 上述程序為互斥，也就是說，您可以在建立或更新監控排程時指定 `MonitoringJobDefinition` 欄位或 `MonitoringJobDefinitionName` 欄位。

 當您建立監控工作定義或在 `MonitoringJobDefinition` 欄位中指定一個定義時，您可以設定安全性參數，例如 `NetworkConfig` 和 `VolumeKmsKeyId`。身為管理員，您可能希望這些參數一律設定為特定值，以便監控工作永遠在安全的環境中執行。為了確保這一點，請設定適當的[服務控制政策](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html) (SCP)。SCP 是一種組織政策類型，可用來管理組織中的許可。

 下列範例顯示可用來確保在建立或更新監控工作排程時，已正確設定基礎架構參數的 SCP。

------
#### [ JSON ]

****  

```
{
    "Version":"2012-10-17",		 	 	 
    "Statement": [
        {
            "Effect": "Deny",
            "Action": [
                "sagemaker:CreateDataQualityJobDefinition",
                "sagemaker:CreateModelBiasJobDefinition",
                "sagemaker:CreateModelExplainabilityJobDefinition",
                "sagemaker:CreateModelQualityJobDefinition"
            ],
            "Resource": "arn:*:sagemaker:*:*:*",
            "Condition": {
                "Null": {
                    "sagemaker:VolumeKmsKey":"true",
                    "sagemaker:VpcSubnets": "true",
                    "sagemaker:VpcSecurityGroupIds": "true"
                }
            }
        },
        {
            "Effect": "Deny",
            "Action": [
                "sagemaker:CreateDataQualityJobDefinition",
                "sagemaker:CreateModelBiasJobDefinition",
                "sagemaker:CreateModelExplainabilityJobDefinition",
                "sagemaker:CreateModelQualityJobDefinition"
            ],
            "Resource": "arn:*:sagemaker:*:*:*",
            "Condition": {
                "Bool": {
                    "sagemaker:InterContainerTrafficEncryption": "false"
                }
            }
        },
        {
            "Effect": "Deny",
            "Action": [
                "sagemaker:CreateMonitoringSchedule",
                "sagemaker:UpdateMonitoringSchedule"
            ],
            "Resource": "arn:*:sagemaker:*:*:monitoring-schedule/*",
            "Condition": {
                "Null": {
                    "sagemaker:ModelMonitorJobDefinitionName": "true"
                }
            }
        }
    ]
}
```

------

 在範例中的前兩個規則，確定一律為監控工作定義設定安全性參數。最終規則會要求組織中建立或更新排程的任何人都必須一律指定 `MonitoringJobDefinitionName` 欄位。這樣可確保在建立或更新排程時，組織中的任何人都不能透過指定 `MonitoringJobDefinition` 欄位為安全性參數設定不安全值。

# Amazon SageMaker Model Monitor 預建容器
<a name="model-monitor-pre-built-container"></a>

SageMaker AI 提供稱為 `sagemaker-model-monitor-analyzer` 的內建影像，可提供一系列模型監控功能，包括建議限制條件、產生統計資料、根據基準來驗證限制條件，以及發出 Amazon CloudWatch 指標。此影像根據 Spark 3.3.0 版，並使用 [Deequ](https://github.com/awslabs/deequ) 2.0.2 版建置。

**注意**  
您不能直接提取內建 `sagemaker-model-monitor-analyzer` 影像。當您使用其中一個 AWS SDKs 提交基準處理或監控工作時，可以使用`sagemaker-model-monitor-analyzer`映像。

 使用 SageMaker Python SDK (請參閱 [SageMaker AI Python SDK 參考指南](https://sagemaker.readthedocs.io/en/stable/api/utility/image_uris.html)中的 `image_uris.retrieve`) 為您產生 ECR 影像 URI，或直接指定 ECR 影像 URI。您可以取得 SageMaker Model Monitor 的預先建置影像，如下所示：

`<ACCOUNT_ID>.dkr.ecr.<REGION_NAME>.amazonaws.com/sagemaker-model-monitor-analyzer`

例如：`159807026194.dkr.ecr.us-west-2.amazonaws.com/sagemaker-model-monitor-analyzer`

如果您位於中國 AWS 區域，則可以存取 SageMaker Model Monitor 的預先建置映像，如下所示：

`<ACCOUNT_ID>.dkr.ecr.<REGION_NAME>.amazonaws.com.rproxy.govskope.us.cn/sagemaker-model-monitor-analyzer`

如需帳戶 IDs和 AWS 區域名稱，請參閱 [Docker 登錄檔路徑和範例程式碼](https://docs.aws.amazon.com/sagemaker/latest/dg-ecr-paths/sagemaker-algo-docker-registry-paths)。

若要撰寫您自己的分析容器，請參閱[自訂監控排程](model-monitor-custom-monitoring-schedules.md)中所述的容器合約。

# 解讀結果
<a name="model-monitor-interpreting-results"></a>

當您執行基準處理工作並取得資料集的統計資料和限制條件之後，您就可以執行監控工作來計算統計資料，並列出與基準限制條件相關的任何違規。依預設，您的帳戶也會報告 Amazon CloudWatch 指標。如需在 Amazon SageMaker Studio 中檢視監控結果的相關資訊，請參閱[在 Amazon SageMaker Studio 中以視覺化方式呈現即時端點的結果](model-monitor-interpreting-visualize-results.md)。

## 列出執行
<a name="model-monitor-interpreting-results-list-executions"></a>

排程會依指定的間隔開始監控工作。下列程式碼列出最近的五個執行。如果您在建立每小時排程後執行此程式碼，執行可能是空的，您可能必須等到過了小時界限 (UTC)，才能看到執行開始。下列程式碼包含等待的邏輯。

```
mon_executions = my_default_monitor.list_executions()
print("We created a hourly schedule above and it will kick off executions ON the hour (plus 0 - 20 min buffer.\nWe will have to wait till we hit the hour...")

while len(mon_executions) == 0:
    print("Waiting for the 1st execution to happen...")
    time.sleep(60)
    mon_executions = my_default_monitor.list_executions()
```

## 檢查特定執行
<a name="model-monitor-interpreting-results-inspect-specific-execution"></a>

 

在上一個步驟中，您挑選最近完成或失敗的排程執行。你可以探索對錯情況。終端機狀態為：
+ `Completed` – 監控執行完成，在違規報告中找不到任何問題。
+ `CompletedWithViolations` – 執行完成，但偵測到限制條件違規。
+ `Failed` – 監控執行失敗，可能是因為用戶端錯誤 (例如角色問題) 或基礎結構問題。若要識別原因，請參閱`FailureReason`和`ExitMessage`。

```
latest_execution = mon_executions[-1] # latest execution's index is -1, previous is -2 and so on..
time.sleep(60)
latest_execution.wait(logs=False)

print("Latest execution status: {}".format(latest_execution.describe()['ProcessingJobStatus']))
print("Latest execution result: {}".format(latest_execution.describe()['ExitMessage']))

latest_job = latest_execution.describe()
if (latest_job['ProcessingJobStatus'] != 'Completed'):
        print("====STOP==== \n No completed executions to inspect further. Please wait till an execution completes or investigate previously reported failures.")
```

```
report_uri=latest_execution.output.destination
print('Report Uri: {}'.format(report_uri))
```

## 列出產生的報告
<a name="model-monitor-interpreting-results-list-generated-reports"></a>

使用下列程式碼列出產生的報告。

```
from urllib.parse import urlparse
s3uri = urlparse(report_uri)
report_bucket = s3uri.netloc
report_key = s3uri.path.lstrip('/')
print('Report bucket: {}'.format(report_bucket))
print('Report key: {}'.format(report_key))

s3_client = boto3.Session().client('s3')
result = s3_client.list_objects(Bucket=report_bucket, Prefix=report_key)
report_files = [report_file.get("Key") for report_file in result.get('Contents')]
print("Found Report Files:")
print("\n ".join(report_files))
```

## 違規報告
<a name="model-monitor-interpreting-results-violations-report"></a>

如果有違反基準的情形，則會顯示在違規報告中。使用下面的程式碼列出違規。

```
violations = my_default_monitor.latest_monitoring_constraint_violations()
pd.set_option('display.max_colwidth', -1)
constraints_df = pd.io.json.json_normalize(violations.body_dict["violations"])
constraints_df.head(10)
```

這只適用於包含表格式資料的資料集。下列結構描述檔案指定計算的統計資料和監控的違規。

表格式資料集的輸出檔案


| 檔案名稱 | Description | 
| --- | --- | 
| statistics.json |  針對所分析資料集的每個特徵，包含單欄式統計資料。請在下一個主題中查看此檔案的結構描述。  此檔案僅為了資料品質監控而建立。   | 
| constraint\$1violations.json |  與 `baseline_constaints` 和 `baseline_statistics` 路徑中指定的基準統計資料和限制條件檔案相比較之後，此檔案包含目前這組資料中發現的違規清單。  | 

依預設，[Amazon SageMaker Model Monitor 預建容器](model-monitor-pre-built-container.md) 為每個功能儲存一組 Amazon CloudWatch 指標。

容器程式碼可以在此位置發出 CloudWatch 指標：`/opt/ml/output/metrics/cloudwatch`。

# 在 Amazon SageMaker Studio 中以視覺化方式呈現即時端點的結果
<a name="model-monitor-interpreting-visualize-results"></a>

如果您正在監控即時端點，也可以在 Amazon SageMaker Studio中以視覺化方式呈現結果。您可以檢視任何監控工作執行的詳細資訊，也可以建立圖表以顯示監控工作計算之任何指標的基準和擷取值。

**檢視監控工作的詳細結果**

1. 登入 Studio。如需詳細資訊，請參閱[Amazon SageMaker AI 網域概觀](gs-studio-onboard.md)。

1. 在左側導覽窗格中，選擇**元件和登錄檔**圖示 (![\[Orange paper airplane icon representing email or message sending functionality.\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/icons/Components_registries.png))。

1. 從下拉式清單中選擇**端點**。  
![\[主控台中端點下拉式功能表的位置。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model_monitor/mm-studio-endpoints.png)

1. 在端點索引標籤上，選擇您要檢視其工作詳細資訊的監控類型。  
![\[模型監控區段中模型品質索引標籤的位置。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model_monitor/mm-studio-model-quality.png)

1. 從監控工作清單中，選擇您要檢視詳細資訊的監控工作執行的名稱。  
![\[模型監控區段的模型品質索引標籤。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model_monitor/mm-studio-job-history.png)

1. **監控工作詳細資訊**索引標籤隨即開啟，其中包含監控工作的詳細報告。  
![\[監控任務詳細資訊索引標籤。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model_monitor/mm-studio-job-details.png)

您可以建立圖表以顯示一個時段中的基準和擷取的指標。

**在 SageMaker Studio 中建立圖表以視覺化監控結果**

1. 登入 Studio。如需詳細資訊，請參閱[Amazon SageMaker AI 網域概觀](gs-studio-onboard.md)。

1. 在左側導覽窗格中，選擇**元件和登錄檔**圖示 (![\[Orange paper airplane icon representing email or message sending functionality.\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/icons/Components_registries.png))。

1. 從下拉式清單中選擇**端點**。  
![\[主控台中端點下拉式功能表的位置。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model_monitor/mm-studio-endpoints.png)

1. 在**端點**索引標籤上，選擇您要為其建立圖表的監控類型。此範例顯示**模型品質**監控類型的圖表。  
![\[模型監控區段中模型品質索引標籤的位置。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model_monitor/mm-studio-model-quality.png)

1. 選擇**新增圖表**。  
![\[主控台中新增圖表的位置。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model_monitor/mm-studio-add-chart.png)

1. 在**圖表屬性**索引標籤上，選擇您要建立圖表的時段、統計資料和指標。此範例顯示 **1 週****時間軸**、**平均****統計資料**，以及 **F1** **指標**的圖表。  
![\[在主控台中選取指標的位置。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model_monitor/mm-studio-chart-properties.png)

1. 顯示您在上一步中選擇的基準和目前指標統計資料的圖表會顯示在**端點**索引標籤中。  
![\[範例圖表顯示上一個步驟中選擇的基準和目前平均指標。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model_monitor/mm-studio-f1-chart.png)

# 進階主題
<a name="model-monitor-advanced-topics"></a>

下列各節包含更進階的任務，說明如何使用預先處理和後製處理指令碼自訂監控、如何建置您自己的容器，以及如何使用 CloudFormation 建立監控排程。

**Topics**
+ [自訂監控排程](model-monitor-custom-monitoring-schedules.md)
+ [使用 CloudFormation 自訂資源建立即時端點的監控排程](model-monitor-cloudformation-monitoring-schedules.md)

# 自訂監控排程
<a name="model-monitor-custom-monitoring-schedules"></a>

除了使用內建的監控機制之外，您還可以使用預處理和後處理指令碼，或使用或建置您自己的容器，以建立您自己的自訂監控排程和程序。

**Topics**
+ [預處理和後處理](model-monitor-pre-and-post-processing.md)
+ [使用 Amazon SageMaker Model Monitor 支援您自己的容器](model-monitor-byoc-containers.md)

# 預處理和後處理
<a name="model-monitor-pre-and-post-processing"></a>

您可以使用自訂的預先處理和後製處理 Python 指令碼，將輸入轉換至模型監控，或在成功執行監控後擴充程式碼。將這些指令碼上傳到 Amazon S3，並在建立模型監控時參照它們。

下列範例顯示如何使用預先處理和後製處理指令碼來自訂監控排程。將*使用者預留位置文字*取代為自己的資訊。

```
import boto3, os
from sagemaker import get_execution_role, Session
from sagemaker.model_monitor import CronExpressionGenerator, DefaultModelMonitor

# Upload pre and postprocessor scripts
session = Session()
bucket = boto3.Session().resource("s3").Bucket(session.default_bucket())
prefix = "demo-sagemaker-model-monitor"
pre_processor_script = bucket.Object(os.path.join(prefix, "preprocessor.py")).upload_file("preprocessor.py")
post_processor_script = bucket.Object(os.path.join(prefix, "postprocessor.py")).upload_file("postprocessor.py")

# Get execution role
role = get_execution_role() # can be an empty string

# Instance type
instance_type = "instance-type"
# instance_type = "ml.m5.xlarge" # Example

# Create a monitoring schedule with pre and postprocessing
my_default_monitor = DefaultModelMonitor(
    role=role,
    instance_count=1,
    instance_type=instance_type,
    volume_size_in_gb=20,
    max_runtime_in_seconds=3600,
)

s3_report_path = "s3://{}/{}".format(bucket, "reports")
monitor_schedule_name = "monitor-schedule-name"
endpoint_name = "endpoint-name"
my_default_monitor.create_monitoring_schedule(
    post_analytics_processor_script=post_processor_script,
    record_preprocessor_script=pre_processor_script,
    monitor_schedule_name=monitor_schedule_name,
    # use endpoint_input for real-time endpoint
    endpoint_input=endpoint_name,
    # or use batch_transform_input for batch transform jobs
    # batch_transform_input=batch_transform_name,
    output_s3_uri=s3_report_path,
    statistics=my_default_monitor.baseline_statistics(),
    constraints=my_default_monitor.suggested_constraints(),
    schedule_cron_expression=CronExpressionGenerator.hourly(),
    enable_cloudwatch_metrics=True,
)
```

**Topics**
+ [預處理指令碼](#model-monitor-pre-processing-script)
+ [自訂取樣](#model-monitor-pre-processing-custom-sampling)
+ [後處理指令碼](#model-monitor-post-processing-script)

## 預處理指令碼
<a name="model-monitor-pre-processing-script"></a>

當您需要將輸入轉換為模型監控時，請使用預先處理指令碼。

例如，假設模型的輸出是陣列 `[1.0, 2.1]`。Amazon SageMaker Model Monitor 容器僅適用於表格式或扁平化 JSON 結構，例如 `{“prediction0”: 1.0, “prediction1” : 2.1}`。您可以使用如下的預先處理指令碼，將陣列轉換為正確的 JSON 結構。

```
def preprocess_handler(inference_record):
    input_data = inference_record.endpoint_input.data
    output_data = inference_record.endpoint_output.data.rstrip("\n")
    data = output_data + "," + input_data
    return { str(i).zfill(20) : d for i, d in enumerate(data.split(",")) }
```

在另一個範例中，假設您的模型具有可選功能，並且您使用 `-1` 來表示可選功能有缺少值。如果您有資料品質監控，您可能想要將 `-1` 從輸入值陣列中移除，這樣它就不會包含在監控的指標計算中。您可以使用如下所示的指令碼來移除這些值。

```
def preprocess_handler(inference_record):
    input_data = inference_record.endpoint_input.data
    return {i : None if x == -1 else x for i, x in enumerate(input_data.split(","))}
```

您的預先處理指令碼會接收 `inference_record` 為其唯一的輸入。下列程式碼片段說明 `inference_record` 的範例。

```
{
  "captureData": {
    "endpointInput": {
      "observedContentType": "text/csv",
      "mode": "INPUT",
      "data": "132,25,113.2,96,269.9,107,,0,0,0,0,0,0,1,0,1,0,0,1",
      "encoding": "CSV"
    },
    "endpointOutput": {
      "observedContentType": "text/csv; charset=utf-8",
      "mode": "OUTPUT",
      "data": "0.01076381653547287",
      "encoding": "CSV"
    }
  },
  "eventMetadata": {
    "eventId": "feca1ab1-8025-47e3-8f6a-99e3fdd7b8d9",
    "inferenceTime": "2019-11-20T23:33:12Z"
  },
  "eventVersion": "0"
}
```

下列程式碼片段顯示 `inference_record` 的完整類別結構。

```
KEY_EVENT_METADATA = "eventMetadata"
KEY_EVENT_METADATA_EVENT_ID = "eventId"
KEY_EVENT_METADATA_EVENT_TIME = "inferenceTime"
KEY_EVENT_METADATA_CUSTOM_ATTR = "customAttributes"

KEY_EVENTDATA_ENCODING = "encoding"
KEY_EVENTDATA_DATA = "data"

KEY_GROUND_TRUTH_DATA = "groundTruthData"

KEY_EVENTDATA = "captureData"
KEY_EVENTDATA_ENDPOINT_INPUT = "endpointInput"
KEY_EVENTDATA_ENDPOINT_OUTPUT = "endpointOutput"

KEY_EVENTDATA_BATCH_OUTPUT = "batchTransformOutput"
KEY_EVENTDATA_OBSERVED_CONTENT_TYPE = "observedContentType"
KEY_EVENTDATA_MODE = "mode"

KEY_EVENT_VERSION = "eventVersion"

class EventConfig:
    def __init__(self, endpoint, variant, start_time, end_time):
        self.endpoint = endpoint
        self.variant = variant
        self.start_time = start_time
        self.end_time = end_time


class EventMetadata:
    def __init__(self, event_metadata_dict):
        self.event_id = event_metadata_dict.get(KEY_EVENT_METADATA_EVENT_ID, None)
        self.event_time = event_metadata_dict.get(KEY_EVENT_METADATA_EVENT_TIME, None)
        self.custom_attribute = event_metadata_dict.get(KEY_EVENT_METADATA_CUSTOM_ATTR, None)


class EventData:
    def __init__(self, data_dict):
        self.encoding = data_dict.get(KEY_EVENTDATA_ENCODING, None)
        self.data = data_dict.get(KEY_EVENTDATA_DATA, None)
        self.observedContentType = data_dict.get(KEY_EVENTDATA_OBSERVED_CONTENT_TYPE, None)
        self.mode = data_dict.get(KEY_EVENTDATA_MODE, None)

    def as_dict(self):
        ret = {
            KEY_EVENTDATA_ENCODING: self.encoding,
            KEY_EVENTDATA_DATA: self.data,
            KEY_EVENTDATA_OBSERVED_CONTENT_TYPE: self.observedContentType,
        }
        return ret


class CapturedData:
    def __init__(self, event_dict):
        self.event_metadata = None
        self.endpoint_input = None
        self.endpoint_output = None
        self.batch_transform_output = None
        self.ground_truth = None
        self.event_version = None
        self.event_dict = event_dict
        self._event_dict_postprocessed = False
        
        if KEY_EVENT_METADATA in event_dict:
            self.event_metadata = EventMetadata(event_dict[KEY_EVENT_METADATA])
        if KEY_EVENTDATA in event_dict:
            if KEY_EVENTDATA_ENDPOINT_INPUT in event_dict[KEY_EVENTDATA]:
                self.endpoint_input = EventData(event_dict[KEY_EVENTDATA][KEY_EVENTDATA_ENDPOINT_INPUT])
            if KEY_EVENTDATA_ENDPOINT_OUTPUT in event_dict[KEY_EVENTDATA]:
                self.endpoint_output = EventData(event_dict[KEY_EVENTDATA][KEY_EVENTDATA_ENDPOINT_OUTPUT])
            if KEY_EVENTDATA_BATCH_OUTPUT in event_dict[KEY_EVENTDATA]:
                self.batch_transform_output = EventData(event_dict[KEY_EVENTDATA][KEY_EVENTDATA_BATCH_OUTPUT])

        if KEY_GROUND_TRUTH_DATA in event_dict:
            self.ground_truth = EventData(event_dict[KEY_GROUND_TRUTH_DATA])
        if KEY_EVENT_VERSION in event_dict:
            self.event_version = event_dict[KEY_EVENT_VERSION]

    def as_dict(self):
        if self._event_dict_postprocessed is True:
            return self.event_dict
        if KEY_EVENTDATA in self.event_dict:
            if KEY_EVENTDATA_ENDPOINT_INPUT in self.event_dict[KEY_EVENTDATA]:
                self.event_dict[KEY_EVENTDATA][KEY_EVENTDATA_ENDPOINT_INPUT] = self.endpoint_input.as_dict()
            if KEY_EVENTDATA_ENDPOINT_OUTPUT in self.event_dict[KEY_EVENTDATA]:
                self.event_dict[KEY_EVENTDATA][
                    KEY_EVENTDATA_ENDPOINT_OUTPUT
                ] = self.endpoint_output.as_dict()
            if KEY_EVENTDATA_BATCH_OUTPUT in self.event_dict[KEY_EVENTDATA]:
                self.event_dict[KEY_EVENTDATA][KEY_EVENTDATA_BATCH_OUTPUT] = self.batch_transform_output.as_dict()
        
        self._event_dict_postprocessed = True
        return self.event_dict

    def __str__(self):
        return str(self.as_dict())
```

## 自訂取樣
<a name="model-monitor-pre-processing-custom-sampling"></a>

您也可以在預先處理指令碼中套用自訂取樣策略。若要這麼做，請設定模型監控的第一方預先建置容器，根據您指定的取樣率忽略某個百分比的記錄。在下列範例中，處理常式會取樣 10% 的記錄，傳回 10% 的處理常式呼叫的記錄，其餘為空白清單。

```
import random

def preprocess_handler(inference_record):
    # we set up a sampling rate of 0.1
    if random.random() > 0.1:
        # return an empty list
        return []
    input_data = inference_record.endpoint_input.data
    return {i : None if x == -1 else x for i, x in enumerate(input_data.split(","))}
```

### 預先處理指令碼的自訂記錄
<a name="model-monitor-pre-processing-custom-logging"></a>

 如果您的預先處理指令碼傳回錯誤，請檢查記錄至 CloudWatch 的例外狀況訊息以進行偵錯。您可以在 CloudWatch 上透過 `preprocess_handler` 介面來存取記錄器。您可以將指令碼中所需的任何資訊記錄至 CloudWatch。這在對預先處理指令碼進行偵錯時非常有用。以下範例顯示如何使用 `preprocess_handler` 介面記錄至 CloudWatch 

```
def preprocess_handler(inference_record, logger):
    logger.info(f"I'm a processing record: {inference_record}")
    logger.debug(f"I'm debugging a processing record: {inference_record}")
    logger.warning(f"I'm processing record with missing value: {inference_record}")
    logger.error(f"I'm a processing record with bad value: {inference_record}")
    return inference_record
```

## 後處理指令碼
<a name="model-monitor-post-processing-script"></a>

如果您想要在成功執行監控之後擴充程式碼，請使用後製處理指令碼。

```
def postprocess_handler():
    print("Hello from post-proc script!")
```

# 使用 Amazon SageMaker Model Monitor 支援您自己的容器
<a name="model-monitor-byoc-containers"></a>

Amazon SageMaker Model Monitor 提供預先建置的容器，能夠分析從表格式資料集的端點或批次轉換工作擷取的資料。如果您想使用自有容器，模型監控提供擴充點供您利用。

在幕後，當您建立 `MonitoringSchedule` 時，模型監控最終會啟動處理工作。因此，容器需要知道 [如何建置您自己的處理容器 (進階案例)](build-your-own-processing-container.md) 主題中所記載的處理工作合約。請注意，模型監控會根據排程為您啟動處理工作。調用時，模型監控會為您設定額外的環境變數，以針對排程監控的該特定執行，讓容器有足夠的情境來處理資料。如需容器輸入的其他資訊，請參閱[容器合約輸入](model-monitor-byoc-contract-inputs.md)。

在容器中，您現在可以使用上述環境變數/情境，在自訂程式碼中針對目前時段分析資料集。完成此分析後，您可以選擇發出報告以上傳至 S3 儲存貯體。預先建置容器產生的報告記載於 [容器合約輸出](model-monitor-byoc-contract-outputs.md)。如果您想要在 SageMaker Studio 中啟用報告視覺化，則應該遵循相同的格式。您也可以選擇發出完全自訂的報告。

您也可以依照[適用於使用自有容器的 CloudWatch 指標](model-monitor-byoc-cloudwatch.md)中的指示，從容器發出 CloudWatch 指標。

**Topics**
+ [容器合約輸入](model-monitor-byoc-contract-inputs.md)
+ [容器合約輸出](model-monitor-byoc-contract-outputs.md)
+ [適用於使用自有容器的 CloudWatch 指標](model-monitor-byoc-cloudwatch.md)

# 容器合約輸入
<a name="model-monitor-byoc-contract-inputs"></a>

Amazon SageMaker Model Monitor 平台根據指定的排程，調用您的容器程式碼。如果您選擇撰寫自己的容器程式碼，下列環境變數可使用。在此情況下，您可以分析目前資料集或評估限制條件 (如果選擇如此)，並發出指標 (如果適用)。

即時端點和批次轉換工作的可用環境變數相同，`dataset_format` 變數除外。如果您使用的是即時端點，`dataset_format` 變數會支援下列選項：

```
{\"sagemakerCaptureJson\": {\"captureIndexNames\": [\"endpointInput\",\"endpointOutput\"]}}
```

如果您使用的是批次轉換工作，則 `dataset_format` 支援下列選項：

```
{\"csv\": {\"header\": [\"true\",\"false\"]}}
```

```
{\"json\": {\"line\": [\"true\",\"false\"]}}
```

```
{\"parquet\": {}}
```

下列程式碼範例顯示可用於容器程式碼的完整環境變數集 (並使用即時端點的 `dataset_format` 格式)。

```
"Environment": {
 "dataset_format": "{\"sagemakerCaptureJson\": {\"captureIndexNames\": [\"endpointInput\",\"endpointOutput\"]}}",
 "dataset_source": "/opt/ml/processing/endpointdata",
 "end_time": "2019-12-01T16: 20: 00Z",
 "output_path": "/opt/ml/processing/resultdata",
 "publish_cloudwatch_metrics": "Disabled",
 "sagemaker_endpoint_name": "endpoint-name",
 "sagemaker_monitoring_schedule_name": "schedule-name",
 "start_time": "2019-12-01T15: 20: 00Z"
}
```

Parameters 


| 參數名稱 | Description | 
| --- | --- | 
| dataset\$1format |  對於從 `Endpoint` 支援的 `MonitoringSchedule` 開始的工作，此為 `sageMakerCaptureJson` 且擷取索引為 `endpointInput`、`endpointOutput` 或兩者兼有。對於批次轉換工作，這會指定資料格式，無論是 CSV、JSON 或 Parquet。  | 
| dataset\$1source |  如果您使用的是即時端點，可使用與 `start_time` 和 `end_time` 指定的監控期間對應的資料所在的本機路徑。在此路徑中，資料位於 ` /{endpoint-name}/{variant-name}/yyyy/mm/dd/hh` 中。 我們有時會下載超過開始和結束時間所指定的資料量。容器程式碼會依需要來剖析資料。  | 
| output\$1path |  寫入輸出報告和其他檔案的本機路徑。請在 `CreateMonitoringSchedule` 請求中以 `MonitoringOutputConfig.MonitoringOutput[0].LocalPath` 指定此參數。它會上傳到 `MonitoringOutputConfig.MonitoringOutput[0].S3Uri` 中指定的 `S3Uri` 路徑。  | 
| publish\$1cloudwatch\$1metrics |  對於由 `CreateMonitoringSchedule` 啟動的工作，此參數設定為 `Enabled`。容器可以選擇在 `[filepath]` 寫入 Amazon CloudWatch 輸出檔案。  | 
| sagemaker\$1endpoint\$1name |  如果您使用的是即時端點，則為啟動此排程工作的 `Endpoint` 名稱。  | 
| sagemaker\$1monitoring\$1schedule\$1name |  啟動此工作的 `MonitoringSchedule` 名稱。  | 
| \$1sagemaker\$1endpoint\$1datacapture\$1prefix\$1 |  如果您使用的是即時端點，則為 `Endpoint` 的 `DataCaptureConfig` 參數中指定的前置詞。如果容器需要直接存取超過 SageMaker AI 在 `dataset_source` 路徑上已下載的資料量，則可以使用此參數。  | 
| start\$1time, end\$1time |  此分析執行的時間範圍。例如，對於排定在 05:00 (UTC) 執行的工作和 2020/2/20 執行的工作，`start_time` 為 2020-02-19T06:00:00Z，`end_time` 為 2020-02-20T05:00:00Z  | 
| baseline\$1constraints: |  ` BaselineConfig.ConstraintResource.S3Uri` 中指定的基準限制條件檔案的本機路徑。這只有當 `CreateMonitoringSchedule` 請求中指定此參數時才能使用。  | 
| baseline\$1statistics |  `BaselineConfig.StatisticsResource.S3Uri` 中指定的基準統計資料檔案的本機路徑。這只有當 `CreateMonitoringSchedule` 請求中指定此參數時才能使用。  | 

# 容器合約輸出
<a name="model-monitor-byoc-contract-outputs"></a>

容器可以分析 `*dataset_source*` 路徑中可用的資料，並將報告寫入 `*output_path*.` 中的路徑。容器程式碼可以撰寫符合您需求的任何報告。

如果您使用下列結構和合約，SageMaker AI 在視覺化和 API 上會特別處理某些輸出檔案。這只適用於表格式資料集。

表格式資料集的輸出檔案


| 檔案名稱 | Description | 
| --- | --- | 
| statistics.json |  針對所分析資料集的每個特徵，此檔案會有單欄式統計資料。在下一節可查看此檔案的結構描述。  | 
| constraints.json |  針對所觀察的特徵，此檔案會有限制條件。在下一節可查看此檔案的結構描述。  | 
| constraints\$1violations.json |  與 `baseline_constaints` 和 `baseline_statistics` 路徑中指定的基準統計資料和限制條件檔案相比較之後，此檔案中預期會有目前這組資料中發現的違規清單。  | 

此外，如果 `publish_cloudwatch_metrics` 值為 `"Enabled"`，容器程式碼可以在此位置發出 Amazon CloudWatch 指標：`/opt/ml/output/metrics/cloudwatch`。下列各節描述這些檔案的結構描述。

**Topics**
+ [統計資料的結構描述 (statistics.json 檔案)](model-monitor-byoc-statistics.md)
+ [限制條件的結構描述 (constraints.json 檔案)](model-monitor-byoc-constraints.md)

# 統計資料的結構描述 (statistics.json 檔案)
<a name="model-monitor-byoc-statistics"></a>

針對基準和擷取的資料，`statistics.json` 檔案中定義的結構描述指定要計算的統計參數。另外還設定儲存貯體供 [KLL](https://datasketches.apache.org/docs/KLL/KLLSketch.html) 使用 (非常簡潔的分位數草圖，具有延遲壓縮配置)。

```
{
    "version": 0,
    # dataset level stats
    "dataset": {
        "item_count": number
    },
    # feature level stats
    "features": [
        {
            "name": "feature-name",
            "inferred_type": "Fractional" | "Integral",
            "numerical_statistics": {
                "common": {
                    "num_present": number,
                    "num_missing": number
                },
                "mean": number,
                "sum": number,
                "std_dev": number,
                "min": number,
                "max": number,
                "distribution": {
                    "kll": {
                        "buckets": [
                            {
                                "lower_bound": number,
                                "upper_bound": number,
                                "count": number
                            }
                        ],
                        "sketch": {
                            "parameters": {
                                "c": number,
                                "k": number
                            },
                            "data": [
                                [
                                    num,
                                    num,
                                    num,
                                    num
                                ],
                                [
                                    num,
                                    num
                                ][
                                    num,
                                    num
                                ]
                            ]
                        }#sketch
                    }#KLL
                }#distribution
            }#num_stats
        },
        {
            "name": "feature-name",
            "inferred_type": "String",
            "string_statistics": {
                "common": {
                    "num_present": number,
                    "num_missing": number
                },
                "distinct_count": number,
                "distribution": {
                    "categorical": {
                         "buckets": [
                                {
                                    "value": "string",
                                    "count": number
                                }
                          ]
                     }
                }
            },
            #provision for custom stats
        }
    ]
}
```

**備註**  
在稍後的視覺化變更中，SageMaker AI 可辨識指定的指標。如果需要，容器可以發出更多指標。
[KLL 草圖](https://datasketches.apache.org/docs/KLL/KLLSketch.html)是可辨識的草圖。自訂容器可以撰寫自己的表示法，但無法由 SageMaker AI 在視覺化中辨識。
依預設，分成 10 個儲存貯體將分佈具體化。這無法變更。

# 限制條件的結構描述 (constraints.json 檔案)
<a name="model-monitor-byoc-constraints"></a>

constraints.json 檔案是用來表達資料集必須滿足的限制條件。Amazon SageMaker Model Monitor 容器可以使用 constraints.json 檔案來評估資料集。預先建置的容器能夠為基準資料集自動產生 constraints.json 檔案。如果您使用自有容器，則可以在容器中提供類似的功能，或者，您可以用其他方式建立 constraints.json 檔案。以下是預先建置的容器所使用的限制條件檔案的結構描述。使用自有容器可以採用相同的格式，或依需要來增強。

```
{
    "version": 0,
    "features":
    [
        {
            "name": "string",
            "inferred_type": "Integral" | "Fractional" | 
                    | "String" | "Unknown",
            "completeness": number,
            "num_constraints":
            {
                "is_non_negative": boolean
            },
            "string_constraints":
            {
                "domains":
                [
                    "list of",
                    "observed values",
                    "for small cardinality"
                ]
            },
            "monitoringConfigOverrides":
            {}
        }
    ],
    "monitoring_config":
    {
        "evaluate_constraints": "Enabled",
        "emit_metrics": "Enabled",
        "datatype_check_threshold": 0.1,
        "domain_content_threshold": 0.1,
        "distribution_constraints":
        {
            "perform_comparison": "Enabled",
            "comparison_threshold": 0.1,
            "comparison_method": "Simple"||"Robust",
            "categorical_comparison_threshold": 0.1,
            "categorical_drift_method": "LInfinity"||"ChiSquared"
        }
    }
}
```

`monitoring_config` 物件包含用於監控功能工作的選項。下表描述各個選項。

監控限制條件

[\[See the AWS documentation website for more details\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/model-monitor-byoc-constraints.html)

# 適用於使用自有容器的 CloudWatch 指標
<a name="model-monitor-byoc-cloudwatch"></a>

在 `/opt/ml/processing/processingjobconfig.json` 檔案的 `Environment` 對應中，如果 `publish_cloudwatch_metrics` 值為 `Enabled`，容器程式碼會在此位置發出 Amazon CloudWatch 指標：`/opt/ml/output/metrics/cloudwatch`。

此檔案的結構描述緊密地以 `PutMetrics` API 為基礎。此處未指定命名空間。它預設為下列項目：
+ `For real-time endpoints: /aws/sagemaker/Endpoint/data-metrics`
+ `For batch transform jobs: /aws/sagemaker/ModelMonitoring/data-metrics`

但是，您可以指定維度。建議您至少增加以下維度：
+ 適用於即時端點的 `Endpoint` 和 `MonitoringSchedule`
+ 適用於批次轉換工作的 `MonitoringSchedule`

下列 JSON 程式碼片段顯示如何設定維度。

如果是即時端點，請參閱下列包含 `Endpoint` 和 `MonitoringSchedule` 維度的 JSON 程式碼片段：

```
{ 
    "MetricName": "", # Required
    "Timestamp": "2019-11-26T03:00:00Z", # Required
    "Dimensions" : [{"Name":"Endpoint","Value":"endpoint_0"},{"Name":"MonitoringSchedule","Value":"schedule_0"}]
    "Value": Float,
    # Either the Value or the StatisticValues field can be populated and not both.
    "StatisticValues": {
        "SampleCount": Float,
        "Sum": Float,
        "Minimum": Float,
        "Maximum": Float
    },
    "Unit": "Count", # Optional
}
```

如果是批次轉換工作，請參閱下列包含 `MonitoringSchedule` 維度的 JSON 程式碼片段：

```
{ 
    "MetricName": "", # Required
    "Timestamp": "2019-11-26T03:00:00Z", # Required
    "Dimensions" : [{"Name":"MonitoringSchedule","Value":"schedule_0"}]
    "Value": Float,
    # Either the Value or the StatisticValues field can be populated and not both.
    "StatisticValues": {
        "SampleCount": Float,
        "Sum": Float,
        "Minimum": Float,
        "Maximum": Float
    },
    "Unit": "Count", # Optional
}
```

# 使用 CloudFormation 自訂資源建立即時端點的監控排程
<a name="model-monitor-cloudformation-monitoring-schedules"></a>

如果您使用的是即時端點，您可以使用 CloudFormation 自訂資源來建立監控排程。自訂資源在 Python 中。若要部署，請參閱 [Python Lambda 部署](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html)。

## 自訂資源
<a name="model-monitor-cloudformation-custom-resource"></a>

首先，將自訂資源新增至您的 CloudFormation 範本。這會指向您在下一步中建立的 AWS Lambda 函式。

此資源可讓您自訂監控排程的參數。您可以在下列範例資源中修改 CloudFormation 資源和 Lambda 函數，以新增或移除更多參數。

```
{
    "AWSTemplateFormatVersion": "2010-09-09",
    "Resources": {
        "MonitoringSchedule": {
            "Type": "Custom::MonitoringSchedule",
            "Version": "1.0",
            "Properties": {
                "ServiceToken": "arn:aws:lambda:us-west-2:111111111111:function:lambda-name",
                "ScheduleName": "YourScheduleName",
                "EndpointName": "YourEndpointName",
                "BaselineConstraintsUri": "s3://your-baseline-constraints/constraints.json",
                "BaselineStatisticsUri": "s3://your-baseline-stats/statistics.json",
                "PostAnalyticsProcessorSourceUri": "s3://your-post-processor/postprocessor.py",
                "RecordPreprocessorSourceUri": "s3://your-preprocessor/preprocessor.py",
                "InputLocalPath": "/opt/ml/processing/endpointdata",
                "OutputLocalPath": "/opt/ml/processing/localpath",
                "OutputS3URI": "s3://your-output-uri",
                "ImageURI": "111111111111.dkr.ecr.us-west-2.amazonaws.com/your-image",
                "ScheduleExpression": "cron(0 * ? * * *)",
                "PassRoleArn": "arn:aws:iam::111111111111:role/AmazonSageMaker-ExecutionRole"
            }
        }
    }
}
```

## Lambda 自訂資源程式碼
<a name="model-monitor-cloudformation-lambda-custom-resource-code"></a>

此 CloudFormation 自訂資源使用[自訂資源協助程式](https://github.com/aws-cloudformation/custom-resource-helper) AWS 程式庫，您可以使用 安裝 搭配 pip`pip install crhelper`。

在建立和刪除堆疊 CloudFormation 期間， 會叫用此 Lambda 函數。此 Lambda 函式負責建立及刪除監控排程，以及使用上一節所述之自訂資源中定義的參數。

```
import boto3
import botocore
import logging

from crhelper import CfnResource
from botocore.exceptions import ClientError


logger = logging.getLogger(__name__)
sm = boto3.client('sagemaker')

# cfnhelper makes it easier to implement a CloudFormation custom resource
helper = CfnResource()

# CFN Handlers

def handler(event, context):
    helper(event, context)


@helper.create
def create_handler(event, context):
    """
    Called when CloudFormation custom resource sends the create event
    """
    create_monitoring_schedule(event)


@helper.delete
def delete_handler(event, context):
    """
    Called when CloudFormation custom resource sends the delete event
    """
    schedule_name = get_schedule_name(event)
    delete_monitoring_schedule(schedule_name)


@helper.poll_create
def poll_create(event, context):
    """
    Return true if the resource has been created and false otherwise so
    CloudFormation polls again.
    """
    schedule_name = get_schedule_name(event)
    logger.info('Polling for creation of schedule: %s', schedule_name)
    return is_schedule_ready(schedule_name)

@helper.update
def noop():
    """
    Not currently implemented but crhelper will throw an error if it isn't added
    """
    pass

# Helper Functions

def get_schedule_name(event):
    return event['ResourceProperties']['ScheduleName']

def create_monitoring_schedule(event):
    schedule_name = get_schedule_name(event)
    monitoring_schedule_config = create_monitoring_schedule_config(event)

    logger.info('Creating monitoring schedule with name: %s', schedule_name)

    sm.create_monitoring_schedule(
        MonitoringScheduleName=schedule_name,
        MonitoringScheduleConfig=monitoring_schedule_config)

def is_schedule_ready(schedule_name):
    is_ready = False

    schedule = sm.describe_monitoring_schedule(MonitoringScheduleName=schedule_name)
    status = schedule['MonitoringScheduleStatus']

    if status == 'Scheduled':
        logger.info('Monitoring schedule (%s) is ready', schedule_name)
        is_ready = True
    elif status == 'Pending':
        logger.info('Monitoring schedule (%s) still creating, waiting and polling again...', schedule_name)
    else:
        raise Exception('Monitoring schedule ({}) has unexpected status: {}'.format(schedule_name, status))

    return is_ready

def create_monitoring_schedule_config(event):
    props = event['ResourceProperties']

    return {
        "ScheduleConfig": {
            "ScheduleExpression": props["ScheduleExpression"],
        },
        "MonitoringJobDefinition": {
            "BaselineConfig": {
                "ConstraintsResource": {
                    "S3Uri": props['BaselineConstraintsUri'],
                },
                "StatisticsResource": {
                    "S3Uri": props['BaselineStatisticsUri'],
                }
            },
            "MonitoringInputs": [
                {
                    "EndpointInput": {
                        "EndpointName": props["EndpointName"],
                        "LocalPath": props["InputLocalPath"],
                    }
                }
            ],
            "MonitoringOutputConfig": {
                "MonitoringOutputs": [
                    {
                        "S3Output": {
                            "S3Uri": props["OutputS3URI"],
                            "LocalPath": props["OutputLocalPath"],
                        }
                    }
                ],
            },
            "MonitoringResources": {
                "ClusterConfig": {
                    "InstanceCount": 1,
                    "InstanceType": "ml.t3.medium",
                    "VolumeSizeInGB": 50,
                }
            },
            "MonitoringAppSpecification": {
                "ImageUri": props["ImageURI"],
                "RecordPreprocessorSourceUri": props['PostAnalyticsProcessorSourceUri'],
                "PostAnalyticsProcessorSourceUri": props['PostAnalyticsProcessorSourceUri'],
            },
            "StoppingCondition": {
                "MaxRuntimeInSeconds": 300
            },
            "RoleArn": props["PassRoleArn"],
        }
    }


def delete_monitoring_schedule(schedule_name):
    logger.info('Deleting schedule: %s', schedule_name)
    try:
        sm.delete_monitoring_schedule(MonitoringScheduleName=schedule_name)
    except ClientError as e:
        if e.response['Error']['Code'] == 'ResourceNotFound':
            logger.info('Resource not found, nothing to delete')
        else:
            logger.error('Unexpected error while trying to delete monitoring schedule')
            raise e
```

# 模型監控常見問答集
<a name="model-monitor-faqs"></a>

如需有關 Amazon SageMaker Model Monitor 的詳細資訊，請參閱下列常見問答集。

**問：模型監控和 SageMaker Clarify 如何協助客戶監控模型行為？**

客戶可以透過 Amazon SageMaker Model Monitor 和 SageMaker Clarify 來監控以下四個維度的模型行為：[資料品質](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-data-quality.html)、[模型品質](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-model-quality.html)、[偏差偏離](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-monitor-bias-drift.html)和[功能屬性偏離](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-monitor-feature-attribution-drift.html)。[模型監控](https://aws.amazon.com/sagemaker/model-monitor/)會持續監控生產中 Amazon SageMaker AI 機器學習模型的品質。這包括監控資料品質和模型品質指標的偏離 (例如準確度和 RMSE)。[SageMaker Clarify](https://aws.amazon.com/sagemaker/clarify/?sagemaker-data-wrangler-whats-new.sort-by=item.additionalFields.postDateTime&sagemaker-data-wrangler-whats-new.sort-order=desc) 偏差監控可協助資料科學家和機器學習 (ML) 工程師監控模型預測和功能屬性偏離中的偏差。

**問：啟用 Sagemaker Model Monitor 時，在背景中會發生什麼情況？**

Amazon SageMaker Model Monitor 可自動進行模型監控，因此無需手動監控模型或建置任何其他工具。為了將程序自動化，模型監控可讓您使用訓練模型的資料來建立一組基準統計資料和限制條件，然後設定排程以監控在端點上進行的預測。模型監控會使用規則來偵測模型中的偏離，並在發生偏離時向您提出警示。下列步驟說明啟用模型監控時會發生什麼情況：
+ **啟用模型監控**：對於即時端點，您必須啟用端點將傳入請求中的資料擷取到部署的機器學習 (ML) 模型，以及產生的模型預測。對於批次轉換工作，啟用批次轉換輸入和輸出的資料擷取。
+ **基準處理工作**：然後從用來訓練模型的資料集建立基準。基準會計算指標，並建議指標的限制條件。例如，模型的回呼分數不應迴歸並降至 0.571 以下，或精確度分數不應低於 1.0。模型中的即時或批次預測會與限制條件進行比較，如果超出限制條件值，則會報告為違規。
+ **監控工作**：然後建立監控排程，指定要收集哪些資料、收集資料的頻率、如何分析資料，以及要產生哪些報告。
+ **合併工作**：這只有在您利用 Amazon SageMaker Ground Truth 時才適用。模型監控會將模型所做的預測與 Ground Truth 標籤進行比較，以測量模型的品質。為了這麼做，您可以定期標籤端點或批次轉換工作擷取的資料，並將其上傳到 Amazon S3。

  建立並上傳 Ground Truth 標籤後，在建立監控工作時將標籤的位置納入為參數。

當您使用模型監控來監控批次轉換工作而非即時端點時，則不會接收端點的要求和追蹤預測，而是模型監控會監控推論輸入和輸出。在模型監控排程中，客戶會提供要用於處理工作的執行個體計數和類型。無論目前執行的狀態為何，這些資源都會保留，直到刪除排程為止。

**問：什麼是資料擷取，為什麼需要資料擷取，以及如何啟用？**

為了將模型端點的輸入和從部署模型的推論輸出記錄到 Amazon S3，您可以啟用名為[資料擷取](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-data-capture.html)的功能。如需有關如何為即時端點和批次轉換工作啟用此功能的詳細資訊，請參閱[從即時端點擷取資料](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-data-capture-endpoint.html)和[從批次轉換工作擷取資料](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-data-capture-batch.html)。

**問：啟用資料擷取是否會影響即時端點的效能？**

資料擷取以非同步方式進行，不會影響生產流量。在啟用資料擷取後，請求和回應承載以及一些其他中繼資料會儲存在您於 `DataCaptureConfig` 中指定的 Amazon S3 位置。請注意，將擷取的資料傳播到 Amazon S3 可能會延遲。

您也可以列出儲存在 Amazon S3 中的資料擷取檔案以檢視擷取日期。Amazon S3 路徑的格式為：`s3:///{endpoint-name}/{variant-name}/yyyy/mm/dd/hh/filename.jsonl`。Amazon S3 資料擷取應與模型監控排程位於同一區域。您也應確定基準資料集的欄位名稱只有小寫字母和一個底線 (`_`) 做為唯一的分隔符號。

**問：為什麼模型監控需要 Ground Truth？**

模型監控的以下功能需要 Ground Truth 標籤：
+ **模型品質監控**會將模型所做的預測與 Ground Truth 標籤進行比較，以測量模型的品質。
+ **模型偏差監控**會監控偏差的預測。當訓練中使用的資料與用於產生預測的資料不同時，會在部署的機器學習 (ML) 模型中導致偏差。如果用於訓練的資料隨著時間變更 (例如抵押貸款利率波動)，則除非使用更新的資料重新訓練模型，否則模型預測不夠準確，在此情況下會特別明顯。例如，如果用於訓練模型的抵押貸款利率與真實世界最目前的抵押貸款利率不同，則用於預測房屋價格的模型可能會偏差。

**問：對於利用 Ground Truth 進行標籤的客戶，我可以採取哪些步驟來監控模型的品質？**

模型品質監控會將模型所做的預測與 Ground Truth 標籤進行比較，以測量模型的品質。為了這麼做，您可以定期標籤端點或批次轉換工作擷取的資料，並將其上傳到 Amazon S3。除了擷取之外，模型偏差監控執行還需要 Ground Truth 資料。在實際使用案例中，應定期收集 Ground Truth 資料並上傳到指定的 Amazon S3 位置。為了讓 Ground Truth 標籤與擷取的預測資料相符，資料集中的每個記錄都必須有唯一識別碼。如需了解每個記錄有關 Ground Truth 資料的結構，請參閱[擷取 Ground Truth 標籤並將其與預測合併](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-model-quality-merge.html)。

下面的程式碼範例可用於產生表格式資料集的人工 Ground Truth 資料。

```
import random

def ground_truth_with_id(inference_id):
    random.seed(inference_id)  # to get consistent results
    rand = random.random()
    # format required by the merge container
    return {
        "groundTruthData": {
            "data": "1" if rand < 0.7 else "0",  # randomly generate positive labels 70% of the time
            "encoding": "CSV",
        },
        "eventMetadata": {
            "eventId": str(inference_id),
        },
        "eventVersion": "0",
    }


def upload_ground_truth(upload_time):
    records = [ground_truth_with_id(i) for i in range(test_dataset_size)]
    fake_records = [json.dumps(r) for r in records]
    data_to_upload = "\n".join(fake_records)
    target_s3_uri = f"{ground_truth_upload_path}/{upload_time:%Y/%m/%d/%H/%M%S}.jsonl"
    print(f"Uploading {len(fake_records)} records to", target_s3_uri)
    S3Uploader.upload_string_as_file_body(data_to_upload, target_s3_uri)
# Generate data for the last hour
upload_ground_truth(datetime.utcnow() - timedelta(hours=1))
# Generate data once a hour
def generate_fake_ground_truth(terminate_event):
    upload_ground_truth(datetime.utcnow())
    for _ in range(0, 60):
        time.sleep(60)
        if terminate_event.is_set():
            break


ground_truth_thread = WorkerThread(do_run=generate_fake_ground_truth)
ground_truth_thread.start()
```

下面的程式碼範例顯示如何產生人工流量以傳送至模型端點。請注意上面用於調用的 `inferenceId` 屬性。如果此屬性存在，會用於與 Ground Truth 資料聯結 (否則，會使用 `eventId`)。

```
import threading

class WorkerThread(threading.Thread):
    def __init__(self, do_run, *args, **kwargs):
        super(WorkerThread, self).__init__(*args, **kwargs)
        self.__do_run = do_run
        self.__terminate_event = threading.Event()

    def terminate(self):
        self.__terminate_event.set()

    def run(self):
        while not self.__terminate_event.is_set():
            self.__do_run(self.__terminate_event)
def invoke_endpoint(terminate_event):
    with open(test_dataset, "r") as f:
        i = 0
        for row in f:
            payload = row.rstrip("\n")
            response = sagemaker_runtime_client.invoke_endpoint(
                EndpointName=endpoint_name,
                ContentType="text/csv",
                Body=payload,
                InferenceId=str(i),  # unique ID per row
            )
            i += 1
            response["Body"].read()
            time.sleep(1)
            if terminate_event.is_set():
                break


# Keep invoking the endpoint with test data
invoke_endpoint_thread = WorkerThread(do_run=invoke_endpoint)
invoke_endpoint_thread.start()
```

您必須將 Ground Truth 資料上傳到路徑格式與擷取資料相同的 Amazon S3 儲存貯體，格式如下：`s3://<bucket>/<prefix>/yyyy/mm/dd/hh`

**注意**  
此路徑中的日期是收集 Ground Truth 標籤的日期。它不一定要符合產生推論的日期。

**問：客戶如何自訂監控排程？**

除了使用內建的監控機制之外，您還可以使用預先處理和後製處理指令碼，或使用或建置您自己的容器，以建立您自己的自訂監控排程和程序。請務必注意，預先處理和後製處理指令碼僅適用於資料和模型品質工作。

Amazon SageMaker AI 為您提供監控和評估模型端點所觀察到資料的功能。為此，您必須建立與即時流量進行比較的基準。準備好基準後，設定排程以持續評估並與基準進行比較。建立排程時，您可以提供預先處理和後製處理指令碼。

下列範例顯示如何使用預先處理和後製處理指令碼來自訂監控排程。

```
import boto3, osfrom sagemaker import get_execution_role, Sessionfrom sagemaker.model_monitor import CronExpressionGenerator, DefaultModelMonitor
# Upload pre and postprocessor scripts
session = Session()
bucket = boto3.Session().resource("s3").Bucket(session.default_bucket())
prefix = "demo-sagemaker-model-monitor"
pre_processor_script = bucket.Object(os.path.join(prefix, "preprocessor.py")).upload_file("preprocessor.py")
post_processor_script = bucket.Object(os.path.join(prefix, "postprocessor.py")).upload_file("postprocessor.py")
# Get execution role
role = get_execution_role() # can be an empty string
# Instance type
instance_type = "instance-type"
# instance_type = "ml.m5.xlarge" # Example
# Create a monitoring schedule with pre and post-processing
my_default_monitor = DefaultModelMonitor(
    role=role,
    instance_count=1,
    instance_type=instance_type,
    volume_size_in_gb=20,
    max_runtime_in_seconds=3600,
)

s3_report_path = "s3://{}/{}".format(bucket, "reports")
monitor_schedule_name = "monitor-schedule-name"
endpoint_name = "endpoint-name"
my_default_monitor.create_monitoring_schedule(
    post_analytics_processor_script=post_processor_script,
    record_preprocessor_script=pre_processor_script,
    monitor_schedule_name=monitor_schedule_name,
    # use endpoint_input for real-time endpoint
    endpoint_input=endpoint_name,
    # or use batch_transform_input for batch transform jobs
# batch_transform_input=batch_transform_name,
    output_s3_uri=s3_report_path,
    statistics=my_default_monitor.baseline_statistics(),
    constraints=my_default_monitor.suggested_constraints(),
    schedule_cron_expression=CronExpressionGenerator.hourly(),
    enable_cloudwatch_metrics=True,
)
```

**問：有哪些我可以利用預先處理指令碼的情況或使用案例？**

當您需要將輸入轉換為模型監控時，可以使用預先處理指令碼。請思考下列範例情況：

1. 預先處理指令碼進行資料轉換。

   假設模型的輸出是陣列：`[1.0, 2.1]`。模型監控容器僅適用於表格式或扁平化 JSON 結構，例如 `{“prediction0”: 1.0, “prediction1” : 2.1}`。您可以使用如下範例的預先處理指令碼，將陣列轉換為正確的 JSON 結構。

   ```
   def preprocess_handler(inference_record):
       input_data = inference_record.endpoint_input.data
       output_data = inference_record.endpoint_output.data.rstrip("\n")
       data = output_data + "," + input_data
       return { str(i).zfill(20) : d for i, d in enumerate(data.split(",")) }
   ```

1. 從模型監控的指標計算中排除某些記錄。

   假設您的模型具有可選功能，並且您使用 `-1` 來表示可選功能有缺少值。如果您有資料品質監控，您可能想要將 `-1` 從輸入值陣列中移除，這樣它就不會包含在監控的指標計算中。您可以使用如下所示的指令碼來移除這些值。

   ```
   def preprocess_handler(inference_record):
       input_data = inference_record.endpoint_input.data
       return {i : None if x == -1 else x for i, x in enumerate(input_data.split(","))}
   ```

1. 套用自訂取樣策略。

   您也可以在預先處理指令碼中套用自訂取樣策略。若要這麼做，請設定模型監控的第一方預先建置容器，根據您指定的取樣率忽略某個百分比的記錄。在下列範例中，處理常式會取樣 10% 的記錄，傳回 10% 的處理常式呼叫的記錄，其餘為空白清單。

   ```
   import random
   
   def preprocess_handler(inference_record):
       # we set up a sampling rate of 0.1
       if random.random() > 0.1:
           # return an empty list
           return []
       input_data = inference_record.endpoint_input.data
       return {i : None if x == -1 else x for i, x in enumerate(input_data.split(","))}
   ```

1. 使用自訂記錄。

   您可以將指令碼中所需的任何資訊記錄至 Amazon CloudWatch。這在發生錯誤對預先處理指令碼進行偵錯時非常有用。以下範例顯示如何使用 `preprocess_handler` 介面記錄至 CloudWatch。

   ```
   def preprocess_handler(inference_record, logger):
       logger.info(f"I'm a processing record: {inference_record}")
       logger.debug(f"I'm debugging a processing record: {inference_record}")
       logger.warning(f"I'm processing record with missing value: {inference_record}")
       logger.error(f"I'm a processing record with bad value: {inference_record}")
       return inference_record
   ```

**注意**  
在批次轉換資料上執行預先處理指令碼時，輸入類型並非永遠是 `CapturedData` 物件。如果是 CSV 資料，類型為字串。如果是 JSON 資料，類型是 Python 字典。

**問：何時可以利用後製處理指令碼？**

成功執行監控後，您可以利用後製處理指令碼做為延伸。以下是簡單的範例，但是您可以執行或呼叫在成功執行監控之後需要執行的任何業務函式。

```
def postprocess_handler(): 
    print("Hello from the post-processing script!")
```

**問：何時應考慮使用自有容器進行模型監控？**

SageMaker AI 提供預先建置的容器，分析從表格式資料集的端點或批次轉換任務擷取的資料。不過，在某些情況下，您可能會想要建立自有容器。請考量下列情況：
+ 您有法規和合規需求，只能使用在組織內部建立和維護的容器。
+ 如果您想要包含一些第三方程式庫，您可以將 `requirements.txt` 檔案放置在本機目錄中，並使用 [SageMaker AI 估算器](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Estimator)中的 `source_dir` 參數來參照該檔案，以便在執行時期啟用程式庫安裝。不過，如果您執行訓練工作時有許多程式庫或相依性會增加的安裝時間，您可能會想要利用 BYOC。
+ 您的環境強制要求沒有網際網路連線 (或 Silo)，因此無法下載套件。
+ 您想要監控除表格式以外的資料格式的資料，例如 NLP 或 CV 使用案例。
+ 當您需要模型監控所支援的監控指標以外的監控指標時。

**問：我有 NLP 和 CV 模型。如何對其監控資料偏離？**

Amazon SageMaker AI 的預先建置容器支援表格式資料集。如果要監控 NLP 和 CV 模型，可以利用模型監控提供的延伸點來使用自有容器。如需有關此需求的更多詳細資訊，請參閱[使用自有容器](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-byoc-containers.html)。下列為更多範例：
+ 如需如何針對電腦視覺使用案例使用模型監控的詳細說明，請參閱[偵測和分析不正確的預測](https://aws.amazon.com/blogs/machine-learning/detecting-and-analyzing-incorrect-model-predictions-with-amazon-sagemaker-model-monitor-and-debugger/)。
+ 如需針對 NLP 使用案例使用模型監控的案例，請參閱[使用自訂 Amazon SageMaker Model Monitor 來偵測 NLP 資料偏離](https://aws.amazon.com/blogs/machine-learning/detect-nlp-data-drift-using-custom-amazon-sagemaker-model-monitor/)。

**問：我想要刪除已啟用模型監控的模型端點，但是由於監控排程仍作用中，所以我無法這樣做。我該怎麼辦？**

如果您要刪除在 SageMaker AI 中託管且已啟用 Model Monitor 的推論端點，必須先刪除模型監控排程 (使用 `DeleteMonitoringSchedule` [CLI](https://docs.aws.amazon.com/cli/latest/reference/sagemaker/delete-monitoring-schedule.html) 或 [API](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DeleteMonitoringSchedule.html))。然後再刪除端點。

**問：SageMaker Model Monitor 是否會計算輸入的指標和統計資料？**

模型監控會計算輸出的指標和統計資料，而不是輸入。

**問：SageMaker Model Monitor 是否支援多模型端點？**

否，模型監控僅支援託管單一模型的端點，不支援監控多模型端點。

**問：SageMaker Model Monitor 是否提供在推論管道中有關個別容器的監控資料？**

模型監控支援監控推論管道，但擷取和分析資料是針對整個管道完成的，而不是針對管道中的單個容器。

**問：在設定資料擷取時，如何防止對推論請求造成影響？**

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

**問：Amazon S3 Data Capture 是否可以與設定監控排程 AWS 的區域位於不同的區域？**

否，Amazon S3 資料擷取必須與模型監控排程位於同一區域。

**問：什麼是基準？如何建立基準？ 我可以建立自訂基準嗎？**

基準用作比較模型中的即時或批次預測的參考。它會計算統計資料和指標及其限制條件。在監控期間，所有這些項目都會結合使用來識別違規。

若要使用 Amazon SageMaker Model Monitor 的預設解決方案，您可以利用 [Amazon SageMaker Python](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html) SDK。特別是，使用 [ModelMonitor](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html#sagemaker.model_monitor.model_monitoring.DefaultModelMonitor) 或 [ModelQualityMonitor](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html#sagemaker.model_monitor.model_monitoring.ModelQualityMonitor) 類別的 [suggest\$1baseline](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html#sagemaker.model_monitor.model_monitoring.DefaultModelMonitor.suggest_baseline) 方法來觸發處理工作，以計算基準的指標和限制條件。

基準工作的結果為兩個檔案：`statistics.json` 和 `constraints.json`。[統計資料的結構描述](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-byoc-statistics.html)和[限制條件的結構描述](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-byoc-constraints.html)包含對應檔案的結構描述。您可以檢視產生的限制條件並進行修改，然後再將其用於監控。根據您對網域和企業問題的瞭解，您可以讓限制條件更積極，或放寬限制條件以控制違規的數量和性質。

**問：建立基準資料集的指南為何？**

任何監控類型的主要需求都是具有用於計算指標和限制條件的基準資料集。通常，這會是模型使用的訓練資料集，但在某些情況下，您可能會選擇使用其他參考資料集。

基準資料集的欄位名稱應與 Spark 相容。為了保持 Spark、CSV、JSON 和 Parquet 之間的最大相容性，建議僅使用小寫字母，並且僅用 `_` 做為分隔符號。包括 `“ ”` 的特殊字元可能導致問題。

**問：`StartTimeOffset` 和 `EndTimeOffset` 參數是什麼？要何時使用？**

當需要 Amazon SageMaker Ground Truth 來監控模型品質等工作時，您需要確保監控工作只使用可用 Ground Truth 的資料。[EndpointInput](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html#sagemaker.model_monitor.model_monitoring.EndpointInput) 的 `start_time_offset` 和 `end_time_offset` 參數可用來選取監控工作所使用的資料。監控工作會使用在 `start_time_offset` 和 `end_time_offset` 定義的時段中的資料。這些參數必須以 [ISO 8601 持續時間格式](https://en.wikipedia.org/wiki/ISO_8601#Durations)指定。下列是一些範例：
+ 如果 Ground Truth 結果在進行預測後 3 天到達，則設定 `start_time_offset="-P3D"` 和 `end_time_offset="-P1D"`，分別為 3 天和 1 天。
+ 如果 Ground Truth 結果在預測後 6 小時到達，並且您有每小時的排程，則設定 `start_time_offset="-PT6H"` 和 `end_time_offset="-PT1H"`，即 6 小時和 1 小時。

**問：是否可以執行 '隨需' 監控工作？**

可以，您可以透過執行 SageMaker Processing 工作來執行 '隨需' 監控工作。對於批次轉換，[Pipelines](https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-overview.html) 具有 [MonitorBatchTransformStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.monitor_batch_transform_step.MonitorBatchTransformStep)，您可以用來建立一個 SageMaker AI 管道，隨需執行監控任務。SageMaker AI 範例儲存庫具有用於隨需執行[資料品質](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker_model_monitor/model_monitor_batch_transform/SageMaker-ModelMonitoring-Batch-Transform-Data-Quality-With-SageMaker-Pipelines-On-Demand.ipynb)和[模型品質](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker_model_monitor/model_monitor_batch_transform/SageMaker-ModelMonitoring-Batch-Transform-Model-Quality-With-SageMaker-Pipelines-On-Demand.ipynb)監控任務的程式碼範例。

**問：如何設定模型監控？**

您可以使用下列方式來設定模型監控：
+ **[Amazon SageMaker AI Python SDK](https://sagemaker.readthedocs.io/en/stable/index.html)** - 有一個 [Model Monitor 模組](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html)，其中包含可協助建議基準、建立監控排程等的類別和函式。請參閱 [Amazon SageMaker Model Monitor 筆記本範例](https://github.com/aws/amazon-sagemaker-examples/tree/main/sagemaker_model_monitor)，以取得利用 SageMaker AI Python SDK 以設定模型監控的詳細筆記本。
+ **[Pipelines](https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-overview.html)** - Pipelines 透過 [QualityCheck Step](https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html#step-type-quality-check) 和 [ClarifyCheckStep](https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html#step-type-clarify-check) API 與 Model Monitor 整合。您可以建立一個包含這些步驟的 SageMaker AI 管道，在每次執行管道時可用於隨需執行監控任務。
+ **[Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio.html)** - 您可以從已部署的模型端點清單中選取端點，直接從使用者介面建立資料或模型品質監控排程以及模型偏差和可解釋性排程。您可以在使用者介面中選取相關索引標籤，來建立其他類型監控的排程。
+ **[SageMaker 模型儀表板](https://docs.aws.amazon.com/sagemaker/latest/dg/model-dashboard.html)** — 您可以選取已部署到端點的模型來啟用端點上的監控。在 SageMaker AI 主控台的下列螢幕擷取畫面中，已從**模型儀表板**的**模型**區段中選取名為 `group1` 的模型。您可以在此頁面建立監控排程，也可以編輯、啟動或停用現有的監控排程和警示。如需有關如何檢視警示和模型監控排程的逐步指南，請參閱[檢視模型監控排程和警示](https://docs.aws.amazon.com/sagemaker/latest/dg/model-dashboard-schedule.html)。

![\[模型儀表板的螢幕擷取畫面，顯示建立監控排程的選項。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/model-monitoring-faqs-screenshot.png)


**問：模型監控如何與 SageMaker 模型儀表板整合**

[SageMaker 模型儀表板](https://docs.aws.amazon.com/sagemaker/latest/dg/model-dashboard.html)透過提供有關預期行為偏差的自動警示以及疑難排解，以檢查模型並分析隨著時間影響模型效能的因素，為您提供涵蓋所有模型的統一監控。