

本文属于机器翻译版本。若本译文内容与英语原文存在差异，则一律以英文原文为准。

# 使用 Amazon 模型监视器监控数据和 SageMaker 模型质量
<a name="model-monitor"></a>

Amazon SageMaker Model Monitor 监控生产中亚马逊 SageMaker AI 机器学习模型的质量。通过模型监控器，您可以设置
+ 利用实时端点进行持续监控。
+ 通过定期运行的批量转换任务进行持续监控。
+ 对异步批量转换作业进行计划监控。

借助 Model Monitor，您可以设置警报，以便在模型质量出现偏差时通知您。及早主动发现这些偏差，就能采取纠正措施。您可以采取重新训练模型、审核上游系统或修复质量问题等措施，而无需手动监控模型或构建额外的工具。您可以使用不需要编码的 Model Monitor 预构建监控功能。您还可以通过编码来提供自定义分析，从而灵活地监控模型。

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-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-pre-built-container.md)
+ [解释结果](model-monitor-interpreting-results.md)
+ [在 Amazon SageMaker Studio 中可视化实时端点的结果](model-monitor-interpreting-visualize-results.md)
+ [高级主题](model-monitor-advanced-topics.md)
+ [模型监视器 FAQs](model-monitor-faqs.md)

# 监控生产中的模型
<a name="how-it-works-model-monitor"></a>

将模型部署到生产环境后，使用 Amazon SageMaker 模型监控器持续实时监控机器学习模型的质量。Amazon SageMaker 模型监控器允许您在模型质量出现偏差（例如数据漂移和异常）时设置自动警报触发系统。Amazon Log CloudWatch s 收集监控模型状态的日志文件，并在模型质量达到您预设的特定阈值时发出通知。 CloudWatch 将日志文件存储到您指定的 Amazon S3 存储桶中。通过模型监视器产品及早主动检测 AWS 模型偏差，使您能够迅速采取措施来维护和提高已部署模型的质量。

有关 SageMaker 模型监控产品的更多信息，请参阅[使用 Amazon 模型监视器监控数据和 SageMaker 模型质量](model-monitor.md)。

要开始使用 SageMaker AI 进行机器学习之旅，请在 Se [t Up SageMaker AI 上](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-set-up.html)注册一个 AWS 帐户。

## Amazon SageMaker 模型监视器的工作原理
<a name="model-monitor-how-it-works"></a>

Amazon M SageMaker odel Monitor 会自动监控生产中的机器学习 (ML) 模型，并在出现质量问题时通知您。Model Monitor 使用规则来检测模型中的偏差，并在出现偏差时提醒您。下图显示了将模型部署到实时端点情况下此过程的工作原理。

![\[使用 Amazon 模型监视器监控 SageMaker 模型的流程。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/model_monitor/mmv2-architecture.png)


您还可以使用 Model Monitor 来监控批量转换作业，而不是实时端点。在这种情况下，模型监控器不是接收对端点的请求并跟踪预测结果，而是监控推理的输入和输出。下图显示了监控批量转换作业的过程。

![\[使用 Amazon 模型监视器监控 SageMaker 模型的流程。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/model_monitor/mmv2-architecture-batch.png)


要启用模型监控，请采取以下步骤。这些步骤跟踪数据在各种数据收集、监测和分析过程中的路径。
+ 对于实时端点，支持该端点捕获从传入请求到已训练机器学习模型的数据以及由此产生的模型预测结果。
+ 对于批量转换作业，支持捕获批量转换输入和输出的数据。
+ 从用于训练模型的数据集创建基准。该基准会计算指标并建议指标的约束条件。将模型的实时或批量预测结果与约束条件进行比较。如果超出限制值，则报告为违规。
+ 创建一个监控计划，该计划指定要收集的数据、数据收集频率、数据分析方式以及生成的报告。
+ 检查报告，将最新数据与基线数据进行比较。留意亚马逊举报的任何违规行为、指标和通知 CloudWatch。

**注意**  
Model Monitor 仅计算表格数据的模型指标和统计数据。例如，仍然可以监控将图像作为输入并根据该图像输出标签的图像分类模型。Model Monitor 将能够计算输出（而不是输入）的指标和统计数据。
Model Monitor 目前仅支持托管单个模型的端点，不支持监控多模型端点。有关使用多模型终端节点的信息，请参阅[多模型端点](multi-model-endpoints.md)。
模型监控器支持对推理管道进行监控。不过，采集和分析数据的对象是整个管道，而不是管道中的单个容器。
为了防止对推理请求产生影响，数据捕获功能会在磁盘利用率较高时停止捕获请求。我们建议您将磁盘利用率保持在 75% 以下，以确保数据捕获继续捕获请求。
如果您在自定义 Amazon VPC 中启动 SageMaker Studio，则必须创建 VPC 终端节点才能让模型监控器与 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)。

### 模型监测样本笔记本
<a name="model-monitor-sample-notebooks"></a>

有关使用模型监控器和实时终端节点完成 end-to-end工作流程的示例笔记本，请参阅 [Amazon SageMaker 模型监控器简介](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)。

有关如何创建和访问可用于在 SageMaker AI 中运行示例的 Jupyter 笔记本实例的说明，请参阅。[Amazon SageMaker 笔记本实例](nbi.md)创建并打开笔记本实例后，选择 “**SageMaker AI 示例**” 选项卡以查看所有 SageMaker AI 示例的列表。要打开笔记本，请选择笔记本的**使用**选项卡，然后选择**创建副本**。

# 数据采集
<a name="model-monitor-data-capture"></a>

要将端点的输入以及已部署模型的推理输出记录到 Amazon S3，可以启用名为*数据捕获* 的特征。*数据捕获* 通常用于记录可用于训练、调试和监控的信息。Amazon SageMaker Model Monitor 会自动解析这些捕获的数据，并将这些数据中的指标与您为模型创建的基准进行比较。有关 Model Monitor 的更多信息，请参阅[使用 Amazon 模型监视器监控数据和 SageMaker 模型质量](model-monitor.md)。

您可以使用 AWS SDK for Python (Boto) 或 Pyth SageMaker on SDK 为实时和批处理模型监视器模式实现*数据捕获*。对于实时端点，您将在创建端点时指定*数据捕获* 配置。由于实时端点具有持久性，您可以配置其他选项，以便在特定时间开启或关闭数据捕获功能，或者更改采样频率。您也可以选择对推理数据进行加密。

对于批量转换作业，如果您要按计划运行模型监控或对常规的定期批量转换作业进行持续模型监控，则可以启用*数据捕获*。创建批量转换作业时，您将指定*数据捕获* 配置。在此配置中，您可以选择开启加密功能，或在输出时生成推理 ID，这有助于将捕获的数据与 Ground Truth 数据进行匹配。

# 从实时端点捕获数据
<a name="model-monitor-data-capture-endpoint"></a>

**注意**  
为了防止对推理请求产生影响，数据捕获功能会在磁盘利用率较高时停止捕获请求。建议将磁盘利用率保持在 75% 以下，以确保数据捕获功能继续捕获请求。

要为实时终端节点捕获数据，必须使用 SageMaker AI 托管服务部署模型。这需要您创建 A SageMaker I 模型、定义端点配置并创建 HTTPS 终端节点。

无论你使用还是 SageMaker Python SDK，开启数据采集所需的步骤都是相似的。 AWS SDK for Python (Boto) 如果您使用 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` 参数。

要使用后续的代码片段，请用您自己的信息替换示例代码*italicized placeholder text*中的。

## 如何启用数据捕获
<a name="model-monitor-data-capture-defing.title"></a>

指定数据捕获配置。可以使用此配置捕获请求负载和/或响应负载。接下来的代码片段演示了如何使用 AWS SDK for Python (Boto) 和 SageMaker AI Python SDK 启用数据采集。

**注意**  
您无需使用 Model Monitor 来捕获请求或响应负载。

------
#### [ AWS SDK for Python (Boto) ]

使用`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 A [CreateEndpointConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html) SageMaker I 服务 API 参考指南中的 API](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_Operations_Amazon_SageMaker_Service.html)。

------
#### [ 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 UR SageMaker I 人工智能将用于存储捕获的数据。如果您不提供， 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 提供端点配置。该服务会启动机器学习计算实例，并按照配置中的规定部署一个或多个模型。

完成模型和端点配置后，可使用 [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)
```

使用模型对象的内置 `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 预测器类中创建[预测器](https://sagemaker.readthedocs.io/en/stable/api/inference/predictors.html)对象。在以后的一个步骤中，您将使用 `Predictor` 类返回的对象来调用端点。提供端点的名称（前面定义为 `endpoint_name`），以及分别用于序列化程序和反序列化程序的序列化程序对象和反序列化程序对象。有关序列化器类型的信息，请参阅 AI [SageMaker Python](https://sagemaker.readthedocs.io/en/stable/index.html) SDK 中的[序列化器](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 的 JSOnline 格式的文件。以下是从我们使用 `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 SDK 还是 SageMaker Python SDK，为批处理转换作业开启数据采集所需的步骤都是相似的。 AWS SDK for Python (Boto) 如果您使用 AWS SDK，请在`CreateTransformJob`方法中定义[DataCaptureConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataCaptureConfig.html)字典以及必填字段，以开启数据采集。如果您使用 SageMaker AI Python SDK，请导入该`BatchDataCaptureConfig`类并从该类初始化一个实例。然后，将此对象传递给转换作业实例的 `batch_data_capture_config` 参数。

 要使用以下代码片段，请用您自己的信息替换示例代码*italicized placeholder text*中的。

## 如何启用数据捕获
<a name="data-capture-batch-enable"></a>

 启动转换作业时指定数据捕获配置。无论您使用还是 SageMaker Python SDK，都必须提供`DestinationS3Uri`参数，即您希望转换作业记录捕获数据的目录。 适用于 Python (Boto3) 的 AWS SDK （可选）您还可以设置以下参数：
+  `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 前缀整理和标记这些清单，以指示它们何时被捕获。这有助于 Model Monitor 确定要分析的数据的相应部分。例如，如果您在 2022-8-26 13PM UTC 开始转换作业，则捕获的数据将标有 `2022/08/26/13/` 前缀字符串。

## InferenceId 世代
<a name="data-capture-batch-inferenceid"></a>

 为转换作业配置 `DataCaptureConfig` 时，可以打开布尔标志 `GenerateInferenceId`。当您需要运行模型质量和模型偏差监控作业（需要用户摄取的 Ground Truth 数据）时，这特别有用。Model Monitor 依靠推理 ID 来匹配捕获的数据和 Ground Truth 数据。有关 Ground Truth 摄取的更多详细信息，请参阅[输入地面实况标签并与预测结果合并](model-monitor-model-quality-merge.md)。打开 `GenerateInferenceId` 后，转换输出会为每条记录附加推理 ID（随机 UUID）以及转换作业开始时间 (UTC)。运行模型质量和模型偏差监控时需要这两个值。构造 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) 模型，并在出现数据质量问题时向您发送通知。生产中的机器学习模型必须对实际数据进行预测，而这些数据并不像大多数训练数据集那样经过了精心策划。如果模型在生产过程中接收到的数据的统计性质偏离了训练所依据的基准数据的性质，则模型将开始失去其预测的准确性。Amazon SageMaker 模型监控器使用规则来检测数据偏差，并在出现偏差时提醒您。要监控数据质量，请执行以下步骤：
+ 启用数据捕获。这会捕获来自实时推理端点或批量转换作业的推理输入和输出，并将数据存储在 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 指标](model-monitor-interpreting-cloudwatch.md)。
+ 解释监控作业的结果。有关更多信息，请参阅 [解释结果](model-monitor-interpreting-results.md)。
+ 如果您使用的是实时端点，请使用 SageMaker Studio 启用数据质量监控并可视化结果。有关更多信息，请参阅 [在 Amazon SageMaker Studio 中可视化实时端点的结果](model-monitor-interpreting-visualize-results.md)。

**注意**  
Model Monitor 仅计算表格数据的模型指标和统计数据。例如，仍然可以监控将图像作为输入并根据该图像输出标签的图像分类模型。Model Monitor 将能够计算输出（而不是输入）的指标和统计数据。

**Topics**
+ [创建基准](model-monitor-create-baseline.md)
+ [计划数据质量监控作业](model-monitor-schedule-data-monitor.md)
+ [统计数据的架构（statistics.json 文件）](model-monitor-interpreting-statistics.md)
+ [CloudWatch 指标](model-monitor-interpreting-cloudwatch.md)
+ [违规情况的架构（constraint\$1violations.json 文件）](model-monitor-interpreting-violations.md)

# 创建基准
<a name="model-monitor-create-baseline"></a>

统计数据和约束的基准计算需作为检测数据漂移和其他数据质量问题的标准。Model Monitor 提供了一个内置容器，该容器能够自动建议针对 CSV 和平面 JSON 输入的约束。此*sagemaker-model-monitor-analyzer*容器还为您提供了一系列模型监控功能，包括根据基准进行约束验证和发出 Amazon CloudWatch 指标。此容器基于 Spark 版本 3.3.0，并通过 [Deequ](https://github.com/awslabs/deequ) 版本 2.0.2 构建。基准数据集中的所有列名称都必须符合 Spark。对于列名称，请仅使用小写字符，`_` 是唯一的特殊字符。

用来训练模型的训练数据集通常是一个很好的基准数据集。训练数据集数据架构和推理数据集架构应完全匹配（特征的数量和顺序）。请注意，假设这些 prediction/output 列是训练数据集中的第一列。在训练数据集中，您可以让 SageMaker AI 建议一组基线约束条件并生成描述性统计数据以探索数据。对于此示例，上传已用于训练本示例中包含的预训练模型的训练数据集。如果您已将训练数据集存储在 Amazon S3 中，则可以直接指向该数据集。

**从训练数据集创建基准** 

当您的训练数据准备就绪并存储在 Amazon S3 中时，请`DefaultModelMonitor.suggest_baseline(..)`使用 Amaz [ SageMaker on Python 软件开发工具包](https://sagemaker.readthedocs.io/en/stable)开始基准处理任务。这将使用 [Amazon SageMaker 模型监控器预建容器](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
)
```

**注意**  
如果您将训练数据集中的 feature/column 名称作为第一行并设置`header=True`选项（如上一个代码示例所示）， SageMaker AI 将使用约束和统计文件中的要素名称。

数据集的基准统计数据包含在 statistics.json 文件中，建议的基准约束包含在 constraints.json 文件中，这两个文件位于您使用 `output_s3_uri` 指定的位置。

表格数据集统计数据和约束的输出文件


| 文件名称 | 说明 | 
| --- | --- | 
| statistics.json |  此文件应具有所分析数据集中每个特征的列式统计数据。有关此文件的架构的更多信息，请参阅[统计数据的架构（statistics.json 文件）](model-monitor-byoc-statistics.md)。  | 
| constraints.json |  此文件应对观察到的特征有约束。有关此文件的架构的更多信息，请参阅[约束的架构（constraints.json 文件）](model-monitor-byoc-constraints.md)。  | 

[Amaz SageMaker on Python 软件开发工具包](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 模型监控器预建容器根据统计数据进行计算。 column/feature 将为基准数据集以及正在分析的当前数据集计算统计数据。

```
{
    "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 指标
<a name="model-monitor-interpreting-cloudwatch"></a>

您可以使用内置的 Amazon SageMaker 模型监控器容器来获取 CloudWatch 指标。当该`emit_metrics`选项位于基准约束文件`Enabled`中时， SageMaker AI 会针对在以下命名空间的数据集中 feature/column 观察到的每个指标发出这些指标：
+ 带 `EndpointName` 和 `ScheduleName` 维度的 `For real-time endpoints: /aws/sagemaker/Endpoints/data-metric` 命名空间。
+ 带 `MonitoringSchedule` 维度的 `For batch transform jobs: /aws/sagemaker/ModelMonitoring/data-metric` 命名空间。

对于数值字段，内置容器会发出以下 CloudWatch指标：
+ 指标：最大值 → 查询 `MetricName: feature_data_{feature_name}, Stat: Max`
+ 指标：最小值 → 查询 `MetricName: feature_data_{feature_name}, Stat: Min`
+ 指标：和 → 查询 `MetricName: feature_data_{feature_name}, Stat: Sum`
+ 指标: SampleCount → 查询 `MetricName: feature_data_{feature_name}, Stat: SampleCount`
+ 指标：平均值 → 查询 `MetricName: feature_data_{feature_name}, Stat: Average`

对于数值和字符串字段，内置容器都会发出以下 CloudWatch 指标：
+ 指标：完整性 → 查询 `MetricName: feature_non_null_{feature_name}, Stat: Sum`
+ 指标：基准偏差 → 查询 `MetricName: feature_baseline_drift_{feature_name}, Stat: Sum`

# 违规情况的架构（constraint\$1violations.json 文件）
<a name="model-monitor-interpreting-violations"></a>

违规情况文件作为 `MonitoringExecution` 的输出生成，其中列出了针对所分析的当前数据集评估约束（在 constraints.json 文件中指定）的结果。Amazon SageMaker 模型监控器预建容器提供以下违规检查。

```
{
    "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"
    }]
}
```

监控的违规情况的类型 


| 违规情况检查类型 | 说明  | 
| --- | --- | 
| data\$1type\$1check | 如果当前执行中的数据类型与基准数据集中的数据类型不同，则会标记此违规情况。 在基准步骤中，生成的约束会为每个列建议推断的数据类型。可以调整 `monitoring_config.datatype_check_threshold` 参数，以便调整标记为违规时的阈值。  | 
| completeness\$1check | 如果当前执行中观察到的完整性（非空项目的百分比）超过了为每个特征指定的完整性阈值中指定的阈值，则会标记此违规情况。 在基准步骤中，生成的约束会建议一个完整性值。  | 
| 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 存储桶中的实际标签合并，然后将预测结果与实际标签进行比较。

为了衡量模型质量，Model Monitor 使用依赖于机器学习问题类型的指标。例如，如果您的模型用于解决回归问题，则评估的指标之一是均方误差 (mse)。有关用于不同机器学习问题类型的所有指标的信息，请参阅[模型质量指标和 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 标签，这些标签将模型监控与从实时推理端点或批量转换作业捕获的预测数据合并。有关更多信息，请参阅 [输入地面实况标签并与预测结果合并](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)
+ [输入地面实况标签并与预测结果合并](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. 基准作业建议了一些约束，这些约束是模型监控所测量指标的阈值。如果一项指标超过建议的阈值，则 Model Monitor 会报告违规行为。要查看基准作业生成的约束，请调用基准作业的 `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)}
   ```

   您可以将预处理脚本作为 `record_preprocessor_script` 添加到基准或监控计划，如[模型监控](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html)文档中所定义。

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 标签可能会延迟。要解决这个问题，请在创建监控计划时指定偏移量。

## Model Monitor 偏移量
<a name="model-monitor-model-quality-schedule-offsets"></a>

模型质量作业包括 `StartTimeOffset` 和 `EndTimeOffset`，它们是 `create_model_quality_job_definition` 方法 `ModelQualityJobInput` 参数的字段，其工作方式如下：
+ `StartTimeOffset` - 如果已指定，则作业将从开始时间中减去此时间。
+ `EndTimeOffset` - 如果已指定，则作业将从结束时间中减去此时间。

例如，偏移量的格式为-PT7 H，其中 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,
)
```

# 输入地面实况标签并与预测结果合并
<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`，则 Model Monitor 用它来将捕获的数据与 Ground Truth 记录合并。您负责确保 Ground Truth 记录中的 `inferenceId` 与所捕获记录中的 `inferenceId` 进行匹配。如果捕获的数据中不存在 `inferenceId`，则 Model Monitor 使用所捕获数据记录中的 `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，请在调用`create_model_quality_job_definition`方法时通过将 Ground Truth 标签的位置指定为`GroundTruthS3Input`参数`S3Uri`字段来执行此操作。如果您使用的是 SageMaker Python SDK，请在调用`ModelQualityMonitor`对象时将 Ground Truth 标签`create_monitoring_schedule`的位置指定为`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>

如果您在创建监控计划`True`时`enable_cloudwatch_metrics`将的值设置为，则模型质量监控任务会将所有指标发送到 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>

Ama SageMaker zon Clarify 偏差监控可帮助数据科学家和机器学习工程师定期监控偏差预测。在监控模型时，客户可以在 SageMaker Studio 中查看详细说明偏差的可导出报告和图表，并在 Amazon 中配置警报， CloudWatch 以便在检测到偏差超过特定阈值时接收通知。当训练数据与模型在部署期间看到的数据（即实时数据）不同时，就会在部署的机器学习模型中引入或加剧偏差。实时数据分布中的这些变化可能是暂时的（例如，由于一些短暂的真实事件），也可能是永久的。无论哪种情况，检测这些变化都可能很重要。例如，如果用于训练该模型的抵押贷款利率与当前的现实世界抵押贷款利率不同，则预测房价模型的输出可能会出现偏差。借助 Model Monitor 中的偏差检测功能，当 SageMaker AI 检测到偏差超过特定阈值时，它会自动生成指标，您可以在 SageMaker Studio 中或通过 Amazon CloudWatch 提醒查看这些指标。

通常，仅在 train-and-deploy相位期间测量偏差可能还不够。部署模型后，部署的模型所看到的数据（即实时数据）分布可能不同于训练数据集中的数据分布。随着时间的推移，这种变化可能会在模型中引入偏差。实时数据分布的变化可能是暂时的（例如，由于某些短暂的行为，例如假日季），也可能是永久的。无论哪种情况，检测这些变化并适时采取措施减少偏差可能都很重要。

为了检测这些变化，C SageMaker larify 提供了持续监控已部署模型的偏差指标的功能，并在指标超过阈值时自动发出警报。例如，考虑 DPPL 偏差指标。指定允许的值范围 A=(amin​,amax​)，例如区间 (-0.1, 0.1)，DPPL 在部署期间应属于该范围。任何偏离此范围的偏差都应引发*检测到偏差* 警报。使用 SageMaker Clarify，您可以定期执行这些检查。

例如，您可以将检查频率设置为 2 天。这意味着 Cl SageMaker arify 会根据在 2 天窗口内收集的数据计算 DPPL 指标。在本例中，Dwin 是模型在上一个 2 天时限内处理的数据。如果根据 Dwin​ 计算的 DPPL 值 bwin​ 超出允许范围 A，则会发出警报。这种检查 bwin 是否在 A 之外的方法可能会产生噪点。Dwin​ 可能由很少的样本组成，可能无法代表实时数据分布。样本量小意味着根据 Dwin​ 计算出的偏差 bwin​ 值可能不是一个非常可靠的估计值。实际上，观察到的极高（或极低）bwin​ 值可能纯属偶然。为了确保从观测数据 D win 中得出的结论具有统计学意义，Clarif SageMaker y 使用了置信区间。具体而言，它使用正常引导间隔方法来构造区间 C= (cmin, cmax)，这样 Clarify 确信根据完整实时数据计算的真实偏差值很可能包含在 C 中。 SageMaker 现在，如果置信区间 C 与允许的范围 A 重叠， SageMaker Clarify 会将其解释为 “实时数据分布的偏差指标值很可能在允许的范围内”。如果 C 和 A 不相交，Cl SageMaker arify 确信偏差指标不在 A 中，因此会发出警报。

## Model Monitor 示例笔记本
<a name="clarify-model-monitor-sample-notebooks-bias-drift"></a>

Ama SageMaker zon Clarify 提供了以下示例笔记本，展示了如何捕获实时终端节点的推理数据，如何创建基线以监控不断变化的偏见，以及如何检查结果：
+ [监控偏见漂移和特征归因偏差 Amazon C SageMaker larif](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_model_monitor/fairness_and_explainability/SageMaker-Model-Monitor-Fairness-and-Explainability.html) y — 使用 Amazon SageMaker 模型监视器监控偏差和特征归因随时间推移而发生的偏差漂移。

本笔记本经过验证，只能在 Amazon SageMaker Studio 中运行。如果您需要有关如何在 Amazon SageMaker Studio 中打开笔记本的说明，请参阅[创建或打开 Amazon SageMaker Studio 经典笔记本电脑](notebooks-create-open.md)。如果系统提示您选择内核，请选择 **Python 3 (Data Science)**。以下主题包含最后两个步骤的重点内容，并包含示例笔记本中的代码示例。

**Topics**
+ [Model Monitor 示例笔记本](#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>

将应用程序配置为捕获实时或批量转换推理数据后，监控偏差偏移的第一项任务就是创建基准。这包括配置数据输入、哪些组是敏感组、如何捕获预测结果，以及模型及其训练后偏差指标。然后，您需要启动设定基准作业。

模型偏差监控器可以定期检测机器学习模型的偏差偏移。与其他监控类型类似，创建模型偏差监控器的标准程序是先设定基准，然后制定监控计划。

```
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 的临界值，是因为预计客户会经常交货。对于更复杂的输出，还有其他一些选项，比如 “标签” 是索引、名称或 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>

Ama SageMaker zon 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` 为 `"application/jsonlines"` 且指定了 `"label"`，则最后一个标题将成为标签列的标题。
+ `"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>

以下是用于配置 CSV 和 JSON 行数据集以监控其偏差偏移的 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`（对于实时端点）或 `BatchTransformInput`（对于批量转换作业）中的 `"features"` 参数值来定位数据集中的特征，`"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-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>

本指南显示了在 Clarify 中可用于偏差漂移分析的 CloudWatch 指标及其 SageMaker 属性。偏差漂移监控作业会计算[训练前的偏差指标](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` 形式发布，不发布包含空值的错误。

每个指标都具有以下属性：
+ `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>

生产中模型的实时数据分布的偏移会导致特征归因值出现相应的偏移，就像监控偏差指标时可能导致偏差偏移一样。Ama SageMaker zon Clarify 功能归因监控可帮助数据科学家和机器学习工程师定期监控功能归因偏差的预测。在监控模型时，客户可以在 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。

在 Cl SageMaker arify 中，如果 NDCG 值低于 0.90，我们会自动发出警报。

## Model Monitor 示例笔记本
<a name="clarify-model-monitor-sample-notebooks-feature-drift"></a>

SageMaker Clarify 提供了以下示例笔记本，展示了如何捕获实时端点的推理数据、创建基线以监控不断变化的偏见，以及如何检查结果：
+ [监控偏见漂移和特征归因偏差 Amazon C SageMaker larif](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_model_monitor/fairness_and_explainability/SageMaker-Model-Monitor-Fairness-and-Explainability.html) y — 使用 Amazon SageMaker 模型监视器监控偏差和特征归因随时间推移而发生的偏差漂移。

此笔记本已经过验证，只能在 SageMaker Studio 中运行。如果您需要有关如何在 SageMaker Studio 中打开笔记本的说明，请参阅[创建或打开 Amazon SageMaker Studio 经典笔记本电脑](notebooks-create-open.md)。如果系统提示您选择内核，请选择 **Python 3 (Data Science)**。以下主题包含最后两个步骤的重点内容，并包含示例笔记本中的代码示例。

**Topics**
+ [Model Monitor 示例笔记本](#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 还支持对机器学习模型进行全局解释，以帮助您从特征的角度了解整个模型的行为。 SageMaker Clarify 通过聚合多个实例上的 Shapley 值来生成机器学习模型的全局解释。 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,
)
```

目前，C SageMaker larify 解释器提供了 SHAP 的可扩展且高效的实现，因此可解释性配置为 SHAPConfig，包括以下内容：
+ `baseline` - Kernel SHAP 算法中用作基准数据集的行（至少一行）列表或 S3 对象 URI。其格式应与数据集格式相同。每行应仅包含要素 columns/values 并省略标签列/值。
+ `num_samples` - 要在 Kernel 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>

Ama SageMaker zon 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。在 Kernel SHAP 算法中用作基准数据集（也称为背景数据集）。其格式应与数据集格式相同。每行应仅包含特征列（或值）。将每行发送到模型之前，请省略任何必须排除的列。
    + `"num_samples"` - 要在 Kernel SHAP 算法中使用的样本数。该数字决定了生成的用于计算 SHAP 值的合成数据集的大小。如果未提供，则 Cl SageMaker arify 作业会根据要素数量选择值。
    + `"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>

以下是用于配置 CSV 和 JSON 行数据集以监控它们的特征归因偏移的 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`（对于实时端点）或 `BatchTransformInput`（对于批量转换作业）中的 `"features"` 参数值来定位数据集中的特征，`"probability"` 参数值从模型输出中选择概率值。

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

# 计划特征归因偏移监控作业
<a name="clarify-model-monitor-feature-attribute-drift-schedule"></a>

创建 SHAP 基准后，您可以调用 `ModelExplainabilityMonitor` 类实例的 `create_monitoring_schedule()` 方法来计划每小时一次的模型可解释性监控。以下几节介绍如何为部署到实时端点的模型以及为批量转换作业创建模型可解释性监控。

**重要**  
创建监控计划时，您可以指定批量转换输入或端点输入，但不能同时指定两者。

如果已提交设定基准作业，则监控器会自动从基准作业中选取分析配置。但是，如果您跳过设定基准步骤，或者捕获数据集的性质与训练数据集不同，则必须提供分析配置。`ExplainabilityAnalysisConfig` 需要 `ModelConfig`，原因与设定基准作业需要它的原因相同。请注意，计算特征归因时只需要特征，因此您应排除 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 指标的可视化效果，方法是选择 Endpoints 选项卡，然后双击该**端点**。

# CloudWatch 特征偏差分析指标
<a name="clarify-feature-attribute-drift-cw"></a>

本指南显示了在 Clarify 中可用于要素属性漂移分析的 CloudWatch 指标及其 SageMaker 属性。特征归因偏移监控作业计算和发布两种类型的指标：
+ 每个特征的全局 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 模型监控器使您能够监控从您的实时终端节点收集的数据。您可以按照定期计划监控数据，也可以立即进行一次性监控。您可以使用 [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-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 定期分析计划**  
如果要为实时端点计划模型监控，则使用基准约束和统计数据与实时流量进行比较。以下代码片段显示了用于为实时端点计划模型监控的一般格式。此示例将 Model Monitor 计划为每小时运行一次。  

```
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 模型监控器支持以下`cron`表达式：
+ 要将作业设置为每小时启动一次，请使用以下命令：

  `Hourly: cron(0 * ? * * *)`
+ 要每日运行作业，请使用以下命令：

  `cron(0 [00-23] ? * * *)`
+ 要立即运行一次作业，使用以下关键字：

  `NOW`

例如，以下是有效的 `cron` 表达式：
+ 每天凌晨 12 点 (UTC)：`cron(0 12 ? * * *)`
+ 每天中午 12 点 (UTC)：`cron(0 0 ? * * *)`

为了支持每 6 小时或 12 小时运行一次，Model Monitor 支持以下表达式：

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

例如，以下是有效的 `cron` 表达式：
+ 每 12 小时一次，从下午 5 点 (UTC) 开始：`cron(0 17/12 ? * * *)`
+ 每 2 小时一次，从中午 12 点 (UTC) 开始：`cron(0 0/2 ? * * *)`

**注意**  
尽管 `cron` 表达式设置为下午 5 点 (UTC) 开始，但请注意，从实际请求的时间到运行执行可能有 0-20 分钟的延迟。
如果您想按每日计划运行，请不要提供此参数。 SageMaker AI 每天都会选择一个时间来跑步。
目前， SageMaker AI 仅支持 1 小时到 24 小时之间的每小时整数费率。

# 为监控计划配置服务控制策略
<a name="model-monitor-scp-rules"></a>

 在分别使用 API 或 [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)根据您的使用案例，可以通过以下方式之一执行此操作：
+  您可以在调用`CreateMonitoringSchedule`或时指定[MonitoringJobDefinition](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_MonitoringJobDefinition.html)字段`UpdateMonitoringSchedule`。[MonitoringScheduleConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_MonitoringScheduleConfig.html)只能用它来创建或更新数据质量监控作业的计划。
+  调用 `CreateMonitoringSchedule` 或 `UpdateMonitoringSchedule` 时，可以为 `MonitoringScheduleConfig` 的 `MonitoringJobDefinitionName` 字段指定已创建的监控作业定义的名称。您可以将其用于使用以下任一选项创建的任何作业定义 APIs：
  +  [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) (SCPs)。 SCPs 是一种组织策略，可用于管理组织中的权限。

 以下示例显示了一个 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 模型监控器预建容器
<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` 映像。当您使用其中一个提交基线处理或监控任务时，您可以使用该`sagemaker-model-monitor-analyzer`图像 AWS SDKs。

 使用 SageMaker Python SDK（参见 `image_uris.retrieve` [SageMaker AI Python SDK 参考指南](https://sagemaker.readthedocs.io/en/stable/api/utility/image_uris.html)中）为你生成 ECR 图片 URI，或者直接指定 ECR 图片 URI。可以通过以下方式访问 SageMaker 模型监视器的预建映像：

`<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 ：

`<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>

运行基准处理作业并获得数据集的统计数据和约束后，可以执行监控作业，以便计算统计数据并列出相对于基准约束遇到的任何违规情况。默认情况下，亚马逊 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)
```

这仅适用于包含表格式数据的数据集。以下架构文件指定计算的统计数据和监控的违规情况。

表格数据集的输出文件


| 文件名称 | 说明 | 
| --- | --- | 
| statistics.json |  包含所分析数据集中每个特征的列式统计数据。请参阅下一个主题中此文件的架构。  创建此文件仅用于数据质量监控。   | 
| constraint\$1violations.json |  包含在当前数据集中找到的相对于 `baseline_statistics` 路径中指定的基准统计数据文件和 `baseline_constaints` 路径中指定的约束文件的所有违规情况。  | 

默认情况下，会为每项功能[Amazon SageMaker 模型监控器预建容器](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。有关更多信息，请参阅 [亚马逊 SageMaker AI 域名概述](gs-studio-onboard.md)。

1. 在左侧导航窗格中，选择**组件和注册表**图标 (![\[Orange paper airplane icon representing email or message sending functionality.\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/icons/Components_registries.png))。

1. 在下拉菜单中选择**端点**。  
![\[管理控制台中端点下拉菜单的位置。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/model_monitor/mm-studio-endpoints.png)

1. 在“端点”选项卡上，选择要查看作业详细信息的监控类型。  
![\[模型监测部分中模型质量选项卡的位置。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/model_monitor/mm-studio-model-quality.png)

1. 从监控作业列表中选择要查看详细信息的监控作业运行的名称。  
![\[模型监测部分的模型质量选项卡。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/model_monitor/mm-studio-job-history.png)

1. 此时将打开**监控作业详细信息**选项卡，其中包含监控作业的详细报告。  
![\[监测任务详情选项卡。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/model_monitor/mm-studio-job-details.png)

您可以创建一个图表，以显示一段时间内的基准和捕获的指标。

**在 SageMaker Studio 中创建图表以可视化监控结果**

1. 登录 Studio。有关更多信息，请参阅 [亚马逊 SageMaker AI 域名概述](gs-studio-onboard.md)。

1. 在左侧导航窗格中，选择**组件和注册表**图标 (![\[Orange paper airplane icon representing email or message sending functionality.\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/icons/Components_registries.png))。

1. 在下拉菜单中选择**端点**。  
![\[管理控制台中端点下拉菜单的位置。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/model_monitor/mm-studio-endpoints.png)

1. 在**端点**选项卡上，选择要创建图表的监控类型。本例显示**模型质量**监控类型的图表。  
![\[模型监测部分中模型质量选项卡的位置。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/model_monitor/mm-studio-model-quality.png)

1. 选择**添加图表**。  
![\[管理控制台中添加图表的位置。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/model_monitor/mm-studio-add-chart.png)

1. 在**图表属性**选项卡上，选择要绘制图表的时间段、统计数据和指标。本例显示**时间轴**为 **1 周**、**统计数据**为**平均值**且**指标**为 **F1** 的图表。  
![\[在管理控制台中选择指标的位置。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/model_monitor/mm-studio-chart-properties.png)

1. 显示上一步中所选基准和当前指标统计数据的图表将显示在**端点**选项卡中。  
![\[示例图表，显示上一步中选择的基准指标和当前平均指标。\]](http://docs.aws.amazon.com/zh_cn/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-byoc-containers.md)

# 预处理和后处理
<a name="model-monitor-pre-and-post-processing"></a>

您可以使用自定义的预处理和后处理 Python 脚本将输入转换为 Model Monitor，或者在成功运行监控后扩展代码。将这些脚本上传到 Amazon S3，并在创建 Model Monitor 时引用它们。

以下示例说明了如何使用预处理和后处理脚本来自定义监控计划。*user placeholder text*用您自己的信息替换。

```
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>

当需要将输入转换为 Model Monitor 时，请使用预处理脚本。

例如，假设模型的输出是一个数组 `[1.0, 2.1]`。Amazon SageMaker 模型监视器容器仅适用于表格或扁平化的 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>

您也可以在预处理脚本中应用自定义采样策略。为此，请将 Model Monitor 的第一方预构建容器配置为根据您指定的采样率忽略一定比例的记录。在以下示例中，处理程序通过在 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 模型监视器支持您自己的容器
<a name="model-monitor-byoc-containers"></a>

Amazon SageMaker Model Monitor 提供了一个预建容器，能够分析从终端节点捕获的数据或表格数据集的批量转换任务。如果要自带容器，Model Monitor 为您提供了可利用的扩展点。

在后台，当您创建 `MonitoringSchedule` 时，Model Monitor 最终将启动处理作业。因此，容器需要了解[如何构建您自己的处理容器（高级方案）](build-your-own-processing-container.md)主题中记录的处理作业约定。请注意，Model Monitor 将按照计划代表您启动处理作业。在调用时，Model Monitor 会为您设置额外的环境变量，以便您的容器具有足够的上下文来处理已计划监控的特定执行的数据。有关容器输入的其他信息，请参阅 [容器约定输入](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 模型监控器平台会根据指定的计划调用您的容器代码。如果您选择编写您自己的容器代码，则可以使用以下环境变量。在此上下文中，可以分析当前数据集或评估约束（如果您选择这样做）并发出指标（如果适用）。

除了 `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"
}
```

参数 


| 参数名称 | 说明 | 
| --- | --- | 
| dataset\$1format |  对于从由 `Endpoint` 支持的 `MonitoringSchedule` 开始的作业，这是具有捕获索引 `endpointInput` 和/或 `endpointOutput` 的 `sageMakerCaptureJson`。对于批量转换作业，这指定了数据格式，无论是 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`。容器可以选择将 Amazon CloudWatch 输出文件写入到`[filepath]`。  | 
| 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 运行的作业和在 20/02/2020 运行的作业，`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*.` 中的路径。容器代码可以编写任何报告来满足您的需求。

如果您使用以下结构和合约，AI 会在可视化和 AP SageMaker I 中对某些输出文件进行特殊处理。这仅适用于表格数据集。

表格数据集的输出文件


| 文件名称 | 说明 | 
| --- | --- | 
| statistics.json |  此文件应具有所分析数据集中每个特征的列式统计数据。下一节将介绍此文件的架构。  | 
| constraints.json |  此文件应对观察到的特征有约束。下一节将介绍此文件的架构。  | 
| constraints\$1violations.json |  此文件应包含在当前数据集中找到的相对于 `baseline_statistics` 路径中指定的基准统计数据文件和 `baseline_constaints` 路径中指定的约束文件的违规情况的列表。  | 

此外，如果`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 模型监控器容器可以使用 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_cn/sagemaker/latest/dg/model-monitor-byoc-constraints.html)

# CloudWatch 自带容器的指标
<a name="model-monitor-byoc-cloudwatch"></a>

如果该`publish_cloudwatch_metrics`值`Enabled`在`/opt/ml/processing/processingjobconfig.json`文件`Environment`的地图中，则容器代码会在以下位置发出亚马逊 CloudWatch 指标：`/opt/ml/output/metrics/cloudwatch`。

此文件的架构紧密基于 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 片段展示了如何设置维度。

对于实时端点，请参阅以下 JSON 片段，其中包含 `Endpoint` 和 `MonitoringSchedule` 维度：

```
{ 
    "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
}
```

对于批量转换作业，请参阅以下 JSON 片段，其中包含 `MonitoringSchedule` 维度：

```
{ 
    "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 install crhelper` pip 安装该库。

此 Lambda 函数由 CloudFormation 在创建和删除堆栈期间调用。此 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
```

# 模型监视器 FAQs
<a name="model-monitor-faqs"></a>

有关 Amazon SageMaker 模型监视 FAQs 器的更多信息，请参阅以下内容。

**问：Model Monitor and C SageMaker larify 如何帮助客户监控模型行为？**

客户可以通过 Amazon Model Monitor 和 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)、 SageMaker 模型质量、[偏差漂](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-monitor-bias-drift.html)[移和 SageMaker 特征归因漂移](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-monitor-feature-attribution-drift.html)。[模型监控器](https://aws.amazon.com/sagemaker/model-monitor/)持续监控 Amazon A SageMaker I 机器学习模型在生产中的质量。这包括监控数据质量和模型质量指标（如准确性和 RMSE）的偏移。SageMaker C@@ [l](https://aws.amazon.com/sagemaker/clarify/?sagemaker-data-wrangler-whats-new.sort-by=item.additionalFields.postDateTime&sagemaker-data-wrangler-whats-new.sort-order=desc) arify 偏差监测可帮助数据科学家和机器学习工程师监控模型预测中的偏差和特征归因偏差。

**问：启用 SageMaker Model Monitor 后，后台会发生什么？**

Amazon SageMaker Model Monitor 可自动监控模型，从而无需手动监控模型或构建任何其他工具。为了自动执行该过程，Model Monitor 使您能够使用训练模型时所用的数据创建一组基准统计数据和约束，然后设置计划来监控对端点所做的预测。Model Monitor 使用规则来检测模型中的偏差，并在出现偏差时提醒您。以下步骤描述了启用模型监控时会发生的情况：
+ **启用模型监控**：对于实时端点，您必须启用端点，以捕获从传入请求到已部署机器学习模型的数据以及由此产生的模型预测。对于批量转换作业，支持捕获批量转换输入和输出的数据。
+ **基准处理作业**：然后您从用于训练模型的数据集创建基准。该基准会计算指标并建议指标的约束条件。例如，模型的查全率得分不应回归并降至 0.571 以下，或者查准率得分不应降至 1.0 以下。将模型中的实时预测或批量预测与约束条件进行比较，如果这些预测超出约束值，则报告为违规。
+ **监控作业**：然后，您创建一个监控计划，该计划指定要收集的数据、数据收集频率、数据分析方式以及生成的报告。
+ **合并任务**：这仅适用于您使用 Amazon G SageMaker round Truth 的情况。Model Monitor 将您的模型所做的预测与 Ground Truth 标签进行比较，以衡量模型的质量。为此，您需要定期为端点或批量转换作业捕获的数据添加标签，然后将其上传到 Amazon S3。

  创建并上传 Ground Truth 标签后，请在创建监控作业时将标签的位置作为参数包括在内。

当您使用 Model Monitor 监控批量转换作业而不是实时端点时，Model Monitor 将监控推理输入和输出，而不是接收对端点的请求并跟踪预测。在 Model Monitor 计划中，客户提供要在处理作业中使用的实例的数量和类型。无论当前执行的状态如何，这些资源都会一直保留到计划被删除为止。

**问：什么是数据捕获，为什么需要它，以及如何启用它？**

要将模型端点的输入以及已部署模型的推理输出记录到 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 数据捕获应与 Model Monitor 计划位于同一区域。您还应确保基准数据集的列名称仅使用小写字母，并使用下划线 (`_`) 作为唯一分隔符。

**问：为什么模型监控需要 Ground Truth？**

Model Monitor 的以下特征需要使用 Ground Truth 标签：
+ **模型质量监控**将您的模型所做的预测与 Ground Truth 标签进行比较，以衡量模型的质量。
+ **模型偏差监控**可监控预测是否存在偏差。在部署的机器学习模型中引入偏差的一种可能情况是当训练中使用的数据与用于生成预测的数据不同时。如果用于训练的数据会随着时间的推移而发生变化（例如抵押贷款利率的波动），模型预测的准确性就会大打折扣，除非使用更新的数据对模型进行再训练。例如，如果用于训练预测房价的模型的抵押贷款利率与现实世界中最新的抵押贷款利率不同，则该模型可能会有偏差。

**问：对于利用 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,
)
```

**问：我可以在哪些场景或使用案例中使用预处理脚本？**

当需要转换对 Model Monitor 的输入时，可以使用预处理脚本。考虑以下示例场景：

1. 用于数据转换的预处理脚本。

   假设模型的输出是一个数组：`[1.0, 2.1]`。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. 从 Model Monitor 的指标计算中排除某些记录。

   假设您的模型具有可选特征，而您使用 `-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. 应用自定义采样策略。

   您也可以在预处理脚本中应用自定义采样策略。为此，请将 Model Monitor 的第一方预构建容器配置为根据您指定的采样率忽略一定比例的记录。在以下示例中，处理程序通过在 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 使用案例。
+ 当您需要除 Model Monitor 支持的监控指标之外的其他监控指标时。

**问：我有 NLP 和 CV 模型。如何监控它们是否存在数据偏差？**

Amazon SageMaker AI 的预构建容器支持表格数据集。如果您想监控 NLP 和 CV 模型，可以利用 Model Monitor 提供的扩展点自带容器。有关要求的更多详细信息，请参阅[自带容器](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-byoc-containers.html)。下面提供了更多示例：
+ 有关如何将 Model Monitor 用于计算机视觉使用案例的详细说明，请参阅[检测和分析错误的预测](https://aws.amazon.com/blogs/machine-learning/detecting-and-analyzing-incorrect-model-predictions-with-amazon-sagemaker-model-monitor-and-debugger/)。
+ 有关模型监视器可用于 NLP 用例的场景，请参阅使用[自定义 Ama SageMaker zon 模型监控器检测 NLP 数据偏差](https://aws.amazon.com/blogs/machine-learning/detect-nlp-data-drift-using-custom-amazon-sagemaker-model-monitor/)。

**问：我想删除已启用 Model Monitor 的模型端点，但由于监控计划仍处于活动状态，因此无法删除。我应该怎么办？**

如果要删除已启用模型监控器的 SageMaker AI 中托管的推理端点，则必须先删除模型监控计划（使用 `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 数据捕获能否位于与设置监控计划的 AWS 区域不同的区域？**

否，Amazon S3 数据捕获必须与监控计划位于同一区域。

**问：什么是基准，如何创建基准？ 我可以创建自定义基准吗？**

基准用作比较模型的实时预测或批量预测的参考。它计算统计数据和指标以及对它们的约束。监控期间，将结合使用所有这些来识别违规行为。

要使用亚马逊 SageMaker 模型监控器的默认解决方案，您可以利用亚马逊 [ SageMaker Python 软件开发工具包](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html)。具体而言，使用[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 G SageMaker round Truth 来监控模型质量等任务时，您需要确保监控任务仅使用可用 Ground Truth 的数据。的`start_time_offset`和`end_time_offset`参数[EndpointInput](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html#sagemaker.model_monitor.model_monitoring.EndpointInput)可用于选择监控作业使用的数据。监控作业使用由 `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 小时。

**问：我是否可以运行“按需”监控作业？**

是的，您可以通过运行 Processing 作业来运行 “按需” 监控作业。 SageMaker 对于 Batch Transform [MonitorBatchTransformStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.monitor_batch_transform_step.MonitorBatchTransformStep)，Pipelin [es](https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-overview.html) 有一个可用于创建按需运行监控作业的 SageMaker AI 管道。A SageMaker I 示例存储库包含用于按需运行[数据质量](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)监控作业的代码示例。

**问：如何设置 Model Monitor？**

您可以使用以下方法设置 Model Monitor：
+ **[Amazon SageMaker AI Python SDK](https://sagemaker.readthedocs.io/en/stable/index.html)** — 有一个[模型监控器模块](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html)，其中包含有助于建议基准、创建监控计划等的类和函数。有关利用 A SageMaker I Python SDK 设置[ SageMaker 模型监控器的详细笔记本，请参阅 Amazon 模型监视器笔记本示例](https://github.com/aws/amazon-sagemaker-examples/tree/main/sagemaker_model_monitor)。
+ **[管道](https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-overview.html)** —通过[QualityCheck 步骤](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) APIs。您可以创建包含这些步骤的 SageMaker AI 管道，该管道可用于在执行管道时按需运行监控作业。
+ **[Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio.html)** — 您可以从已部署的模型终端节点列表中选择终端节点，直接从用户界面创建数据或模型质量监控计划以及模型偏差和可解释性计划。通过选择 UI 中的相关选项卡，可以创建其他类型监控的计划。
+ **[SageMaker 模型控制面板](https://docs.aws.amazon.com/sagemaker/latest/dg/model-dashboard.html)**-您可以通过选择已部署到端点的模型来启用对端点的监控。在以下 SageMaker AI 控制台屏幕截图中，`group1`已从 “模型” **仪表板的 “**模型**” 部分中选择了一个名为的模型**。在此页面上，您可以创建监控计划，也可以编辑、激活或停用现有的监控计划和警报。有关如何查看警报和 Model Monitor 计划的分步指南，请参阅[查看 Model Monitor 计划和警报](https://docs.aws.amazon.com/sagemaker/latest/dg/model-dashboard-schedule.html)。

![\[模型控制面板的屏幕截图，显示了用于创建监控计划的选项。\]](http://docs.aws.amazon.com/zh_cn/sagemaker/latest/dg/images/model-monitoring-faqs-screenshot.png)


**问：模型监视器如何与 SageMaker 模型仪表板集成**

[SageMaker Model Das](https://docs.aws.amazon.com/sagemaker/latest/dg/model-dashboard.html) hboard 通过提供有关偏离预期行为的自动警报和故障排除，以检查模型并分析随时间推移影响模型性能的因素，从而对所有模型进行统一监控。