

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

# 使用 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
}
```