

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

  `NOW`

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

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

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

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

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

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

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

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

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

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

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

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

****  

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

------

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