

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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


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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

監控的違規類型 


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