

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Amazon SageMaker Model Monitor를 사용한 데이터 및 모델 품질 모니터링
<a name="model-monitor"></a>

Amazon SageMaker Model Monitor는 프로덕션 환경에서 Amazon SageMaker AI 기계 학습 모델의 품질을 모니터링합니다. Model Monitor를 사용하면 다음을 설정할 수 있습니다.
+ 실시간 엔드포인트를 사용한 지속적인 모니터링.
+ 정기적으로 실행되는 배치 변환 작업을 사용한 지속적인 모니터링
+ 비동기 배치 변환 작업에 대한 일정에 따른 모니터링

모델 모니터로 모델 품질에 편차가 있을 때 알려주는 알림을 설정할 수 있습니다. 이러한 편차를 조기에 사전 예방적으로 감지하여 시정 조치를 취할 수 있습니다. 모델을 수동으로 모니터링하거나 추가 툴링을 빌드할 필요 없이 모델 재훈련, 업스트림 시스템 감사 또는 품질 문제 수정과 같은 조치를 취할 수 있습니다. 코딩이 필요하지 않은 모델 모니터 사전 빌드 모니터링 기능을 사용할 수 있습니다. 또한 사용자 지정 분석을 제공하도록 코딩하여 모델을 유연하게 모니터링할 수 있습니다.

모델 모니터는 다음 유형의 모니터링을 제공합니다.
+ [데이터 품질](model-monitor-data-quality.md) - 데이터 품질의 드리프트를 모니터링합니다.
+ [모델 품질](model-monitor-model-quality.md) - 정확도와 같은 모델 품질 지표의 드리프트를 모니터링합니다.
+ [프로덕션 환경의 모델에 대한 바이어스 드리프트](clarify-model-monitor-bias-drift.md) - 모델 예측의 바이어스를 모니터링합니다.
+ [프로덕션 환경의 모델에 대한 특성 어트리뷰션 드리프트](clarify-model-monitor-feature-attribution-drift.md) - 기능 속성의 드리프트를 모니터링합니다.

**Topics**
+ [프로덕션 환경에서 모델 모니터링](how-it-works-model-monitor.md)
+ [Amazon SageMaker Model Monitor 작동 방식](#model-monitor-how-it-works)
+ [데이터 캡처](model-monitor-data-capture.md)
+ [데이터 품질](model-monitor-data-quality.md)
+ [모델 품질](model-monitor-model-quality.md)
+ [프로덕션 환경의 모델에 대한 바이어스 드리프트](clarify-model-monitor-bias-drift.md)
+ [프로덕션 환경의 모델에 대한 특성 어트리뷰션 드리프트](clarify-model-monitor-feature-attribution-drift.md)
+ [모니터링 작업 일정 예약](model-monitor-scheduling.md)
+ [Amazon SageMaker Model Monitor 사전 구축 컨테이너](model-monitor-pre-built-container.md)
+ [결과 해석](model-monitor-interpreting-results.md)
+ [Amazon SageMaker Studio에서 실시간 엔드포인트의 결과 시각화](model-monitor-interpreting-visualize-results.md)
+ [고급 주제](model-monitor-advanced-topics.md)
+ [Model Monitor FAQ](model-monitor-faqs.md)

# 프로덕션 환경에서 모델 모니터링
<a name="how-it-works-model-monitor"></a>

모델을 프로덕션 환경에 배포한 후에는 Amazon SageMaker Model Monitor를 사용하여 실시간으로 기계 학습 모델의 품질을 지속적으로 모니터링할 수 있습니다. Amazon SageMaker Model Monitor를 사용하면 데이터 드리프트 및 이상 현상과 같이 모델 품질에 편차가 있을 때 자동 알림 트리거 시스템을 설정할 수 있습니다. Amazon CloudWatch Logs는 모델 상태를 모니터링하는 로그 파일을 수집하여 모델 품질이 미리 설정한 특정 임계값에 도달하면 이를 알립니다. CloudWatch는 지정된 Amazon S3 버킷에 CloudWatch가 로그 파일을 저장합니다. AWS 모델 모니터 제품을 통해 모델 편차를 조기에 선제적으로 감지하면 배포된 모델의 품질을 유지하고 개선하기 위한 즉각적인 조치를 취할 수 있습니다.

SageMaker Model Monitor 제품에 대한 자세한 내용은 [Amazon SageMaker Model Monitor를 사용한 데이터 및 모델 품질 모니터링](model-monitor.md) 섹션을 참조하세요.

SageMaker AI로 기계 학습 여정을 시작하려면 [ SageMaker AI 설정](https://docs.aws.amazon.com/sagemaker/latest/dg/gs-set-up.html)에서 AWS 계정에 가입하세요.

## Amazon SageMaker Model Monitor 작동 방식
<a name="model-monitor-how-it-works"></a>

Amazon SageMaker Model Monitor는 프로덕션 환경의 기계 학습(ML) 모델을 자동으로 모니터링하여 품질 문제가 발생할 때 사용자에게 알립니다. 모델 모니터는 규칙을 사용하여 모델의 드리프트를 감지하고, 드리프트가 발생하면 사용자에게 알려줍니다. 다음 그림은 모델이 실시간 엔드포인트에 배포된 경우 이 프로세스가 어떻게 작동하는지 보여줍니다.

![\[모델 모니터링은 Amazon SageMaker 모델 모니터로 처리합니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/model_monitor/mmv2-architecture.png)


또한 모델 모니터를 사용하여 실시간 엔드포인트 대신 배치 변환 작업을 모니터링할 수 있습니다. 이 경우 모델 모니터는 엔드포인트에 대한 요청을 수신하고 예측을 추적하는 대신 추론 입력 및 출력을 모니터링합니다. 다음 그림은 배치 변환 작업을 모니터링하는 프로세스를 도식화한 것입니다.

![\[모델 모니터링은 Amazon SageMaker 모델 모니터로 처리합니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/model_monitor/mmv2-architecture-batch.png)


모델 모니터링을 활성화하려면 다음 단계를 수행합니다. 이러한 단계는 다양한 데이터 수집, 모니터링 및 분석 프로세스를 통해 데이터 경로를 따릅니다.
+ 실시간 엔드포인트의 경우, 엔드포인트를 활성화하여 훈련된 ML 모델로 들어오는 요청에서 나온 데이터와 그 결과로 생성된 모델 예측을 캡처합니다.
+ 배치 변환 작업의 경우 배치 변환 입력 및 출력의 데이터 캡처를 활성화합니다.
+ 모델을 훈련하는 데 사용된 데이터세트에서 기준을 생성합니다. 기준은 지표를 계산한 다음 지표에 대한 제약 조건을 제안합니다. 모델의 실시간 또는 배치 예측을 제약 조건과 비교합니다. 제한된 값을 벗어나는 경우 위반으로 보고됩니다.
+ 모니터링 일정을 생성하여 수집할 데이터, 수집 빈도, 분석 방법 및 생성할 보고서를 지정합니다.
+ 최신 데이터를 기준과 비교하는 보고서를 검사합니다. Amazon CloudWatch에서 보고된 위반 사항, 지표 및 알림을 확인합니다.

**참고**  
모델 모니터는 테이블 형식 데이터에 대해서만 모델 지표와 통계를 계산합니다. 예를 들어, 이미지를 입력으로 받아 이미지 기반의 레이블을 출력하는 이미지 분류 모델을 모니터링할 수 있습니다. 모델 모니터는 입력이 아닌 출력에 대한 지표와 통계를 계산할 수 있습니다.
모델 모니터는 현재 단일 모델을 호스트하는 엔드포인트만 지원하며 다중 모델 엔드포인트의 모니터링을 지원하지 않습니다. 다중 모델 엔드포인트 사용에 대한 자세한 내용은 [다중 모델 엔드포인트](multi-model-endpoints.md)섹션을 참조하세요.
Model Monitor는 추론 파이프라인 모니터링을 지원합니다. 그러나 데이터 캡처 및 분석은 파이프라인의 개별 컨테이너가 아닌 전체 파이프라인에 대해 수행됩니다.
Data Capture는 추론 요청에 영향이 없도록 하기 위해 디스크 사용량이 많은 경우 요청 캡처를 중단합니다. 데이터 캡처가 요청을 계속 캡처하도록 하려면 디스크 사용률을 75% 미만으로 유지하는 것이 좋습니다.
사용자 지정 Amazon VPC에서 SageMaker Studio를 시작하는 경우, 모델 모니터가 Amazon S3 및 CloudWatch와 통신할 수 있도록 VPC 엔드포인트를 만들어야 합니다. VPC 엔드포인트에 대한 자세한 내용은 [Amazon 가상 사설 클라우드 사용자 설명서](https://docs.aws.amazon.com/vpc/latest/privatelink/concepts.html)의 VPC 엔드포인트를 참조하세요.** 사용자 지정 VPC에서 SageMaker Studio를 시작하는 방법에 대한 자세한 내용은 [VPC의 Studio 노트북을 외부 리소스에 연결](studio-notebooks-and-internet-access.md)섹션을 참조하세요.

### Model Monitor 샘플 노트북
<a name="model-monitor-sample-notebooks"></a>

실시간 엔드포인트와 함께 Model Monitor를 사용하여 엔드투엔드 워크플로를 안내하는 샘플 노트북은 [Introduction to Amazon SageMaker Model Monitor](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_model_monitor/introduction/SageMaker-ModelMonitoring.html)를 참조하세요.

모니터링 일정에서 선택한 실행에 대한 statistics.json 파일을 시각화하는 샘플 노트북에 대한 내용은 [모델 모니터 시각화](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_model_monitor/visualization/SageMaker-Model-Monitor-Visualize.html)를 참조하세요.

SageMaker AI에서 예시 실행에 사용할 수 있는 Jupyter Notebook 인스턴스를 생생하고 액세스하는 방법은 [Amazon SageMaker 노트북 인스턴스](nbi.md) 섹션을 참고하세요. 노트북 인스턴스를 만든 후 열고 **SageMaker AI 예시** 탭을 선택하여 모든 SageMaker AI 샘플 목록을 확인하세요. 노트북을 열려면 노트북의 **사용** 탭을 선택한 후 **사본 생성**을 선택합니다.

# 데이터 캡처
<a name="model-monitor-data-capture"></a>

엔드포인트로 들어오는 입력과 Amazon S3에 배포된 모델의 추론 출력을 기록하기 위해 데이터 캡처라는 특징을 활성화할 수 있습니다.** 데이터 캡처는 일반적으로 훈련, 디버깅 및 모니터링에 사용할 수 있는 정보를 기록하는 데 사용됩니다.** Amazon SageMaker 모델 모니터는 캡처된 이 데이터를 자동으로 구문 분석하고 이 데이터의 지표을 사용자가 모델에 대해 생성한 기준과 비교합니다. 모델 모니터링에 대한 자세한 내용은 [Amazon SageMaker Model Monitor를 사용한 데이터 및 모델 품질 모니터링](model-monitor.md)섹션을 참조하세요.

 AWS SDK for Python (Boto) 또는 SageMaker Python SDK를 사용하여 실시간 및 배치 모델 모니터링 모드 모두에 대해 *데이터 캡처*를 구현할 수 있습니다. 실시간 엔드포인트의 경우, 엔드포인트를 생성할 때 데이터 캡처 구성을 지정해야 합니다.** 실시간 엔드포인트의 지속적 특성 때문에 특정 시간에 데이터 캡처를 켜거나 끄거나 샘플링 빈도를 변경하는 추가 옵션을 구성할 수 있습니다. 추론 데이터를 암호화하도록 선택할 수도 있습니다.

배치 변환 작업의 경우 정기적이고 주기적인 배치 변환 작업에 대해 일정에 따른 모델 모니터링 또는 지속적인 모델 모니터링을 실행하기 위해 데이터 캡처를 활성화할 수 있습니다.** 배치 변환 작업을 생성할 때 데이터 캡처 구성을 지정해야 합니다.** 이 구성에서는 출력과 함께 암호화를 켜거나 추론 ID를 생성할 수 있으며, 이렇게 하면 캡처한 데이터를 Ground Truth 데이터와 일치시키는 데 도움이 됩니다.

# 실시간 엔드포인트에서 데이터 캡처
<a name="model-monitor-data-capture-endpoint"></a>

**참고**  
데이터 캡처는 추론 요청에 영향이 없도록 하기 위해 디스크 사용량이 많은 경우 요청 캡처를 중단합니다. 데이터 캡처가 요청을 계속 캡처하도록 하려면, 디스크 사용률을 75% 미만으로 유지하는 것이 좋습니다.

실시간 엔드포인트의 데이터를 캡처하려면 SageMaker AI 호스팅 서비스를 사용하여 모델을 배포해야 합니다. 이를 위해서는 SageMaker AI 모델을 생성하고, 엔드포인트 구성을 정의하고, HTTPS 엔드포인트를 생성해야 합니다.

데이터 캡처를 켜는 데 필요한 단계는 AWS SDK for Python (Boto) 을 사용하든 SageMaker Python SDK를 사용하든 비슷합니다. AWS SDK를 사용하는 경우 [CreateEndpointConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html) 메서드 내에서 필수 필드와 함께 [DataCaptureConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataCaptureConfig.html) 사전을 정의하여 데이터 캡처를 켭니다. SageMaker Python SDK를 사용하는 경우 [DataCaptureConfig](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html#sagemaker.model_monitor.data_capture_config.DataCaptureConfig) 클래스를 가져와서 이 클래스에서 인스턴스를 초기화하세요. 그런 다음 이 객체를 `sagemaker.model.Model.deploy()`메서드의 `DataCaptureConfig`파라미터에 전달합니다.

이전 코드 스니펫을 사용하려면 예시 코드의 *기울임꼴 자리표시자 텍스트*를 자신의 정보로 대체합니다.

## 데이터 캡처 활성화 방법
<a name="model-monitor-data-capture-defing.title"></a>

데이터 캡처 구성을 지정합니다. 이 구성을 사용하여 요청 페이로드, 응답 페이로드 또는 둘 다를 캡처할 수 있습니다. 진행 코드 조각은 AWS SDK for Python (Boto) 및 SageMaker AI Python SDK를 사용하여 데이터 캡처를 활성화하는 방법을 보여줍니다.

**참고**  
요청 또는 응답 페이로드를 캡처하기 위해 모델 모니터를 사용할 필요는 없습니다.

------
#### [ 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`중 하나를 지정합니다.

키-값 페어의 인수를 `CaptureContentTypeHeader` 사전에 전달하여 SageMaker AI가 캡처된 데이터를 인코딩하는 방법을 선택적으로 지정할 수 있습니다.

```
# Create an endpoint config name.
endpoint_config_name = '<endpoint-config-name>'

# The name of the production variant.
variant_name = '<name-of-production-variant>'                   
  
# The name of the model that you want to host. 
# This is the name that you specified when creating the model.
model_name = '<The_name_of_your_model>'

instance_type = '<instance-type>'
#instance_type='ml.m5.xlarge' # Example    

# Number of instances to launch initially.
initial_instance_count = <integer>

# Sampling percentage. Choose an integer value between 0 and 100
initial_sampling_percentage = <integer>                                                                                                                                                                                                                        

# The S3 URI containing the captured data
s3_capture_upload_path = 's3://<bucket-name>/<data_capture_s3_key>'

# Specify either Input, Output, or both
capture_modes = [ "Input",  "Output" ] 
#capture_mode = [ "Input"] # Example - If you want to capture input only
                            
endpoint_config_response = sagemaker_client.create_endpoint_config(
    EndpointConfigName=endpoint_config_name, 
    # List of ProductionVariant objects, one for each model that you want to host at this endpoint.
    ProductionVariants=[
        {
            "VariantName": variant_name, 
            "ModelName": model_name, 
            "InstanceType": instance_type, # Specify the compute instance type.
            "InitialInstanceCount": initial_instance_count # Number of instances to launch initially.
        }
    ],
    DataCaptureConfig= {
        'EnableCapture': True, # Whether data should be captured or not.
        'InitialSamplingPercentage' : initial_sampling_percentage,
        'DestinationS3Uri': s3_capture_upload_path,
        'CaptureOptions': [{"CaptureMode" : capture_mode} for capture_mode in capture_modes] # Example - Use list comprehension to capture both Input and Output
    }
)
```

다른 엔드포인트 구성 옵션에 대한 자세한 내용은 [Amazon SageMaker AI 서비스 API 참조 가이드](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_Operations_Amazon_SageMaker_Service.html)의 [CreateEndpointConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpointConfig.html) API를 참조하세요.

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

[sagemaker.model\$1monitor](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html) 모듈에서 `DataCaptureConfig`클래스를 가져옵니다. `EnableCapture`를 부울 값 `True`로 설정하여 데이터 캡처를 활성화합니다.

선택적으로 다음 파라미터에 대한 인수를 제공합니다.
+ `SamplingPercentage`: 샘플링할 데이터의 백분율에 해당하는 정수 값입니다. 샘플링 백분율을 제공하지 않는 경우 SageMaker AI는 데이터의 기본값인 20(20%)을 샘플링합니다.
+ `DestinationS3Uri`: SageMaker AI가 캡처된 데이터를 저장하는 데 사용할 Amazon S3 URI입니다. 제공하지 않는 경우 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 엔드포인트를 생성합니다.

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

SageMaker AI에 엔드포인트 구성을 제공합니다. 서비스는 ML 컴퓨팅 인스턴스를 시작하고 구성에서 지정된 대로 모델을 배포합니다.

모델 및 엔드포인트 구성이 완료되면 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpoint.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpoint.html)API를 사용하여 엔드포인트를 생성합니다. 엔드포인트 이름은 AWS 계정의 AWS 리전 내에서 고유해야 합니다.

다음은 요청에 지정된 엔드포인트 구성을 사용하여 엔드포인트를 생성합니다. Amazon SageMaker AI는 엔드포인트를 사용하여 리소스를 프로비저닝하고 모델을 배포합니다.

```
# The name of the endpoint. The name must be unique within an AWS Region in your AWS account.
endpoint_name = '<endpoint-name>' 

# The name of the endpoint configuration associated with this endpoint.
endpoint_config_name='<endpoint-config-name>'

create_endpoint_response = sagemaker_client.create_endpoint(
                                            EndpointName=endpoint_name, 
                                            EndpointConfigName=endpoint_config_name)
```

자세한 정보는 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpoint.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateEndpoint.html)API를 참조하세요.

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

엔드포인트의 이름을 정의합니다. 이 단계는 선택 사항입니다. 이름을 제공하지 않는 경우 SageMaker AI는 고유한 이름을 생성합니다.

```
from datetime import datetime

endpoint_name = f"DEMO-{datetime.utcnow():%Y-%m-%d-%H%M}"
print("EndpointName =", endpoint_name)
```

모델 객체의 내장 `deploy()`메서드를 사용하여 실시간 HTTPS 엔드포인트에 모델을 배포합니다. `initial_instance_count` 필드에 엔드포인트를 실행할 초기 인스턴스 수와 함께 `instance_type`필드에 이 모델을 배포할 Amazon EC2 인스턴스 유형의 이름을 입력합니다.

```
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`으로 정의됨)을 serializer 및 deserializer용 serializer 및 deserializer 객체와 함께 제공합니다. Serializer 유형에 대한 자세한 내용은 [SageMaker AI Python SDK](https://sagemaker.readthedocs.io/en/stable/index.html)의 [Serializers](https://sagemaker.readthedocs.io/en/stable/api/inference/serializers.html) 클래스를 참조하세요.

```
from sagemaker.predictor import Predictor
from sagemaker.serializers import <Serializer>
from sagemaker.deserializers import <Deserializers>

predictor = Predictor(endpoint_name=endpoint_name,
                      serializer = <Serializer_Class>,
                      deserializer = <Deserializer_Class>)

# Example
#from sagemaker.predictor import Predictor
#from sagemaker.serializers import CSVSerializer
#from sagemaker.deserializers import JSONDeserializer

#predictor = Predictor(endpoint_name=endpoint_name,
#                      serializer=CSVSerializer(),
#                      deserializer=JSONDeserializer())
```

진행 코드 예시 시나리오에서는 `validation_with_predictions`이라는 CSV 파일에 로컬로 저장한 샘플 유효성 검사 데이터를 사용하여 엔드포인트를 호출합니다. 샘플 검증 세트에는 각 입력에 대한 레이블이 포함되어 있습니다.

with 문의 처음 몇 줄은 먼저 검증 세트 CSV 파일을 연 다음 파일 내의 각 행을 쉼표 문자 `","`로 분할한 다음 반환된 두 객체를 레이블 및 input\$1cols 변수에 저장합니다. 각 행에 대해 입력(`input_cols`)은 예측 변수(`predictor`)의 객체 내장 메서드 `Predictor.predict()`로 전달됩니다.

모델이 확률을 반환한다고 가정해 보겠습니다. 확률의 범위는 0\$11.0입니다. 모델에서 반환되는 확률이 80%(0.8)보다 큰 경우 예측에 정수 값 레이블 1을 할당합니다. 그렇지 않으면 예측에 정수 값 레이블 0을 할당합니다.

```
from time import sleep

validate_dataset = "validation_with_predictions.csv"

# Cut off threshold of 80%
cutoff = 0.8

limit = 200  # Need at least 200 samples to compute standard deviations
i = 0
with open(f"test_data/{validate_dataset}", "w") as validation_file:
    validation_file.write("probability,prediction,label\n")  # CSV header
    with open("test_data/validation.csv", "r") as f:
        for row in f:
            (label, input_cols) = row.split(",", 1)
            probability = float(predictor.predict(input_cols))
            prediction = "1" if probability > cutoff else "0"
            baseline_file.write(f"{probability},{prediction},{label}\n")
            i += 1
            if i > limit:
                break
            print(".", end="", flush=True)
            sleep(0.5)
print()
print("Done!")
```

이전 단계에서 데이터 캡처를 활성화했으므로 요청 및 응답 페이로드는 일부 추가 메타데이터와 함께 `DataCaptureConfig`에서 지정한 Amazon S3 위치에 저장됩니다. 캡처 데이터를 Amazon S3로 전송하는 데 몇 분이 걸릴 수 있습니다.

캡처된 데이터는 Amazon S3에 저장된 데이터 캡처 파일을 나열하는 방식으로 확인하세요. 해당 Amazon S3 경로의 형식은 `s3:///{endpoint-name}/{variant-name}/yyyy/mm/dd/hh/filename.jsonl`입니다.

호출이 발생한 시간을 기준으로 구성된 서로 다른 기간의 서로 다른 파일을 볼 수 있습니다. 다음을 실행하여 단일 캡처 파일의 내용을 인쇄합니다.

```
print("\n".join(capture_file[-3:-1]))
```

그러면 SageMaker AI에 특정한 JSON 줄 형식의 파일이 반환됩니다. 다음은 `csv/text`데이터를 사용하여 호출한 실시간 엔드포인트에서 가져온 응답 샘플입니다.

```
{"captureData":{"endpointInput":{"observedContentType":"text/csv","mode":"INPUT",
"data":"69,0,153.7,109,194.0,105,256.1,114,14.1,6,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,1,0,1,0\n",
"encoding":"CSV"},"endpointOutput":{"observedContentType":"text/csv; charset=utf-8","mode":"OUTPUT","data":"0.0254181120544672","encoding":"CSV"}},
"eventMetadata":{"eventId":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","inferenceTime":"2022-02-14T17:25:49Z"},"eventVersion":"0"}
{"captureData":{"endpointInput":{"observedContentType":"text/csv","mode":"INPUT",
"data":"94,23,197.1,125,214.5,136,282.2,103,9.5,5,4,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,1,0,1,0,1\n",
"encoding":"CSV"},"endpointOutput":{"observedContentType":"text/csv; charset=utf-8","mode":"OUTPUT","data":"0.07675473392009735","encoding":"CSV"}},
"eventMetadata":{"eventId":"aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee","inferenceTime":"2022-02-14T17:25:49Z"},"eventVersion":"0"}
```

진행 예시에서 `capture_file`객체는 목록 유형입니다. 목록의 첫 번째 요소를 인덱싱하여 단일 추론 요청을 확인합니다.

```
# The capture_file object is a list. Index the first element to view a single inference request  
print(json.dumps(json.loads(capture_file[0]), indent=2))
```

이는 다음과 비슷한 응답을 반환합니다. 반환되는 값은 엔드포인트 구성, SageMaker AI 모델 및 캡처된 데이터에 따라 달라집니다.

```
{
  "captureData": {
    "endpointInput": {
      "observedContentType": "text/csv", # data MIME type
      "mode": "INPUT",
      "data": "50,0,188.9,94,203.9,104,151.8,124,11.6,8,3,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,1,0,0,0,0,0,0,0,0,0,1,1,0,1,0\n",
      "encoding": "CSV"
    },
    "endpointOutput": {
      "observedContentType": "text/csv; charset=character-encoding",
      "mode": "OUTPUT",
      "data": "0.023190177977085114",
      "encoding": "CSV"
    }
  },
  "eventMetadata": {
    "eventId": "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee",
    "inferenceTime": "2022-02-14T17:25:06Z"
  },
  "eventVersion": "0"
}
```

# 배치 변환 작업에서 데이터 캡처
<a name="model-monitor-data-capture-batch"></a>

 배치 변환 작업에 대한 데이터 캡처를 활성화하는 데 필요한 단계는 AWS SDK for Python (Boto) 를 사용하든 SageMaker Python SDK를 사용하든 비슷합니다. AWS SDK를 사용하는 경우 `CreateTransformJob` 메서드 내에서 필수 필드와 함께 [DataCaptureConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_DataCaptureConfig.html) 사전을 정의하여 데이터 캡처를 켭니다. SageMaker AI Python SDK를 사용하는 경우 `BatchDataCaptureConfig` 클래스를 가져와서 이 클래스에서 인스턴스를 초기화하세요. 그런 다음 이 객체를 변환 작업 인스턴스의 `batch_data_capture_config`파라미터에 전달합니다.

 다음 코드 스니펫을 사용하려면 예시 코드의 *기울임꼴 자리표시자 텍스트*를 자신의 정보로 대체합니다.

## 데이터 캡처 활성화 방법
<a name="data-capture-batch-enable"></a>

 변환 작업을 시작할 때 데이터 캡처 구성을 지정하세요. AWS SDK for Python (Boto3) 를 사용하든 SageMaker Python SDK를 사용하든, 변환 작업이 캡처된 데이터를 로깅할 디렉터리인 `DestinationS3Uri` 인수를 제공해야 합니다. 선택적으로 다음 파라미터를 지정할 수도 있습니다.
+  `KmsKeyId`: 캡처된 데이터를 암호화하는 데 사용되는 AWS KMS 키입니다.
+  `GenerateInferenceId`: 데이터를 캡처할 때 변환 작업에서 출력에 추론 ID와 시간을 추가할지 여부를 나타내는 부울 플래그입니다. 이는 Ground Truth 데이터를 수집해야 하는 모델 품질 모니터링에 유용합니다. 추론 ID 및 시간은 캡처된 데이터를 Ground Truth 데이터와 일치시키는 데 도움이 됩니다.

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

 `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`: 변환 작업의 캡처된 출력 데이터입니다.

 데이터 중복을 방지하기 위해 이전 두 디렉터리에 있는 캡처된 데이터는 매니페스트입니다. 각 매니페스트는 원본 객체의 Amazon S3 위치가 포함된 JSONL 파일입니다. 매니페스트 파일은 다음 예시와 같습니다.

```
# 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 접두사를 사용하여 이러한 매니페스트를 구성하고 레이블을 지정합니다. 이렇게 하면 모델 모니터가 분석할 데이터의 적절한 부분을 결정하는 데 도움이 됩니다. 예를 들어, 2022-8-26 13PM UTC에 변환 작업을 시작하면 캡처된 데이터에 `2022/08/26/13/`접두사 문자열이 레이블로 지정됩니다.

## 추론 ID 생성
<a name="data-capture-batch-inferenceid"></a>

 변환 작업에 대해 `DataCaptureConfig`을 구성할 때 부울 플래그 `GenerateInferenceId`를 켤 수 있습니다. 이는 사용자가 수집한 Ground Truth 데이터가 필요한 모델 품질 및 모델 바이어스 모니터링 작업을 실행해야 할 때 특히 유용합니다. 모델 모니터는 추론 ID를 사용하여 캡처된 데이터와 Ground Truth 데이터를 일치시킵니다. Ground Truth 수집에 대한 자세한 내용은 [Ground Truth 레이블을 수집하여 예측과 병합](model-monitor-model-quality-merge.md)섹션을 참조하세요. `GenerateInferenceId`가 켜져 있으면 변환 출력에 추론 ID(임의 UUID)와 각 레코드의 변환 작업 시작 시간(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) 모델을 자동으로 모니터링하여 데이터 품질 문제가 발생할 때 사용자에게 알립니다. 프로덕션 환경의 ML 모델은 대부분의 훈련 데이터세트에서와 같이 신중하게 선별되지 않은 실제 데이터를 예측해야 합니다. 프로덕션 환경에서 모델이 수신하는 데이터의 통계적 속성이 훈련 받은 기준 데이터의 속성과 멀어지면 모델의 예측 정확도가 떨어지기 시작합니다. Amazon SageMaker 모델 모니터는 규칙을 사용하여 데이터 드리프트를 감지하고 데이터 드리프트가 발생하면 알려줍니다. 데이터 품질을 모니터링하려면 다음 단계를 따르세요.
+ 데이터 캡처를 활성화합니다. 이는 실시간 추론 엔드포인트 또는 배치 변환 작업에서 추론 입력 및 출력을 캡처한 다음, 해당 데이터를 Amazon S3에 저장합니다. 자세한 내용은 [데이터 캡처](model-monitor-data-capture.md)섹션을 참조하세요.
+ 기준을 생성합니다. 이 단계에서는 제공하는 입력 데이터세트를 분석하는 기준 작업을 실행합니다. 기준은 대규모 데이터세트에서 데이터 품질을 측정하는 데 사용되는 Apache Spark를 토대로 빌드된 오픈 소스 라이브러리인 [Deequ](https://github.com/awslabs/deequ)를 사용하여 각 기능에 대한 기준 스키마 제약 조건 및 통계를 계산합니다. 자세한 내용은 [기준 생성](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)섹션을 참조하세요.

**참고**  
모델 모니터는 테이블 형식 데이터에 대해서만 모델 지표와 통계를 계산합니다. 예를 들어, 이미지를 입력으로 받아 이미지 기반의 레이블을 출력하는 이미지 분류 모델을 모니터링할 수 있습니다. 모델 모니터는 입력이 아닌 출력에 대한 지표와 통계를 계산할 수 있습니다.

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

데이터 드리프트 및 기타 데이터 품질 문제를 감지할 수 있는 기준이 되는 표준으로 통계 및 제약 조건의 기준 계산이 필요합니다. 모델 모니터는 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에 저장했으면 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable)를 사용하여 `DefaultModelMonitor.suggest_baseline(..)`으로 기본 처리 작업을 시작합니다. [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 s.json 파일에 포함되어 있으며, 제안된 기준 제약 조건은 `output_s3_uri`에서 지정한 위치의 constraints.json 파일에 포함되어 있습니다.

테이블 형식 데이터세트 통계 및 제약 조건의 출력 파일


| 파일 이름 | 설명 | 
| --- | --- | 
| 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 모델 모니터는 열/기능 통계를 기준으로 사전 빌드된 컨테이너를 계산합니다. 통계는 기준 데이터세트를 비롯해 분석 중인 현재 데이터세트에 대 계산됩니다.

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

CloudWatch 지표에 내장된 Amazon SageMaker 모델 모니터 컨테이너를 사용할 수 있습니다. `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 모델 모니터 사전 빌드된 컨테이너는 다음과 같은 위반 검사를 제공합니다.

```
{
    "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 | 현재 실행에서 관찰된 완전성(null이 아닌 항목의 %)이 기능별로 지정된 완전성 임계값에 지정된 임계값을 초과하면 이 위반에 플래그가 지정됩니다. 기준 단계 동안 생성된 제약 조건은 완전성 값을 제안합니다.  | 
| baseline\$1drift\$1check | 현재 데이터세트와 기준 데이터세트 간에 계산된 분포 거리가 `monitoring_config.comparison_threshold`에 지정된 임계값보다 크면 이 위반에 플래그가 지정됩니다.  | 
| missing\$1column\$1check | 현재 데이터세트의 열 수가 기준 데이터세트의 개수보다 작으면 이 위반에 플래그가 지정됩니다.  | 
| extra\$1column\$1check | 현재 데이터세트의 열 수가 기준의 개수보다 많으면 이 위반에 플래그가 지정됩니다.  | 
| categorical\$1values\$1check | 현재 데이터세트의 알 수 없는 값이 기준 데이터세트보다 더 많으면 이 위반에 플래그가 지정됩니다. 이 값은 `monitoring_config.domain_content_threshold`의 임계값에 의해 결정됩니다.  | 

# 모델 품질
<a name="model-monitor-model-quality"></a>

모델 품질 모니터링 작업은 모델의 예측과 모델이 예측하려는 실제 Ground Truth 레이블을 비교하여 모델의 성능을 모니터링합니다. 이를 위해 모델 품질 모니터링은 실시간 또는 배치 추론에서 캡처한 데이터를 Amazon S3 버킷에 저장한 실제 레이블과 병합한 다음 예측을 실제 레이블과 비교합니다.

모델 모니터는 모델의 품질을 측정하기 위해 ML의 문제 유형에 따라 서로 다른 지표를 사용합니다. 예를 들어, 회귀 문제를 다루는 모델이라면, 평가 지표 중 하나는 평균 제곱 오차(MSE)입니다. 다양한 ML 문제 유형에 사용되는 모든 지표에 대한 자세한 내용은 [모델 품질 지표 및 Amazon CloudWatch 모니터링](model-monitor-model-quality-metrics.md)를 참조하세요.

모델 품질 모니터링은 데이터 품질 모니터링과 동일한 단계를 거치게 되지만, 여기에 Amazon S3의 실제 레이블을 실시간 추론 엔드포인트 또는 배치 변환 작업에서 캡처한 예측과 병합하는 단계가 추가됩니다. 모델 품질을 모니터링하려면 다음 단계를 따르세요.
+ 데이터 캡처를 활성화합니다. 이는 실시간 추론 엔드포인트 또는 배치 변환 작업에서 추론 입력 및 출력을 캡처한 다음, 해당 데이터를 Amazon S3에 저장합니다. 자세한 내용은 [데이터 캡처](model-monitor-data-capture.md)섹션을 참조하세요.
+ 기준을 생성합니다. 이 단계에서는 모델의 예측을 기준 데이터세트의 Ground Truth 레이블과 비교해보는 기준 작업을 실행합니다. 기준 작업은 모델 성능을 평가하는 데 기준이 되는 임계값을 정의하는 기준 통계 규칙 및 제약 조건을 자동으로 생성해줍니다. 자세한 내용은 [모델 품질 기준 만들기](model-monitor-model-quality-baseline.md)섹션을 참조하세요.
+ 모델 품질 모니터링 작업을 정의하고 스케줄링합니다. 모델 품질 모니터링 작업에 대한 특정 정보 및 코드 샘플은 [모델 품질 모니터링 작업 예약](model-monitor-model-quality-schedule.md) 섹션을 참조하세요. 작업 모니터링에 대한 일반적인 내용은 [모니터링 작업 일정 예약](model-monitor-scheduling.md)섹션을 참조하세요.
+ 모델 모니터가 실시간 추론 엔드포인트 또는 배치 변환 작업에서 캡처한 예측 데이터와 병합하게 될 Ground Truth 레이블을 수집합니다. 자세한 내용은 [Ground Truth 레이블을 수집하여 예측과 병합](model-monitor-model-quality-merge.md)섹션을 참조하세요.
+ 모델 품질 모니터링을 Amazon CloudWatch와 통합합니다. 자세한 내용은 [CloudWatch를 사용한 모델 품질 모니터링 지표](model-monitor-model-quality-metrics.md#model-monitor-model-quality-cw)섹션을 참조하세요.
+ 모니터링 작업의 결과물을 해석합니다. 자세한 내용은 [결과 해석](model-monitor-interpreting-results.md)섹션을 참조하세요.
+ SageMaker Studio를 사용하여 모델 품질 모니터링을 활성화하고 결과를 시각화합니다. 자세한 내용은 [Amazon SageMaker Studio에서 실시간 엔드포인트의 결과 시각화](model-monitor-interpreting-visualize-results.md)섹션을 참조하세요.

**Topics**
+ [모델 품질 기준 만들기](model-monitor-model-quality-baseline.md)
+ [모델 품질 모니터링 작업 예약](model-monitor-model-quality-schedule.md)
+ [Ground Truth 레이블을 수집하여 예측과 병합](model-monitor-model-quality-merge.md)
+ [모델 품질 지표 및 Amazon CloudWatch 모니터링](model-monitor-model-quality-metrics.md)

# 모델 품질 기준 만들기
<a name="model-monitor-model-quality-baseline"></a>

모델 예측을 사용자가 Amazon S3에 저장해둔 기준 데이터세트의 실측 레이블과 비교하는 기준 작업을 생성합니다. 일반적으로 훈련 데이터세트를 기준 데이터세트로 사용합니다. 기준 작업은 해당 모델에 대한 지표를 계산한 다음 모델 품질의 드리프트를 모니터링하는 데 사용할 제약 조건을 제안해줍니다.

기준 작업을 생성하려면, 모델이 수행한 예측이 포함된 데이터세트와 작업 데이터에 대한 Ground Truth를 나타내는 레이블이 준비되어야 합니다.

기준 작업을 생성하려면, 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)}
   ```

   사전 처리 스크립트는 [Model Monitor](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html) 설명서에 정의된 대로 `record_preprocessor_script`의 형태로 기준 또는 모니터링 일정에 추가하는 것이 가능합니다.

1. 제약 조건에 만족한다면, 모니터링 일정을 생성할 때 해당 제약 조건을 `constraints`매개변수로서 전달하세요. 자세한 내용은 [모델 품질 모니터링 작업 예약](model-monitor-model-quality-schedule.md)섹션을 참조하세요.

제안된 기준 제약 조건은 사용자가 `output_s3_uri`를 통해 지정한 위치의 constraints.json 파일에 포함되어 있습니다. 이 파일의 스키마에 대한 자세한 내용은 [제약 조건에 대한 스키마(constraints.json 파일)](model-monitor-byoc-constraints.md)섹션을 참조하세요.

# 모델 품질 모니터링 작업 예약
<a name="model-monitor-model-quality-schedule"></a>

기준 생성을 마쳤다면, `ModelQualityMonitor`클래스 인스턴스의 `create_monitoring_schedule()`메서드를 호출하여 시간별 모델 품질 모니터를 예약할 수 있습니다. 다음 섹션은 실시간 엔드포인트에 배포된 모델 및 배치 변환 작업에 사용할 모델 품질 모니터를 생성하는 방법을 보여줍니다.

**중요**  
모니터링 일정을 생성할 때는 배치 변환 입력이나 엔드포인트 입력 중에서 하나를 지정할 수 있지만, 둘 다 지정할 수는 없습니다.

데이터 품질 모니터링과는 달리, 모델 품질을 모니터링하려면 Ground Truth 레이블을 제공해야 합니다. 그러나 Ground Truth 레이블은 지연될 수 있습니다. 이 문제를 해결하려면, 모니터링 일정을 생성할 때 오프셋을 지정하세요.

## 모델 모니터 오프셋
<a name="model-monitor-model-quality-schedule-offsets"></a>

모델 품질 작업에는 `StartTimeOffset`및 `EndTimeOffset`이 포함되며, 이는 `create_model_quality_job_definition`메서드의 `ModelQualityJobInput`매개변수 필드로서 다음과 같이 작동합니다.
+ `StartTimeOffset` - 지정된 경우, 작업의 시작 시간으로부터 이만큼의 시간이 차감됩니다.
+ `EndTimeOffset` - 지정된 경우, 작업의 종료 시간으로부터 이만큼의 시간이 차감됩니다.

오프셋 형식은 예컨대 -PT7H와 같이 표기되며, 여기서 7H는 7시간을 의미합니다. -PT\$1H 또는 -P\$1D 형식으로 사용이 가능하며, 여기서 H=시간, D=일, M=분이고, \$1은 숫자입니다. 또한 오프셋은 [ISO 8601 지속시간 형식](https://en.wikipedia.org/wiki/ISO_8601#Durations)을 사용해야 합니다.

예를 들어, 해당 Ground Truth가 1일이 지난 후부터 들어오기 시작하지만 일주일 안에는 완료되지 않는 경우라면, `StartTimeOffset`을 `-P8D`로, `EndTimeOffset`을 `-P1D`로 설정하세요. 그런 다음에 작업 실행 시점을 `2020-01-09T13:00`로 예약한다면, `2020-01-01T13:00`\$1`2020-01-08T13:00`사이의 데이터가 분석됩니다.

**중요**  
일정 케이던스는 다음 번의 실행이 시작되기 전에 한 가지 실행이 먼저 완료되는 형태로 설정해야 하며, 이렇게 해야 실행 시 Ground Truth 병합 작업과 모니터링 작업이 완료될 수 있습니다. 실행의 최대 런타임은 두 작업으로 나누어지기 때문에, 시간별 모델 품질 모니터링 작업에서의 경우 `StoppingCondition`의 일부로서 지정된 `MaxRuntimeInSeconds`의 값은 1800을 넘지 않아야 합니다.

## 실시간 엔드포인트에 배포된 모델에 대한 모델 품질 모니터링
<a name="model-monitor-data-quality-schedule-rt"></a>

실시간 엔드포인트에 대한 모델 품질 모니터를 예약하려면, 다음 코드 샘플에 나와 있는 것처럼 `EndpointInput`인스턴스를 `ModelQualityMonitor`인스턴스의 `endpoint_input`인수로 전달하세요.

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

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

## 배치 변환 작업에 대한 모델 품질 모니터링
<a name="model-monitor-data-quality-schedule-tt"></a>

배치 변환 작업에 대한 모델 품질 모니터를 예약하려면, 다음 코드 샘플에 나와 있는 것처럼 `BatchTransformInput`인스턴스를 `ModelQualityMonitor`인스턴스의 `batch_transform_input`인수로 전달하세요.

```
from sagemaker.model_monitor import CronExpressionGenerator

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

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

# Ground Truth 레이블을 수집하여 예측과 병합
<a name="model-monitor-model-quality-merge"></a>

모델 품질 모니터링은 모델의 품질을 측정하기 위해 해당 모델이 수행한 예측과 실측 레이블을 비교하게 됩니다. 이렇게 하려면, 엔드포인트에서 캡처된 데이터 또는 배치 변환 작업에 주기적으로 레이블을 지정한 다음 이를 Amazon S3에 업로드해야 합니다.

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`가 없다면, 모델 모니터는 캡처된 데이터 레코드의 `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 레이블을 생성하여 업로드를 마쳤다면, 모니터링 작업을 생성하는 단계에서 해당 레이블의 위치를 매개변수로 포함시키세요. 를 사용하는 경우 `create_model_quality_job_definition` 메서드 호출에서 Ground Truth 레이블의 위치를 `GroundTruthS3Input` 파라미터의 `S3Uri` 필드로 지정하여이 작업을 AWS SDK for Python (Boto3)수행합니다. 현재 SageMaker Python SDK를 사용 중이라면, `ModelQualityMonitor`객체의 `create_monitoring_schedule`호출 시 Ground Truth 레이블의 위치를 `ground_truth_input`매개변수로서 지정하세요.

# 모델 품질 지표 및 Amazon CloudWatch 모니터링
<a name="model-monitor-model-quality-metrics"></a>

모델 품질 모니터링 작업은 다양한 지표를 계산하여 기계 학습 모델의 품질과 성능을 평가합니다. 계산된 특정 지표는 회귀, 바이너리 분류 또는 멀티클래스 분류와 같은 ML 문제의 유형에 따라 달라집니다. 시간 경과에 따른 모델 드리프트를 감지하려면 이러한 지표를 모니터링하는 것이 중요합니다. 다음 섹션에서는 각 문제 유형에 대한 주요 모델 품질 지표와 CloudWatch를 사용하여 모델의 성능을 지속적으로 추적하는 자동 모니터링 및 알림을 설정하는 방법을 다룹니다.

**참고**  
지표의 표준 편차는 최소한 200개 이상의 샘플을 사용할 수 있는 경우에만 제공됩니다. Model Monitor가 표준 편차를 계산하는 방식은 계산 데이터의 80%를 5회 랜덤하게 샘플링하고 지표를 계산한 다음 해당 결과에 대한 표준 편차를 취하는 것입니다.

## 회귀 지표
<a name="model-monitor-model-quality-metrics-regression"></a>

다음 예제는 모델 품질 모니터가 회귀 문제에 대해 계산을 수행하는 경우의 지표를 보여줍니다.

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

## 바이너리 분류 지표
<a name="model-monitor-model-quality-metrics-binary"></a>

다음 예제는 모델 품질 모니터가 바이너리 분류 문제에 대해 계산을 수행하는 경우의 지표를 보여줍니다.

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

## 멀티클래스 지표
<a name="model-monitor-model-quality-metrics-multi"></a>

다음 예제는 모델 품질 모니터가 멀티클래스 분류 문제에 대해 계산을 수행하는 경우의 지표를 보여줍니다.

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

## CloudWatch를 사용한 모델 품질 모니터링 지표
<a name="model-monitor-model-quality-cw"></a>

모니터링 일정을 만들 때 `enable_cloudwatch_metrics`의 값을 `True`로 설정하면, 모델 품질 모니터링 작업은 모든 지표를 CloudWatch로 전송하게 됩니다.

모델 품질 지표는 다음 네임스페이스에 표시됩니다.
+ 실시간 엔드포인트인 경우: `aws/sagemaker/Endpoints/model-metrics`
+ 배치 변환 작업인 경우: `aws/sagemaker/ModelMonitoring/model-metrics`

방출되는 지표 목록은 이 페이지의 이전 섹션을 참조하세요.

CloudWatch 지표를 사용하면, 사용자가 지정한 임계값을 특정 지표가 충족하지 못할 경우 이를 알려주는 경보를 생성할 수 있습니다. CloudWatch 경보를 만드는 방법에 대한 지침은 *CloudWatch 사용 설명서*의 [정적 임곗값을 기반으로 CloudWatch 경보 생성](https://docs.aws.amazon.com/AmazonCloudWatch/latest/monitoring/ConsoleAlarms.html) 섹션을 참조하세요.

# 프로덕션 환경의 모델에 대한 바이어스 드리프트
<a name="clarify-model-monitor-bias-drift"></a>

Amazon SageMaker Clarify 편향 모니터링은 데이터 사이언티스트와 ML 엔지니어가 예측의 편향을 정기적으로 모니터링할 수 있도록 도와줍니다. 모델이 모니터링되는 동안, 고객은 SageMaker Studio에서 편향을 자세히 설명하는 내보내기 가능한 보고서와 그래프를 확인할 수 있고, 특정 임계값을 초과하는 편향이 감지되면 알림을 받아보도록 Amazon CloudWatch에서 경보를 구성할 수 있습니다. 훈련 데이터가 해당 모델이 배포 과정에서 보는 데이터(즉, 라이브 데이터)와 다를 경우, 배포된 ML 모델에서 편향이 발생하거나 악화될 수 있습니다. 라이브 데이터 분포에서 이러한 종류의 변동은 일시적일 수도 있고(예: 일부 일시적인 실제 환경의 이벤트로 인한 변동) 또는 영구적인 것일 수도 있습니다. 어느 경우든, 이러한 변동을 감지하는 것이 중요할 수 있습니다. 예를 들어, 주택 가격 예측을 위한 모델에서 해당 모델의 훈련에 사용된 모기지 금리가 현재의 실제 모기지 금리와 다를 경우, 예측의 결과가 편향될 수 있습니다. Model Monitor의 편향 감지 기능을 사용하면, SageMaker AI가 특정 임곗값을 초과하는 편향을 감지했을 때 사용자가 SageMaker Studio 및 Amazon CloudWatch 경보를 통해서 확인할 수 있는 지표가 자동으로 생성됩니다.

일반적으로 훈련 및 배포 단계에서 편향을 측정하는 것만으로는 충분하지 않을 수 있습니다. 모델을 이미 배포한 상황에서, 배포된 모델에서 보게 되는 데이터(즉, 라이브 데이터)의 분포가 훈련 데이터세트 상의 데이터 분포와는 다른 경우가 생길 수 있습니다. 이러한 변동으로 인해 시간이 지남에 따라 모델에 편향이 생길 수 있습니다. 라이브 데이터 분포에서 발생하는 변동은 일시적일 수도 있고(예: 연말연시와 같은 일부 단기적인 행동으로 인한) 또는 영구적인 것일 수도 있습니다. 어느 경우든, 이러한 변동을 감지하고 적절한 경우 편향을 줄이기 위한 조치를 취하는 것이 중요할 수 있습니다.

이러한 변동을 감지하기 위해, SageMaker Clarify는 배포된 모델의 편향 지표를 지속적으로 모니터링하다가 지표가 임계값을 초과하는 경우 자동으로 경보를 발생시켜주는 기능을 제공합니다. DPPL 편향 지표를 예로 들어보겠습니다. 배포 중에 DPPL이 속해야 하는 허용값 범위 A=(amin​,amax​)를 예컨대 (-0.1, 0.1) 구간으로 지정합니다. 이 범위를 조금이라도 벗어나면 편향 감지됨 경보가 발생해야 합니다.** SageMaker Clarify를 사용하면 이러한 검사를 정기적으로 수행할 수 있습니다.

예를 들어, 검사 빈도를 2일 간격으로 설정하는 것이 가능합니다. 즉, SageMaker Clarify는 2일 기간 이내에 수집된 데이터에 대해 DPPL 지표를 계산하게 됩니다. 이 예제에서 Dwin는 해당 모델이 지난 2일 기간 이내에 처리한 데이터입니다. Dwin​에 대해 계산된 DPPL 값 bwin​가 허용 범위 A를 벗어나게 되면 경보가 발생합니다. bwin가 A를 벗어나는지 확인하는 이 방법은 다소 복잡할 수 있습니다. Dwin​는 매우 적은 수의 샘플로 구성될 수 있으며 라이브 데이터 분포를 반영하지 못할 수 있습니다. 표본 크기가 작다는 것은 Dwin​에 대해 계산된 편향 bwin​의 값이 그다지 견고한 추정치가 아닐 수도 있다는 뜻입니다. 사실, 순전히 우연에 의해 너무 높은 (또는 낮은) bwin의 값이 관찰될 수도 있습니다. SageMaker Clarify는 관찰된 데이터 Dwin에서 도출된 결론이 통계적으로 유의하도록 하기 위해 신뢰 구간을 사용합니다. 특히 이는 Normal Bootstrap Interval 메서드를 사용하여 구간 C=(cmin,cmax)를 구성함으로써 SageMaker Clarify가 전체 라이브 데이터에 대해 계산된 실제 편향 값이 높은 확률로 C에 포함되어 있다고 확신할 수 있도록 만들어줍니다. 이 때, 만약 신뢰 구간 C가 허용 범위 A와 겹쳐 있다면, SageMaker Clarify는 이를 “라이브 데이터 분포의 편향 지표 값이 허용 범위 내에 속할 가능성이 높다”라고 해석하게 됩니다. 만약 C와 A가 서로 분리되어 있다면, SageMaker Clalify는 편향 지표가 A에 있지 않다고 확신하여 경보를 발생시킵니다.

## 모델 모니터 샘플 노트북
<a name="clarify-model-monitor-sample-notebooks-bias-drift"></a>

Amazon SageMaker Clarify는 실시간 엔드포인트에 대한 추론 데이터를 캡처하고, 변화하는 편향을 모니터링하기 위한 기준을 만들고, 결과를 검사하는 방법을 보여주는 다음과 같은 샘플 노트북을 제공합니다.
+ [Monitoring bias drift and feature attribution drift Amazon SageMaker Clarify](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_model_monitor/fairness_and_explainability/SageMaker-Model-Monitor-Fairness-and-Explainability.html) - Amazon SageMaker Model Monitor를 사용하여 시간 경과에 따른 바이어스 드리프트 및 특징 속성 드리프트를 모니터링합니다.

이 노트북은 Amazon SageMaker Studio에서만 실행이 검증되었습니다. Amazon SageMaker Studio에서 노트북을 여는 방법에 대한 지침이 필요한 경우, [Amazon SageMaker Studio Classic 노트북 만들기 또는 열기](notebooks-create-open.md)섹션을 참조하세요. 커널을 선택하라는 메시지가 표시되면, **Python 3 (Data Science)**를 선택합니다. 다음 주제들에는 마지막 두 단계의 주요 내용과 예제 노트북에서 보았던 코드 예제가 포함되어 있습니다.

**Topics**
+ [모델 모니터 샘플 노트북](#clarify-model-monitor-sample-notebooks-bias-drift)
+ [바이어스 드리프트 기준 생성](clarify-model-monitor-bias-drift-baseline.md)
+ [바이어스 드리프트 위반](clarify-model-monitor-bias-drift-violations.md)
+ [바이어스 드리프트를 모니터링하는 파라미터](clarify-config-json-monitor-bias-parameters.md)
+ [바이어스 드리프트 모니터링 작업 예약](clarify-model-monitor-bias-drift-schedule.md)
+ [데이터 바이어스 드리프트 보고서 검사](clarify-model-monitor-bias-drift-report.md)
+ [바이어스 드리프트 분석을 위한 CloudWatch 지표](clarify-model-monitor-bias-drift-cw.md)

# 바이어스 드리프트 기준 생성
<a name="clarify-model-monitor-bias-drift-baseline"></a>

실시간 또는 배치 변환 추론 데이터를 캡처하도록 애플리케이션을 구성했다면, 바이어스 드리프트의 모니터링을 위해 먼저 필요한 작업은 기준을 생성하는 것입니다. 여기에는 데이터 입력 방식, 민감한 그룹 구분, 예측 캡처 방법, 해당 모델 및 훈련 후 편향 지표를 구성하는 작업이 포함됩니다. 그 다음에는 기준 설정 작업을 시작해야 합니다.

모델 편향 모니터는 ML 모델의 바이어스 드리프트를 정기적으로 탐지할 수 있습니다. 다른 모니터링 유형과 마찬가지로, 모델 편향 모니터를 생성하는 표준적인 단계는 먼저 기준을 설정한 다음에 모니터링 일정을 지정하는 것입니다.

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

`DataConfig`는 분석하려는 데이터세트(예: 데이터세트 파일), 해당 형식(즉, CSV 또는 JSON Lines), 헤더(있는 경우) 및 레이블과 관련한 정보를 저장합니다.

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

`BiasConfig`는 데이터세트에 있는 민감한 그룹의 구성 설정입니다. 일반적으로 편향은 지표를 계산하고 이를 그룹 간에 비교하는 방식으로 측정됩니다. 관심 그룹을 패싯이라고 합니다.** 훈련 후 편향의 경우, 긍정적인 레이블도 함께 고려해야 합니다.

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

`ModelPredictedLabelConfig`는 모델 출력으로부터 예측된 레이블을 추출하는 방법을 지정합니다. 이 예제에서는 고객의 이탈이 잦을 것으로 예상하여 컷오프를 0.8로 선택했습니다. 좀 더 복잡한 출력이 필요하다면, 몇 가지 옵션이 더 있습니다.예를 들어 “label”은 인덱스, 이름을 나타내며, 또는 JMEsPath를 사용하여 엔드포인트 응답 페이로드에서 예측된 레이블을 찾는 것도 가능합니다.

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

`ModelConfig`는 추론에 사용할 모델과 관련된 구성 설정입니다. 훈련 후 편향 지표를 계산하기 위해서는, 제공된 해당 모델 이름에 대한 추론을 계산 과정에서 가져와야 합니다. 이렇게 하기 위해 처리 작업은 해당 모델을 사용하여 임시 엔트포인트(섀도우 엔드포인트라고도 함)를 만듭니다.** 처리 작업은 계산이 완료되고 나면 해당 섀도우 엔드포인트를 삭제합니다. 이러한 구성은 설명 가능성 모니터에서도 사용됩니다.

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

이제 기준 설정 작업을 시작할 수 있습니다.

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

예약된 모니터는 기준 설정 작업의 이름을 자동으로 반영한 다음 모니터링이 시작되기 전에 대기합니다.

# 바이어스 드리프트 위반
<a name="clarify-model-monitor-bias-drift-violations"></a>

바이어스 드리프트 작업은 [기준 구성](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelBiasJobDefinition.html#sagemaker-CreateModelBiasJobDefinition-request-ModelBiasBaselineConfig)에서 제공하는 기준 제약 조건을 현재의 `MonitoringExecution`에 대한 분석 결과와 비교하여 평가합니다. 이 작업은 위반이 감지되면 해당 위반을 실행 출력 위치에 있는 *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"
    }]
}
```

편향 지표는 분포가 균등한 정도를 측정하는 데 사용됩니다. 값이 0에 가까우면 분포가 더 잘 이루어지고 있음을 나타냅니다. 만약 작업 분석 결과 파일(analysis.json)의 편향 지표 값이 기준 제약 조건 파일의 해당 값보다 나쁘다면, 위반으로 기록됩니다. 예를 들어, 만약 DPPL 편향 지표의 기준 제약 조건이 `0.2`이고 분석 결과가 `0.1`이라면, `0.1`은 `0.2`보다는 `0`에 더 가까우므로 이는 위반으로 기록되지 않습니다. 그러나 만약 분석 결과가 `-0.3`이라면, 이는 기준 제약 조건인 `0.2`보다 `0`에서 더 멀리 떨어진 값이기 때문에 위반으로 기록됩니다.

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

# 바이어스 드리프트를 모니터링하는 파라미터
<a name="clarify-config-json-monitor-bias-parameters"></a>

Amazon SageMaker Clarify 바이어스 모니터링은 [분석 구성 파일](clarify-processing-job-configure-analysis.md)의 분석 구성에서 사용된 매개변수의 하위 집합을 재사용합니다. 이 주제에서는 구성 매개변수에 대해 설명한 후, JSON 파일의 예제를 제공합니다. 이러한 파일은 기계 학습 모델이 프로덕션 단계에 있을 때 바이어스 드리프트를 모니터링하도록 CSV 및 JSON Lines 데이터세트를 구성하는 데 사용됩니다.

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 Lines인 경우)로서 지정됩니다.
+ `"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 Lines인 경우 해당 특징 열을 찾는 데 사용되는 것은 JMEsPath입니다.
+ `InferenceAttribute` - 편향 지표를 사용하여 편향을 모니터링하는 데 사용할 대상 속성에 대한 모델 출력의 인덱스 또는 JMEsPath 위치입니다. 만약 CSV `accept_type`의 경우에서 이 값이 제공되지 않았다면, 모델 출력이 점수 또는 확률에 해당하는 단일 숫자 값인 것으로 간주됩니다.
+ `ProbabilityAttribute` - 확률을 계산하는 모델 출력의 인덱스 또는 JMEsPath 위치입니다. 예를 들어, 모델 출력이 레이블 및 확률 목록을 포함하는 JSON Lines인 경우라면, 최대 확률에 해당하는 레이블이 편향 계산 용도로 선택됩니다.
+ `ProbabilityThresholdAttribute` - (선택사항) 바이너리 분류의 경우에서 바이너리 레이블을 선택하기 위한 임계값을 나타내는 부동 소수점 값입니다. 기본값은 0.5입니다.

## CSV 및 JSON Lines 데이터 세트를 위한 JSON 구성 파일의 예제
<a name="clarify-config-json-monitor-bias-parameters-examples"></a>

다음은 CSV 및 JSON Lines 데이터세트를 구성하여 바이어스 드리프트를 모니터링하기 위해 사용하는 JSON 파일의 예제입니다.

**Topics**
+ [CSV 데이터 세트](#clarify-config-json-monitor-bias-parameters-example-csv)
+ [JSON Lines 데이터 세트](#clarify-config-json-monitor-bias-parameters-example-jsonlines)

### CSV 데이터 세트
<a name="clarify-config-json-monitor-bias-parameters-example-csv"></a>

다음 예제와 같이 특징 열 4개와 레이블 열 1개가 있는 데이터 세트에서 첫 번째 특징과 레이블이 이진수라고 가정해 보겠습니다.

```
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 기준으로 시작하는 번호 매기기가 사용되므로, 여기서 0은 모델 출력의 첫 번째 열을 나타냅니다.

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

그 밖에, 다른 매개변수를 사용하여 확률 값을 이진수의 예측된 레이블로 변환하는 방법도 있습니다. 0 기준으로 시작하는 번호 매기기가 사용된 상황에서, 1은 두 번째 열을 나타내고, 0.6이라는 `ProbabilityThresholdAttribute`값은 확률이 0.6보다 크면 이진수 레이블을 1로 예측한다는 것을 나타냅니다.

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

### JSON Lines 데이터 세트
<a name="clarify-config-json-monitor-bias-parameters-example-jsonlines"></a>

다음 예제와 같이 특징 열 4개와 레이블 열 1개가 있는 데이터 세트에서 첫 번째 특징과 레이블이 이진수라고 가정해 보겠습니다.

```
{"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 Lines 데이터세트를 구성할 수 있는 방법의 예시를 보여줍니다.

```
{
    "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-quality-schedule.md#model-monitor-model-quality-schedule-offsets)섹션을 참조하세요.

사용자가 기준 설정 작업을 이미 제출한 경우, 모니터는 기준 설정 작업으로부터 분석 구성을 자동으로 반영합니다. 만약 사용자가 기준 설정 단계를 건너뛰었거나, 캡처 데이터세트의 특성이 훈련 데이터세트의 특성과 다르다면, 분석 구성을 반드시 제공해야 합니다.

## 실시간 엔드포인트에 배포된 모델에 대한 바이어스 드리프트 모니터링
<a name="model-monitor-bias-quality-rt"></a>

실시간 엔드포인트에 대한 바이어스 드리프트 모니터를 예약하려면, 다음 코드 샘플에 나와 있는 것처럼 `EndpointInput`인스턴스를 `ModelBiasModelMonitor`인스턴스의 `endpoint_input`인수로 전달하세요.

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

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

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

## 배치 변환 작업에 대한 바이어스 드리프트 모니터링
<a name="model-monitor-bias-quality-bt"></a>

배치 변환 작업에 대한 바이어스 드리프트 모니터를 예약하려면, 다음 코드 샘플에 나와 있는 것처럼 `BatchTransformInput`인스턴스를 `ModelBiasModelMonitor`인스턴스의 `batch_transform_input`인수로 전달하세요.

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

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

# 데이터 바이어스 드리프트 보고서 검사
<a name="clarify-model-monitor-bias-drift-report"></a>

만약 SageMaker Studio에서 생성된 보고서의 모니터링 결과를 검사할 수 없는 상황이라면, 이를 다음과 같이 인쇄할 수 있습니다.

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

 기준과 비교 시 위반 항목이 있는 경우, 다음과 같이 나열됩니다.

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

모델이 실시간 엔드포인트에 배포되어 있다면, SageMaker AI Studio에서 **엔드포인트** 탭을 선택한 다음 해당 엔드포인트를 두 번 클릭하여 분석 결과 및 CloudWatch 지표의 시각화를 확인할 수 있습니다.

# 바이어스 드리프트 분석을 위한 CloudWatch 지표
<a name="clarify-model-monitor-bias-drift-cw"></a>

이 가이드는 SageMaker Clalify에서 바이어스 드리프트 분석을 위해 사용할 수 있는 CloudWatch 지표와 관련 속성을 보여줍니다. 바이어스 드리프트 모니터링 작업은 [훈련 전 편향 지표](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-measure-data-bias.html)와 [훈련 후 편향 지표](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-measure-post-training-bias.html)를 모두 계산한 다음, 이를 다음과 같은 CloudWatch 네임스페이스에 게시하게 됩니다.
+ 실시간 엔드포인트인 경우: `aws/sagemaker/Endpoints/bias-metrics`
+ 배치 변환 작업인 경우: `aws/sagemaker/ModelMonitoring/bias-metrics` 

CloudWatch 지표 이름은 해당 지표의 약식 이름을 `bias_metric`에 붙입니다.

예를 들어, `bias_metric_CI`는 클래스 불균형(CI)에 대한 편향 지표입니다.

**참고**  
`+/- infinity`는 부동 소수점 숫자 `+/- 2.348543e108`의 형태로 게시되며, null 값을 포함한 오류는 게시되지 않습니다.

각 지표에는 다음 속성이 있습니다.
+ `Endpoint`: 해당 시, 모니터링되는 엔드포인트의 이름입니다.
+ `MonitoringSchedule`: 모니터링 작업을 위한 일정의 이름입니다.
+ `BiasStage`: 바이어스 드리프트 모니터링 작업의 단계 이름입니다. [`Pre-training`] 또는 [`Post-Training`]을 선택합니다.
+ `Label`: 모니터링 작업 분석 구성 `label`에 의해 제공되는 대상 특징의 이름입니다.
+ `LabelValue`: 모니터링 작업 분석 구성 `label_values_or_threshold`에 의해 제공되는 대상 특징의 값입니다.
+ `Facet`: 모니터링 작업 분석의 구성 패싯 `name_of_index`에 의해 제공되는 해당 패싯의 이름입니다.
+ `FacetValue`: 모니터링 작업 분석의 구성 패싯 `nvalue_or_threshold`에 의해 제공되는 해당 패싯의 값입니다.

모니터링 작업이 지표를 게시하지 않도록 하려면, [모델 바이어스 작업](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelBiasJobDefinition.html) 정의의 `Environment`맵에서 `publish_cloudwatch_metrics`를 `Disabled`로 설정합니다.

# 프로덕션 환경의 모델에 대한 특성 어트리뷰션 드리프트
<a name="clarify-model-monitor-feature-attribution-drift"></a>

프로덕션 중인 모델의 라이브 데이터 분포에서 드리프트가 발생하면, 편향 지표를 모니터링할 때 편향 드리프트가 일어날 수 있는 것과 마찬가지로, 특징 속성 값에도 그에 따른 드리프트가 발생할 수 있습니다. Amazon SageMaker Clarify 특징 속성 모니터링은 데이터 사이언티스트와 ML 엔지니어가 특징 속성의 편향을 정기적으로 모니터링할 수 있도록 도와줍니다. 모델이 모니터링되는 동안, 고객은 SageMaker Studio에서 특징 속성을 자세히 설명하는 내보내기 가능한 보고서와 그래프를 확인할 수 있고, 속성 값이 특정 임계값을 넘어 드리프트하는 것으로 감지되면 알림을 받아보도록 Amazon CloudWatch에서 경보를 구성할 수 있습니다.

구체적인 상황에 대입하여 이를 살펴보기 위해, 대학 입시를 위한 가상의 시나리오를 생각해 보겠습니다. 해당 훈련 데이터와 라이브 데이터에서 다음과 같은 (집계된) 특징 속성 값을 관찰했다고 가정해 보겠습니다.

대학 입시 가상 시나리오


| 기능 | 훈련 데이터의 속성 | 라이브 데이터의 속성 | 
| --- | --- | --- | 
| SAT 점수 | 0.70 | 0.10 | 
| 평점평균(GPA) | 0.50 | 0.20 | 
| 학급 석차 | 0.05 | 0.70 | 

훈련 데이터에서 라이브 데이터로의 변동 폭이 크게 나타났습니다. 특징 순위가 완전히 뒤바뀌었습니다. 편향 드리프트와 마찬가지로, 특징 속성 드리프트가 발생하는 것은 라이브 데이터 분포의 변화가 원인일 수 있으므로 라이브 데이터 상에서 모델의 동작을 자세히 살펴볼 필요가 있습니다. 앞서와 마찬가지로, 이러한 시나리오에서 먼저 수행할 일은 드리프트가 발생했다는 경보가 울리게 하는 것입니다.

훈련 데이터에서 라이브 데이터로 넘어갈 때 개별 특징의 순위가 어떻게 변하는지 비교하는 방법으로 드리프트를 감지할 수 있습니다. 순위 순서의 변화를 민감하게 살펴보는 것 외에도, 특징의 원시 속성 점수에도 민감하게 주의를 기울여야 합니다. 예를 들어, 두 종류의 특징이 훈련 데이터에서 라이브 데이터로 넘어갈 때 각각의 순위가 동일한 등수만큼 떨어진 경우라면, 훈련 데이터상에서 속성 점수가 더 높게 나타난 특징을 더 민감하게 살펴볼 필요가 있습니다. 이러한 특성을 염두에 둔 채, 정규화된 할인 누적 이득(NDCG) 점수를 이용하여 훈련 데이터와 라이브 데이터의 특징 속성 순위를 비교해보도록 하겠습니다.

구체적으로 다음과 같은 내용을 가정해봅시다.
+ *F=[f1,...,fm]*는 훈련 데이터에서 각자의 속성 점수를 기준으로 정렬된 특징의 목록입니다.여기서 *m*은 특징의 총 개수입니다. 예를 들어, 이 사나리오에서 *F*=[SAT 점수, GPA, 학급 석차]입니다.
+ *a(f)*는 특징 *f*가 주어졌을 때 훈련 데이터에 대한 특징 속성 점수를 반환하는 함수입니다. 예컨대, *a*(SAT 점수) = 0.70입니다.
+ *F′=[f′1,...,f′m]*는 라이브 데이터에서 각자의 속성 점수를 기준으로 정렬된 특징의 목록입니다. 예컨대, *F*′=[학급 석차, GPA, SAT 점수]입니다.

이제 NDCG를 다음과 같이 계산할 수 있습니다.

        NDCG=DCG/iDCG

여기서 DCG와 iDCG는 각각 다음과 같습니다.
+ DCG = ∑1m*a*(*f'i*)/log2​(*i*\$11)
+ iDCG = ∑1m*a*(*fi*)/log2​(*i*\$11)

수량 DCG는 훈련 데이터상에서 고순위 속성인 특징이 라이브 데이터에서 특징 속성을 계산했을 때도 고순위에 속하는지 여부를 측정합니다. 수량 iDCG는 이상적인 점수를 측정하며, 이는 단순히 최종 수량이 항상 [0, 1] 범위 안에 들어가도록 만들기 위한 정규화 인수에 불과합니다.여기서 1은 가능한 최상의 값을 의미합니다.** NDCG 값이 1이라면 라이브 데이터의 특징 속성 순위가 훈련 데이터의 특징 속성 순위와 동일하다는 뜻입니다. 이 예제에서는 순위가 크게 바뀌었기 때문에, NDCG 값은 0.69가 되었습니다.

SageMaker Clarify에서는 NDCG 값이 0.90 미만이면 자동으로 경보를 발생시킵니다.

## 모델 모니터 예제 노트북
<a name="clarify-model-monitor-sample-notebooks-feature-drift"></a>

SageMaker Clarify는 실시간 엔드포인트에 대한 추론 데이터를 캡처하고, 변화하는 편향을 모니터링하기 위한 기준을 만들고, 결과를 검사하는 방법을 보여주는 다음과 같은 예제 노트북을 제공합니다.
+ [Monitoring bias drift and feature attribution drift Amazon SageMaker Clarify](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker_model_monitor/fairness_and_explainability/SageMaker-Model-Monitor-Fairness-and-Explainability.html) - Amazon SageMaker Model Monitor를 사용하여 시간 경과에 따른 바이어스 드리프트 및 특징 속성 드리프트를 모니터링합니다.

이 노트북은 SageMaker Studio에서만 실행이 검증되었습니다. SageMaker Studio에서 노트북을 여는 방법에 대한 지침이 필요한 경우, [Amazon SageMaker Studio Classic 노트북 만들기 또는 열기](notebooks-create-open.md)을 참조하세요. 커널을 선택하라는 메시지가 표시되면, **Python 3 (Data Science)**를 선택합니다. 다음 주제들에는 마지막 두 단계의 주요 내용과 예제 노트북에서 보았던 코드 예제가 포함되어 있습니다.

**Topics**
+ [모델 모니터 예제 노트북](#clarify-model-monitor-sample-notebooks-feature-drift)
+ [프로덕션 중인 모델을 위한 SHAP 기준 생성](clarify-model-monitor-shap-baseline.md)
+ [모델 특징 속성 드리프트 위반](clarify-model-monitor-model-attribution-drift-violations.md)
+ [어트리뷰션 드리프트를 모니터링하는 파라미터](clarify-config-json-monitor-model-explainability-parameters.md)
+ [특징 속성 드리프트 모니터링 작업 예약](clarify-model-monitor-feature-attribute-drift-schedule.md)
+ [프로덕션 모델의 특징 속성 드리프트에 대한 보고서 검사](clarify-feature-attribute-drift-report.md)
+ [특징 드리프트 분석을 위한 CloudWatch 지표](clarify-feature-attribute-drift-cw.md)

# 프로덕션 중인 모델을 위한 SHAP 기준 생성
<a name="clarify-model-monitor-shap-baseline"></a>

설명은 주로 대조적입니다.즉, 대부분 기준으로부터의 편차를 반영하는 내용입니다. 설명 가능성 기준에 대한 자세한 내용은 [설명 가능성에 대한 SHAP 기준](clarify-feature-attribute-shap-baselines.md)를 참조하세요.

SageMaker Clarify는 인스턴스별 추론에 대한 설명을 제공하는 것 외에도, 포함된 특징과 관련하여 모델 전체의 동작을 이해할 수 있도록 도와주는 ML 모델에 대한 전반적인 설명도 지원합니다. SageMaker Clarify는 여러 인스턴스의 Shapley 값을 집계하여 ML 모델에 대한 전반적인 설명을 생성합니다. SageMaker Clarify는 사용자가 기준을 정의하는 데 사용할 수 있는 다음과 같은 다양한 집계 방법을 지원합니다.
+ `mean_abs` - 모든 인스턴스에 대한 절대 SHAP 값의 평균입니다.
+ `median` - 모든 인스턴스에 대한 SHAP 값의 중앙값입니다.
+ `mean_sq` - 모든 인스턴스에 대한 제곱 SHAP 값의 평균입니다.

실시간 또는 배치 변환 추론 데이터를 캡처하도록 애플리케이션을 구성했다면, 특징 속성 드리프트의 모니터링을 위해 먼저 필요한 작업은 비교해볼 수 있는 기준을 생성하는 것입니다. 여기에는 데이터 입력 방식, 민감한 그룹 구분, 예측 캡처 방법, 해당 모델 및 훈련 후 편향 지표를 구성하는 작업이 포함됩니다. 그 다음에는 기준 설정 작업을 시작해야 합니다. 모델 설명 가능성 모니터는 이미 배포되어 추론을 생산하면서 특징 속성 드리프트를 정기적으로 감지하고 있는 모델이 수행한 예측을 설명할 수 있습니다.

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

이 예제에서 설명 가능성 기준 설정 작업은 테스트 데이터세트를 편향 기준 설정 작업과 공유하므로, 동일한 `DataConfig`가 사용되고 있으며, 둘 사이의 유일한 차이점은 작업 출력 URI입니다.

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

현재 SageMaker Clarify 설명자는 확장 가능하고 효율적인 SHAP 구현을 제공하므로, 설명 가능성 구성은 SHAPConfig이며, 여기에는 다음이 포함됩니다.
+ `baseline` - Kernel SHAP 알고리즘에서 기준 데이터세트로 사용할 행의 목록(하나 이상) 또는 S3 객체 URI입니다. 형식은 데이터 세트 형식과 동일해야 합니다. 각 행에는 특징 열/값만 포함되어야 하고 레이블 열/값은 생략되어야 합니다.
+ `num_samples` - Kernel SHAP 알고리즘에서 사용할 샘플의 수입니다. 이 숫자는 SHAP 값을 계산하기 위해 생성되는 합성 데이터 세트의 크기를 결정합니다.
+ agg\$1method - 글로벌 SHAP 값에 대한 집계 메서드입니다. 유효한 값은 다음과 같습니다.
  + `mean_abs` - 모든 인스턴스에 대한 절대 SHAP 값의 평균입니다.
  + `median` - 모든 인스턴스에 대한 SHAP 값의 중앙값입니다.
  + `mean_sq` - 모든 인스턴스에 대한 제곱 SHAP 값의 평균입니다.
+ `use_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>

특징 속성 드리프트 작업은 [기준 구성](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelExplainabilityJobDefinition.html#sagemaker-CreateModelExplainabilityJobDefinition-request-ModelExplainabilityBaselineConfig)에서 제공하는 기준 제약 조건을 현재의 `MonitoringExecution`에 대한 분석 결과와 비교하여 평가합니다. 이 작업은 위반이 감지되면 해당 위반을 실행 출력 위치에 있는 *constraint\$1violations.json* 파일에 나열하고, 실행 상태를 [결과 해석](model-monitor-interpreting-results.md)로 표시합니다.

특징 속성 드리프트 위반 파일의 스키마는 다음과 같습니다.
+ `label` - 레이블, 작업 분석 구성 `label_headers`또는 자리 표시자(예: `"label0"`)의 이름입니다.
+ `metric_name` - 설명 가능성 분석 메서드의 이름입니다. 현재 `shap`만 지원됩니다.
+ `constraint_check_type` - 모니터링되는 위반의 유형입니다. 현재 `feature_attribution_drift_check`만 지원됩니다.
+ `description` - 위반 내역에 대한 설명 메시지입니다.

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

모니터링 작업은 `explanations`섹션의 각 레이블을 대상으로 기준 제약 조건 파일 및 작업 분석 결과 파일(analysis.json)에 있는 해당 글로벌 SHAP 값의 [nDCG 점수](https://scikit-learn.org/stable/modules/generated/sklearn.metrics.ndcg_score.html)를 계산합니다.** 점수가 0.9점 미만이면 위반이 기록됩니다. 결합된 글로벌 SHAP 값이 평가되는 것이므로, 위반 항목에는 `“feature”`필드가 없습니다. 다음 출력은 기록된 여러 위반의 예시를 제공합니다.

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

# 어트리뷰션 드리프트를 모니터링하는 파라미터
<a name="clarify-config-json-monitor-model-explainability-parameters"></a>

Amazon SageMaker Clarify 설명 가능성 모니터는 [분석 구성 파일](clarify-processing-job-configure-analysis.md)의 분석 구성에서 사용된 매개변수의 하위 집합을 재사용합니다. 다음 매개변수가 반드시 JSON 파일로 제공되어야 하고, 해당 경로는 반드시 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelExplainabilityAppSpecification](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ModelExplainabilityAppSpecification)의 `ConfigUri`매개변수에 제공되어야 합니다.
+ `"version"` - (선택사항) 해당 구성 파일의 스키마 버전입니다. 제공하지 않을 경우, 지원 가능한 최신 버전이 사용됩니다.
+ `"headers"` - (선택사항) 데이터세트의 특징 이름 목록. 설명 가능성 분석에는 레이블이 필요하지 않습니다.
+ `"methods"` - 분석 및 보고를 위한 메서드 및 관련 매개변수의 목록입니다. 생략된 섹션이 있는 경우, 해당 섹션은 계산되지 않습니다.
  + `"shap"` - (선택사항) SHAP 값 계산에 관한 섹션입니다.
    + `"baseline"` - (선택사항) 행의 목록(하나 이상)이거나, 또는 Amazon Simple Storage Service Amazon S3 객체 URI입니다. Kernel SHAP 알고리즘에서 기준 데이터세트(백그라운드 데이터세트라고도 함)로 사용됩니다. 형식은 데이터세트 형식과 동일해야 합니다. 각 행에는 해당 특징 열(또는 값)만 포함되어 있어야 합니다. 각 행을 모델로 보내기 전에 제외되어야 하는 열을 먼저 모두 제외하세요.
    + `"num_samples"` - Kernel SHAP 알고리즘에서 사용할 샘플의 수입니다. 이 숫자는 SHAP 값을 계산하기 위해 생성되는 합성 데이터세트의 크기를 결정합니다. 제공하지 않을 경우, SageMaker Clarify 작업은 특징의 개수를 기반으로 값을 선택합니다.
    + `"agg_method"` - 글로벌 SHAP 값에 대한 집계 메서드입니다. 유효한 값은 다음과 같습니다.
      + `"mean_abs"` - 모든 인스턴스에 대한 절대 SHAP 값의 평균입니다.
      + `"median"` - 모든 인스턴스에 대한 SHAP 값의 중앙값입니다.
      + `"mean_sq"` - 모든 인스턴스에 대한 제곱 SHAP 값의 평균입니다.
    + `"use_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"` - (선택사항) 섀도우 엔드포인트를 통해 추론을 가져오는 데 사용되는 모델 입력 형식입니다. 유효한 값은 CSV인 경우 `"text/csv"`, JSON Lines인 경우 `"application/jsonlines"`, Apache Parquet인 경우 `application/x-parquet`, 그리고 컴퓨터 비전 설명 가능성을 활성화하려면 `application/x-image`입니다. 기본값은 `dataset_type`형식과 동일합니다.
  + `"accept_type"` - (선택사항) 섀도우 엔드포인트를 통해 추론을 가져오는 데 사용되는 모델 출력 형식입니다.** 유효한 값은 `"text/csv"`인 경우 CSV, JSON Lines인 경우 `"application/jsonlines"`입니다. 제외할 경우, SageMaker Clarify 함수는 캡처된 데이터의 응답 데이터 유형을 사용합니다.
  + `"content_template"` - (선택사항) 데이터세트 인스턴스에서 모델 입력을 구성하는 데 사용되는 템플릿 문자열입니다. `"content_type"`이 `"application/jsonlines"`인 경우에만 사용됩니다. 템플릿에는 자리 표시자가 `$features`하나만 있어야 하며, 이는 런타임 시 특징 목록으로 대체됩니다. 예를 들어 `"content_template":"{\"myfeatures\":$features}"`에서, 만약 인스턴스(레이블 없음)가 `1,2,3`이라면, 모델 입력은 JSON Lines `'{"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 Lines인 경우 해당 특징 열을 찾는 데 사용되는 것은 JMEsPath입니다.
+ `ProbabilityAttribute` - 확률을 계산하는 모델 출력의 인덱스 또는 JMEsPath 위치입니다. 예를 들어, 모델 출력이 레이블 및 확률 목록을 포함하는 JSON Lines인 경우라면, 최대 확률에 해당하는 레이블이 편향 계산 용도로 선택됩니다.

## CSV 및 JSON Lines 데이터세트를 위한 JSON 구성 파일의 예제
<a name="clarify-config-json-monitor-model-explainability-parameters-examples"></a>

다음은 CSV 및 JSON Lines 데이터세트를 구성하여 특징 속성 드리프트를 모니터링하기 위해 사용하는 JSON 파일의 예제입니다.

**Topics**
+ [CSV 데이터세트](#clarify-config-json-monitor-model-explainability-parameters-example-csv)
+ [JSON Lines 데이터세트](#clarify-config-json-monitor-model-explainability-parameters-example-jsonlines)

### CSV 데이터세트
<a name="clarify-config-json-monitor-model-explainability-parameters-example-csv"></a>

다음 예제와 같이 3개의 숫자형 특징 열이 있는 데이터세트를 생각해보겠습니다.

```
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"`매개변수에 의해 선택되었습니다. 0 기준으로 시작하는 번호 매기기가 사용되므로, 여기서 1은 모델 출력의 두 번째 열을 나타냅니다.

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

### JSON Lines 데이터세트
<a name="clarify-config-json-monitor-model-explainability-parameters-example-jsonlines"></a>

다음 예제와 같이 특징 열 4개와 레이블 열 1개가 있는 데이터세트에서 첫 번째 특징과 레이블이 이진수라고 가정해 보겠습니다.

```
{"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 Line입니다.

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

다음 예제에서, JSON 구성 파일은 이 JSON Lines 데이터세트를 구성할 수 있는 방법을 보여줍니다.

```
{
    "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()`메서드를 호출하여 시간별 모델 설명 가능성 모니터를 예약할 수 있습니다. 다음 섹션은 실시간 엔드포인트에 배포된 모델 및 배치 변환 작업에 사용할 모델 설명 가능성 모니터를 생성하는 방법을 보여줍니다.

**중요**  
모니터링 일정을 생성할 때는 배치 변환 입력이나 엔드포인트 입력 중에서 하나를 지정할 수 있지만, 둘 다 지정할 수는 없습니다.

기준 설정 작업이 이미 제출된 경우, 모니터는 기준 설정 작업으로부터 분석 구성을 자동으로 반영합니다. 다만, 사용자가 기준 설정 단계를 건너뛰거나 해당 캡처 데이터세트의 특성이 훈련 데이터세트의 특성과 다른 경우에는, 분석 구성을 사용자가 제공해야 합니다. `ModelConfig`는 기준 설정 작업에서 필요한 것과 같은 이유로 `ExplainabilityAnalysisConfig`에서 요구됩니다. 특징 속성을 계산하는 데에는 특징만 필요하므로, Ground Truth 레이블 지정은 제외해야 합니다.

## 실시간 엔드포인트에 배포된 모델에 대한 특징 속성 드리프트 모니터링
<a name="model-monitor-explain-quality-rt"></a>

실시간 엔드포인트에 대한 모델 설명 가능성 모니터를 예약하려면, 다음 코드 샘플에 나와 있는 것처럼 `EndpointInput`인스턴스를 `ModelExplainabilityMonitor`인스턴스의 `endpoint_input`인수로 전달하세요.

```
from sagemaker.model_monitor import CronExpressionGenerator

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

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

## 배치 변환 작업에 대한 특징 속성 드리프트 모니터링
<a name="model-monitor-explain-quality-bt"></a>

배치 변환 작업에 대한 모델 설명 가능성 모니터를 예약하려면, 다음 코드 샘플에 나와 있는 것처럼 `BatchTransformInput`인스턴스를 `ModelExplainabilityMonitor`인스턴스의 `batch_transform_input`인수로 전달하세요.

```
from sagemaker.model_monitor import CronExpressionGenerator

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

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

# 프로덕션 모델의 특징 속성 드리프트에 대한 보고서 검사
<a name="clarify-feature-attribute-drift-report"></a>

사용자가 예약한 일정이 기본 설정에 따라 시작된 후에는, 먼저 첫 번째 실행이 시작될 때까지 기다린 다음에 해당 일정을 중지해야 요금이 발생하지 않습니다.

보고서를 검사하려면 다음 코드를 사용하세요.

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

 기준과 비교 시 위반 항목이 있는 경우, 다음과 같이 나열됩니다.

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

모델이 실시간 엔드포인트에 배포되어 있다면, SageMaker Studio에서 **엔드포인트** 탭을 선택한 다음 해당 엔드포인트를 두 번 클릭하여 분석 결과 및 CloudWatch 지표의 시각화를 확인할 수 있습니다.

# 특징 드리프트 분석을 위한 CloudWatch 지표
<a name="clarify-feature-attribute-drift-cw"></a>

이 가이드는 SageMaker Clalify에서 특징 속성 드리프트 분석을 위해 사용할 수 있는 CloudWatch 지표와 관련 속성을 보여줍니다. 특징 속성 드리프트 모니터링 작업은 다음 두 가지 유형의 지표를 계산하고 게시합니다.
+ 각 특징의 글로벌 SHAP 값.
**참고**  
이 지표의 이름은 작업 분석 구성에서 제공하는 특징 이름을 `feature_`에 추가합니다. 예를 들어 `feature_X`는 특징 `X`의 글로벌 SHAP 값입니다.
+ 지표의 `ExpectedValue`.

이러한 지표는 다음 CloudWatch 네임스페이스에 게시됩니다.
+ 실시간 엔드포인트인 경우: `aws/sagemaker/Endpoints/explainability-metrics`
+ 배치 변환 작업인 경우: `aws/sagemaker/ModelMonitoring/explainability-metrics`

각 지표에는 다음 속성이 있습니다.
+ `Endpoint`: 해당 시, 모니터링되는 엔드포인트의 이름입니다.
+ `MonitoringSchedule`: 모니터링 작업을 위한 일정의 이름입니다.
+ `ExplainabilityMethod`: Shapley 값을 계산하는 데 사용되는 메서드입니다. `KernelShap`를 선택합니다.
+ `Label`: 작업 분석 구성 `label_headers`또는 자리 표시자(예: `label0`)에서 제공하는 이름입니다.
+ `ValueType`: 지표에서 반환되는 값의 유형입니다. [`GlobalShapValues`] 또는 [`ExpectedValue`]을 선택합니다.

모니터링 작업이 지표를 게시하지 않도록 하려면, [모델 설명 가능성 작업](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelExplainabilityJobDefinition.html) 정의의 `Environment`맵에서 `publish_cloudwatch_metrics`를 `Disabled`로 설정합니다.

# 모니터링 작업 일정 예약
<a name="model-monitor-scheduling"></a>

Amazon SageMaker Model Monitor는 실시간 엔드포인트에서 수집된 데이터를 모니터링할 수 있는 기능을 제공합니다. 반복되는 일정에 따라 데이터를 모니터링하거나 일회성으로 즉시 모니터링할 수 있습니다. [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateMonitoringSchedule.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateMonitoringSchedule.html) API를 사용하여 모니터링 일정을 만들 수 있습니다.

SageMaker AI는 모니터링 일정을 통해 작업 처리를 시작하여 지정된 기간 동안 수집되었던 데이터를 분석할 수 있습니다. 처리 작업에서 SageMaker AI는 현재 분석에 대한 데이터세트를 사용자가 제공하는 기준 통계 및 제약 조건과 비교합니다. 그런 다음 SageMaker AI는 위반 보고서를 생성합니다. 또한 분석 중인 각 기능에 대해 CloudWatch 지표를 내보냅니다.

SageMaker AI는 테이블 형식 데이터세트에 대한 분석을 수행하기 위한 사전 구축된 컨테이너를 제공합니다. 아니면 [Amazon SageMaker Model Monitor에서 자체 컨테이너 지원](model-monitor-byoc-containers.md)항목에 설명된 대로 자체 컨테이너를 사용하는 방법을 선택할 수도 있습니다.

실시간 엔드포인트 또는 배치 변환 작업에 대한 모델 모니터링 일정을 생성할 수 있습니다. 기준 리소스(제약 조건 및 통계)를 사용하여 실시간 트래픽 또는 배치 작업 입력과 비교합니다.

**Example 기준 할당**  
다음 예제에서는 모델 훈련에 사용된 훈련 데이터세트가 Amazon S3에 업로드되었습니다. Amazon S3에 이미 데이터를 보유 중인 경우에는, 이를 직접 가리킬 수 있습니다.  

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

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

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

**Example 반복 분석 일정**  
실시간 엔드포인트에 대한 모델 모니터를 예약하려는 경우, 기준 제약 조건 및 통계를 사용하여 실시간 트래픽과 비교합니다. 다음 코드 조각은 실시간 엔드포인트에 대한 모델 모니터를 예약하는 데 사용되는 일반적인 형식을 보여줍니다. 이 예제에서는 모델 모니터가 매시간 실행되도록 예약합니다.  

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

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

**Example 일회성 분석 일정**  
다음과 같은 인수를 `create_monitoring_schedule`메서드에 전달하여 분석이 반복 없이 한 번만 실행되도록 예약할 수도 있습니다.  

```
    schedule_cron_expression=CronExpressionGenerator.now(),
    data_analysis_start_time="-PT1H",
    data_analysis_end_time="-PT0H",
```
이러한 인수에서 `schedule_cron_expression`매개변수는 `CronExpressionGenerator.now()`값을 사용하여 한 번의 분석을 즉시 실행하도록 예약합니다. 이 설정을 사용하는 모든 일정에는 `data_analysis_start_time`및 `data_analysis_end_time`매개변수가 필요합니다. 이러한 매개변수는 분석 기간의 시작 시간과 종료 시간을 설정합니다. 이러한 시간을 현재 시간을 기준으로 한 오프셋으로 정의하고, ISO8601 기간 형식을 사용하세요. 이 예제에서 시간값 `-PT1H`및 `-PT0H`는 1시간 전의 과거와 현재 시간 사이의 기간을 정의합니다. 이 일정을 사용하면, 분석은 지정된 해당 기간 동안에 수집된 데이터만을 평가합니다.

**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']))
```

# 모니터링 일정에 대한 크론 표현식
<a name="model-monitor-schedule-expression"></a>

모니터링 일정에 대한 세부 정보를 제공하려면 모니터링 일정에 대한 세부 정보를 설명하는 `cron`표현식인 [https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ScheduleConfig.html](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_ScheduleConfig.html)을 사용합니다.

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시간마다 실행을 지원하기 위해 Model Monitor는 다음 표현식을 지원합니다.

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

예를 들어 다음은 유효한 `cron`표현식입니다.
+ 오후 5시(UTC)부터 12시간마다: `cron(0 17/12 ? * * *)`
+ 오전 12시(UTC)부터 2시간마다: `cron(0 0/2 ? * * *)`

**참고**  
`cron` 표현식이 오후 5시(UTC)에 시작하도록 설정되어 있지만 실제 실행이 요청된 시간으로부터 0-20분의 지연이 발생할 수 있습니다.
일일 일정에 따라 실행하려는 경우에는 이 파라미터를 제공하지 마세요. SageMaker AI는 매일 실행할 시간을 선택합니다.
현재 SageMaker AI에서는 1\$124시간 사이의 시간당 정수 비율만 지원합니다.

# 모니터링 일정을 위한 서비스 제어 정책 구성
<a name="model-monitor-scp-rules"></a>

 [CreateMonitoringSchedule](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateMonitoringSchedule.html) API 또는 [UpdateMonitoringSchedule](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_UpdateMonitoringSchedule.html) API를 사용하여 모니터링 작업 일정을 만들거나 업데이트할 때는 각각의 모니터링 작업의 매개변수를 지정해야 합니다. 사용 사례에 따라 다음 중 한 가지 방법으로 이를 수행할 수 있습니다.
+  `CreateMonitoringSchedule` 또는 `UpdateMonitoringSchedule`을 호출할 때 [MonitoringScheduleConfig](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_MonitoringScheduleConfig.html)의 [MonitoringJobDefinition](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_MonitoringJobDefinition.html) 필드를 지정할 수 있습니다. 이 옵션은 데이터 품질 모니터링 작업의 일정을 만들거나 업데이트하는 데만 사용 가능합니다.
+  `CreateMonitoringSchedule` 또는 `UpdateMonitoringSchedule`을 호출할 때 사용자가 `MonitoringScheduleConfig`의 `MonitoringJobDefinitionName`필드에 이미 생성해둔 모니터링 작업 정의의 이름을 지정할 수 있습니다. 다음 API 중 하나를 사용하여 생성하는 모든 작업 정의에 이 방법을 사용할 수 있습니다.
  +  [CreateDataQualityJobDefinition](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateDataQualityJobDefinition.html) 
  +  [CreateModelQualityJobDefinition](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelQualityJobDefinition.html) 
  +  [CreateModelBiasJobDefinition](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelBiasJobDefinition.html) 
  +  [CreateModelExplainabilityJobDefinition](https://docs.aws.amazon.com/sagemaker/latest/APIReference/API_CreateModelExplainabilityJobDefinition.html) 

   SageMaker Python SDK를 사용하여 일정을 만들거나 업데이트하려면 이 프로세스를 필수적으로 사용해야 합니다.

 앞서 언급한 프로세스는 상호 배타적입니다.즉, 사용자는 모니터링 일정을 생성하거나 업데이트할 때 `MonitoringJobDefinition`필드 아니면 `MonitoringJobDefinitionName`필드를 지정할 수 있습니다.

 모니터링 작업 정의를 생성하거나 `MonitoringJobDefinition`필드에 정의를 지정할 때는 `NetworkConfig`및 `VolumeKmsKeyId`와 같은 보안 매개변수를 설정할 수 있습니다. 관리자는 모니터링 작업이 항상 안전한 환경에서 실행될 수 있도록 이러한 매개변수를 항상 특정한 값으로 설정해두는 것이 좋습니다. 이를 보장하려면 적절한 [서비스 제어 정책](https://docs.aws.amazon.com/organizations/latest/userguide/orgs_manage_policies_scps.html)(SCP)을 설정하세요. 서비스 제어 정책(SCP)은 조직의 권한을 관리하는 데 사용할 수 있는 조직 정책의 유형입니다.

 다음 예제는 모니터링 작업 일정을 만들거나 업데이트할 때 인프라 매개변수가 제대로 설정되었는지 여부를 확인하는 데 사용할 수 있는 SCP를 보여줍니다.

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

****  

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

------

 예제의 처음 두 규칙은 모니터링 작업 정의를 위한 보안 매개변수가 항상 설정되어 있도록 보장합니다. 마지막 규칙은 일정을 만들거나 업데이트하는 조직 내 모든 사용자가 항상 `MonitoringJobDefinitionName`필드를 지정하도록 요구합니다. 이렇게 하면 조직 내부의 누군가가 일정을 만들거나 업데이트할 때 `MonitoringJobDefinition`필드를 지정함으로써 보안 매개변수에 대해 안전하지 않은 값을 설정하는 일이 생기지 않게 됩니다.

# Amazon SageMaker Model Monitor 사전 구축 컨테이너
<a name="model-monitor-pre-built-container"></a>

SageMaker AI는 제약 조건 제안, 통계 생성, 기준과 비교한 제약 조건 검증, Amazon CloudWatch 지표 내보내기 등 다양한 모델 모니터링 기능을 제공하는 `sagemaker-model-monitor-analyzer`라는 사전 구축된 이미지를 제공합니다. 이 이미지는 Spark 버전 3.3.0을 기반으로 하며 [Deequ](https://github.com/awslabs/deequ) 버전 2.0.2를 사용하여 구축되었습니다.

**참고**  
내장된 `sagemaker-model-monitor-analyzer`이미지를 직접 가져올 수는 없습니다. SDK 중 하나를 사용하여 기준 처리 또는 모니터링 작업을 제출할 때 `sagemaker-model-monitor-analyzer` 이미지를 사용할 수 있습니다. AWS SDKs

 SageMaker Python SDK([SageMaker AI Python SDK 참조 가이드](https://sagemaker.readthedocs.io/en/stable/api/utility/image_uris.html)의 `image_uris.retrieve` 참조)를 사용하여 ECR 이미지 URI를 자동으로 생성하거나, ECR 이미지 URI를 직접 지정합니다. SageMaker Model Monitor에 대한 사전 구축된 이미지는 다음과 같이 액세스 할 수 있습니다.

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

예: `159807026194.dkr.ecr.us-west-2.amazonaws.com/sagemaker-model-monitor-analyzer`

중국의 AWS 리전에 있는 경우 SageMaker Model Monitor용 사전 빌드된 이미지에 다음과 같이 액세스할 수 있습니다.

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

계정 IDs 및 AWS 리전 이름은 [Docker 레지스트리 경로 및 예제 코드를 참조하세요](https://docs.aws.amazon.com/sagemaker/latest/dg-ecr-paths/sagemaker-algo-docker-registry-paths).

자체 분석 컨테이너를 작성하는 방법은 [사용자 지정 모니터링 일정](model-monitor-custom-monitoring-schedules.md)에 설명된 컨테이너 계약을 참조하세요.

# 결과 해석
<a name="model-monitor-interpreting-results"></a>

기준 처리 작업을 실행하여 데이터세트에 대한 통계 및 제약 조건을 얻은 후에는 통계를 계산하고 기준 제약 조건과 관련해 발생한 위반을 나열하는 모니터링 작업을 실행할 수 있습니다. Amazon CloudWatch 지표는 기본적으로 사용자 계정에서도 보고됩니다. Amazon SageMaker Studio에서 모니터링 결과를 보는 방법에 대한 자세한 내용은 [Amazon SageMaker Studio에서 실시간 엔드포인트의 결과 시각화](model-monitor-interpreting-visualize-results.md)섹션을 참조하세요.

## 실행 나열
<a name="model-monitor-interpreting-results-list-executions"></a>

지정된 간격으로 일정이 모니터링 작업을 시작합니다. 다음 코드는 가장 최근의 5개 실행을 나열합니다. 시간별 일정을 생성한 후에 이 코드를 실행하는 경우, 실행이 비어 있을 수 있으며 시간 경계(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_constaints` 및 `baseline_statistics`경로에 지정된 기준 통계 및 제약 조건 파일과 비교하여 현재 데이터세트에서 발견된 위반 목록을 포함합니다.  | 

[Amazon SageMaker Model Monitor 사전 구축 컨테이너](model-monitor-pre-built-container.md)는 기본적으로 각 특징에 대한 Amazon CloudWatch 지표의 집합을 저장합니다.

컨테이너 코드는 이 위치(`/opt/ml/output/metrics/cloudwatch`)에 CloudWatch 지표를 내보낼 수 있습니다.

# Amazon SageMaker Studio에서 실시간 엔드포인트의 결과 시각화
<a name="model-monitor-interpreting-visualize-results"></a>

실시간 엔드포인트를 모니터링하는 경우, Amazon SageMaker Studio에서도 결과를 시각화할 수 있습니다. 모니터링 작업 실행의 세부 정보를 볼 수 있으며, 모니터링 작업에서 계산되는 모든 지표에 대한 기준 및 캡처된 값을 보여주는 차트를 생성하는 것도 가능합니다.

**모니터링 작업의 세부 결과를 보려면**

1. Studio에 로그인합니다. 자세한 내용은 [Amazon SageMaker AI 도메인 개요](gs-studio-onboard.md) 단원을 참조하십시오.

1. 왼쪽 탐색 창에서 **구성 요소 및 레지스트리** 아이콘(![\[Orange paper airplane icon representing email or message sending functionality.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/icons/Components_registries.png))을 선택합니다.

1. 드롭다운 메뉴에서 **엔드포인트**를 선택합니다.  
![\[콘솔에서 엔드포인트 드롭다운 메뉴의 위치입니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/model_monitor/mm-studio-endpoints.png)

1. 엔드포인트 탭에서 작업 세부 정보를 확인하고자 하는 모니터링 유형을 선택합니다.  
![\[모델 모니터링 섹션에서 모델 품질 탭의 위치입니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/model_monitor/mm-studio-model-quality.png)

1. 모니터링 작업의 목록에서 세부 정보를 보려는 모니터링 작업 실행의 이름을 선택합니다.  
![\[모델 모니터링 섹션에서 모델 품질 탭입니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/model_monitor/mm-studio-job-history.png)

1. **모니터링 작업 세부 정보** 탭이 열리면서 모니터링 작업의 세부 정보가 표시됩니다.  
![\[작업 세부 정보 모니터링 탭입니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/model_monitor/mm-studio-job-details.png)

일정 기간 동안의 기준 지표와 캡처된 지표를 표시하는 차트를 만들 수 있습니다.

**SageMaker Studio에서 차트를 생성하여 모니터링 결과를 시각화하려면**

1. Studio에 로그인합니다. 자세한 내용은 [Amazon SageMaker AI 도메인 개요](gs-studio-onboard.md) 단원을 참조하십시오.

1. 왼쪽 탐색 창에서 **구성 요소 및 레지스트리** 아이콘(![\[Orange paper airplane icon representing email or message sending functionality.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/icons/Components_registries.png))을 선택합니다.

1. 드롭다운 메뉴에서 **엔드포인트**를 선택합니다.  
![\[콘솔에서 엔드포인트 드롭다운 메뉴의 위치입니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/model_monitor/mm-studio-endpoints.png)

1. **엔드포인트** 탭에서 차트를 만들고자 하는 대상 모니터링 유형을 선택합니다. 이 예제는 **모델 품질** 모니터링 유형에 대한 차트를 보여주고 있습니다.  
![\[모델 모니터링 섹션에서 모델 품질 탭의 위치입니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/model_monitor/mm-studio-model-quality.png)

1. **차트 추가**를 선택합니다.  
![\[콘솔에서 차트 추가의 위치입니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/model_monitor/mm-studio-add-chart.png)

1. **차트 속성** 탭에서 차트로 만들고자 하는 기간, 통계, 지표를 선택합니다. 이 예제는 **1주일**의 **타임라인**에 대한, **평균** **통계**로,** F1** **지표**에 대한 차트를 보여주고 있습니다.  
![\[콘솔에서 지표를 선택하는 위치입니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/model_monitor/mm-studio-chart-properties.png)

1. 사용자가 이전 단계에서 선택한 기준 및 현재 지표 통계를 보여주는 차트가 **엔드포인트** 탭에 표시됩니다.  
![\[이전 단계에서 선택한 기준 및 현재 평균 지표를 보여주는 예시 차트입니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/model_monitor/mm-studio-f1-chart.png)

# 고급 주제
<a name="model-monitor-advanced-topics"></a>

다음 섹션에는 사전 처리 및 사후 처리 스크립트를 사용하여 모니터링을 사용자 지정하는 방법, 자체 컨테이너를 빌드하는 방법,를 사용하여 모니터링 일정을 생성하는 방법을 설명하는 고급 작업이 포함되어 CloudFormation 있습니다.

**Topics**
+ [사용자 지정 모니터링 일정](model-monitor-custom-monitoring-schedules.md)
+ [CloudFormation 사용자 지정 리소스를 사용하여 실시간 엔드포인트에 대한 모니터링 일정 생성](model-monitor-cloudformation-monitoring-schedules.md)

# 사용자 지정 모니터링 일정
<a name="model-monitor-custom-monitoring-schedules"></a>

기본 제공 모니터링 메커니즘을 사용하는 것 외에도 사전 처리 및 사후 처리 스크립트를 사용하거나 자체 컨테이너를 사용하거나 빌드하여 자체 모니터링 일정과 절차를 생성할 수 있습니다.

**Topics**
+ [사전 처리 및 사후 처리](model-monitor-pre-and-post-processing.md)
+ [Amazon SageMaker Model Monitor에서 자체 컨테이너 지원](model-monitor-byoc-containers.md)

# 사전 처리 및 사후 처리
<a name="model-monitor-pre-and-post-processing"></a>

사용자 지정 사전 처리 및 사후 처리 Python 스크립트를 사용하여 모델 모니터에 대한 입력을 변환하거나 모니터링이 성공적으로 실행된 후 코드를 확장할 수 있습니다. 이 스크립트를 Amazon S3에 업로드한 다음 작업할 모델 모니터를 생성할 때 이를 참조하세요.

다음 예제는 사전 처리 스크립트와 사후 처리 스크립트를 사용하여 모니터링 일정을 사용자 지정하는 방법을 보여줍니다. *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>

모델 모니터에 대한 입력을 변환해야 하는 경우 사전 처리 스크립트를 사용하세요.

예를 들어, 모델의 출력이 `[1.0, 2.1]`배열이라고 가정해 보겠습니다. Amazon SageMaker Model Monitor 컨테이너는 `{“prediction0”: 1.0, “prediction1” : 2.1}`와 같은 형태로 테이블 형식 또는 평면화된 JSON 구조에서만 작동합니다. 해당 배열은 다음과 같은 사전 처리 스크립트를 사용하여 올바른 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에 기록된 예외 메시지를 확인하여 디버깅하세요. 사용자는 `preprocess_handler`인터페이스를 통해 CloudWatch의 로거에 액세스할 수 있습니다. 해당 스크립트에서 필요한 모든 정보를 CloudWatch에 기록할 수 있습니다. 이는 사전 처리 스크립트를 디버깅할 때 유용할 수 있습니다. 다음 예제는 CloudWatch로 기록하기 위해 `preprocess_handler`인터페이스를 사용하는 방법을 보여줍니다.

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

## 사후 처리 스크립트
<a name="model-monitor-post-processing-script"></a>

모니터링을 성공적으로 실행한 후 코드를 확장하려면 사후 처리 스크립트를 사용하세요.

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

# Amazon SageMaker Model Monitor에서 자체 컨테이너 지원
<a name="model-monitor-byoc-containers"></a>

Amazon SageMaker Model Monitor는 테이블 형식 데이터세트에 대해 엔드포인트 또는 배치 변환 작업에서 캡처한 데이터를 분석할 수 있는 사전 구축된 컨테이너를 제공합니다. 사용자의 자체 컨테이너를 사용하고자 하는 경우, 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에서도 작동할 수 있게 하려면, 동일한 형식을 따라야 합니다. 완전히 사용자 지정된 보고서를 내보내는 방법을 선택할 수도 있습니다.

또한 [BYOC(Bring Your Own Container)에 대한 CloudWatch 지표](model-monitor-byoc-cloudwatch.md)의 지침에 따라 컨테이너에서 CloudWatch 지표를 내보낼 수도 있습니다.

**Topics**
+ [컨테이너 계약 입력](model-monitor-byoc-contract-inputs.md)
+ [컨테이너 계약 출력](model-monitor-byoc-contract-outputs.md)
+ [BYOC(Bring Your Own Container)에 대한 CloudWatch 지표](model-monitor-byoc-cloudwatch.md)

# 컨테이너 계약 입력
<a name="model-monitor-byoc-contract-inputs"></a>

Amazon SageMaker Model Monitor 플랫폼은 지정된 일정에 따라 사용자의 컨테이너 코드를 호출합니다. 사용자가 자체 컨테이너 코드를 작성하기로 선택한 경우, 다음 환경 변수를 사용할 수 있습니다. 이러한 컨텍스트에서, 사용자는 현재 데이터세트를 분석하거나, 또는 (해당 시) 지표를 내보내기로 선택한 경우 제약 조건을 평가할 수 있습니다.

`dataset_format` 변수를 제외하고, 실시간 엔드포인트 및 배치 변환 작업에 사용할 수 있는 환경 변수는 동일하게 제공됩니다. 사용자가 실시간 엔드포인트를 사용하는 경우, `dataset_format`변수는 다음 옵션을 지원합니다.

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

사용자가 배치 변환 작업을 사용하는 경우, `dataset_format`은 다음 옵션을 지원합니다.

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

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

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

다음 코드 샘플은 사용자가 컨테이너 코드에 사용할 수 있고 실시간 엔드포인트에 대해 `dataset_format`형식을 사용하는 모든 환경 변수의 세트를 보여줍니다.

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

파라미터 


| 파라미터 이름 | 설명 | 
| --- | --- | 
| 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`로 이 파라미터를 지정합니다. `S3Uri`에 지정된 `MonitoringOutputConfig.MonitoringOutput[0].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`매개변수에 지정되어 있는 접두사입니다. 컨테이너는 `dataset_source` 경로에서 SageMaker AI가 이미 다운로드 한 것보다 더 많은 양의 데이터에 직접 액세스해야 하는 경우에 이를 사용할 수 있습니다.  | 
| 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*.`의 경로에 대한 보고서를 작성할 수 있습니다.컨테이너 코드는 사용자의 필요에 맞는 보고서를 작성할 수 있습니다.

사용자가 다음 구조 및 계약을 사용하는 경우, 특정 출력 파일은 시각화와 API에서 SageMaker AI에 의해 특별히 처리됩니다. 이는 테이블 형식 데이터세트에만 적용됩니다.

테이블 형식 데이터세트의 출력 파일


| 파일 이름 | 설명 | 
| --- | --- | 
| statistics.json |  이 파일에는 분석되는 데이터세트의 각 기능에 대한 열 기반 통계가 있어야 합니다. 이 파일에 대한 스키마는 다음 섹션에서 사용할 수 있습니다.  | 
| constraints.json |  이 파일에는 관찰된 기능에 대한 제약 조건이 있어야 합니다. 이 파일에 대한 스키마는 다음 섹션에서 사용할 수 있습니다.  | 
| constraints\$1violations.json |  이 파일에는 `baseline_constaints`및 `baseline_statistics`경로에 지정된 기준 통계 및 제약 조건 파일과 비교하여 현재 데이터세트에서 발견된 위반 목록이 있어야 합니다.  | 

또한 `publish_cloudwatch_metrics`값이 `"Enabled"`인 경우, 컨테이너 코드는 이 위치(`/opt/ml/output/metrics/cloudwatch`)에서 Amazon 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)에서 사용할 버킷을 구성합니다.KLL은 압축 체계가 느슨한 매우 컴팩트한 분위 스케치입니다.

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

**참고**  
지정된 지표는 이후 시각화 변경 시 SageMaker AI에서 인식됩니다. 필요한 경우 컨테이너는 더 많은 지표를 내보낼 수 있습니다.
[KLL 스케치](https://datasketches.apache.org/docs/KLL/KLLSketch.html)는 인식된 스케치입니다. 사용자 지정 컨테이너는 자체 표현을 작성할 수 있지만, 시각화 시 SageMaker AI에서 인식되지는 않습니다.
기본적으로 배포는 10개의 버킷으로 분포를 구체화됩니다. 이 값은 변경할 수 없습니다.

# 제약 조건에 대한 스키마(constraints.json 파일)
<a name="model-monitor-byoc-constraints"></a>

constraints.json 파일은 데이터세트가 반드시 충족해야 하는 제약 조건을 표현하는 데 사용됩니다. Amazon SageMaker Model Monitor 컨테이너는 constraints.json 파일을 사용하여 데이터세트를 평가할 수 있습니다. 사전 구축된 컨테이너는 기준 데이터세트에 대한 constraints.json 파일을 자동으로 생성해주는 기능을 제공합니다. 자체 컨테이너를 사용하는 경우, 비슷한 기능을 제공하거나 기타 몇 가지 방법으로 containints.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/ko_kr/sagemaker/latest/dg/model-monitor-byoc-constraints.html)

# BYOC(Bring Your Own Container)에 대한 CloudWatch 지표
<a name="model-monitor-byoc-cloudwatch"></a>

`publish_cloudwatch_metrics` 값이 `/opt/ml/processing/processingjobconfig.json`파일의 `Environment`맵에 있는 `Enabled`인 경우, 컨테이너 코드는 `/opt/ml/output/metrics/cloudwatch`위치에 Amazon CloudWatch 지표를 내보냅니다.

이 파일의 스키마는 `PutMetrics`API에 밀접한 기반을 두고 있습니다. 네임스페이스는 여기에서 지정되지 않았습니다. 기본값은 다음과 같습니다.
+ `For real-time endpoints: /aws/sagemaker/Endpoint/data-metrics`
+ `For batch transform jobs: /aws/sagemaker/ModelMonitoring/data-metrics`

그러나 차원을 지정할 수 있습니다. 최소한 다음 차원을 추가하는 것이 좋습니다.
+ 실시간 엔드포인트인 경우 `Endpoint`및 `MonitoringSchedule`
+ 배치 변환 작업인 경우 `MonitoringSchedule`

다음 JSON 코드 조각은 차원을 설정하는 방법을 보여줍니다.

실시간 엔드포인트인 경우, `Endpoint`및 `MonitoringSchedule`차원이 포함된 다음 JSON 코드 조각을 참조하세요.

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

배치 변환 작업인 경우, `MonitoringSchedule`차원이 포함된 다음 JSON 코드 조각을 참조하세요.

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

# CloudFormation 사용자 지정 리소스를 사용하여 실시간 엔드포인트에 대한 모니터링 일정 생성
<a name="model-monitor-cloudformation-monitoring-schedules"></a>

실시간 엔드포인트를 사용하는 경우 CloudFormation 사용자 지정 리소스를 사용하여 모니터링 일정을 생성할 수 있습니다. 사용자 지정 리소스는 Python에 있습니다. 배포 방법은 [Python Lambda 배포](https://docs.aws.amazon.com/lambda/latest/dg/lambda-python-how-to-create-deployment-package.html)를 참조하세요.

## 사용자 지정 리소스
<a name="model-monitor-cloudformation-custom-resource"></a>

먼저 CloudFormation 템플릿에 사용자 지정 리소스를 추가합니다. 이는 사용자가 다음 단계에서 생성하는 AWS Lambda 함수를 가리킵니다.

이 리소스를 사용하면 모니터링 일정에 대한 파라미터를 사용자 지정할 수 있습니다. 다음 예제 리소스에서 CloudFormation 리소스와 Lambda 함수를 수정하여 더 많은 파라미터를 추가하거나 제거할 수 있습니다.

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

## Lambda 사용자 지정 리소스 코드
<a name="model-monitor-cloudformation-lambda-custom-resource-code"></a>

이 CloudFormation 사용자 지정 리소스는를 사용하여 pip로 설치할 수 있는 [사용자 지정 리소스 헬퍼](https://github.com/aws-cloudformation/custom-resource-helper) AWS 라이브러리를 사용합니다`pip install crhelper`.

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

# Model Monitor FAQ
<a name="model-monitor-faqs"></a>

Amazon SageMaker Model Monitoror에 대한 자세한 내용은 다음 FAQ를 참조하세요.

**Q: Model Monitor와 SageMaker Clarify는 고객이 모델 동작을 모니터링하는 데 어떤 도움을 주나요?**

고객은 Amazon SageMaker Model Monitor와 SageMaker Clarify를 통해 [데이터 품질](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-data-quality.html), [모델 품질](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-model-quality.html), [바이어스 드리프트](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-monitor-bias-drift.html), [특징 속성 드리프트](https://docs.aws.amazon.com/sagemaker/latest/dg/clarify-model-monitor-feature-attribution-drift.html)의 4가지 차원에 걸쳐 모델 동작을 모니터링할 수 있습니다. [Model Monitor](https://aws.amazon.com/sagemaker/model-monitor/)는 프로덕션 환경에서 Amazon SageMaker AI 기계 학습 모델의 품질을 지속적으로 모니터링합니다. 여기에는 정확성, RMSE 등의 데이터 품질 및 모델 품질 지표에 대한 드리프트 모니터링이 포함됩니다. [SageMaker Clarify](https://aws.amazon.com/sagemaker/clarify/?sagemaker-data-wrangler-whats-new.sort-by=item.additionalFields.postDateTime&sagemaker-data-wrangler-whats-new.sort-order=desc) 바이어스 모니터링은 데이터 사이언티스트와 ML 엔지니어가 모델 예측 및 특징 속성 드리프트의 편향을 모니터링하는 데 도움이 됩니다.

**Q: Sagemaker Model Monitor가 활성화되면 백그라운드에서 어떤 일이 일어나나요?**

Amazon SageMaker Model Monitor는 모델 모니터링을 자동화해주므로 모델을 수동으로 모니터링하거나 별도의 도구를 구축할 필요가 줄어듭니다. Model Monitor는 프로세스를 자동화하기 위해 모델 훈련에 투입되었던 데이터를 사용하여 기준 통계 및 제약 조건 세트를 생성한 다음, 사용자의 엔드포인트에서 이루어진 예측을 모니터링하기 위한 일정을 설정할 수 있는 기능을 제공합니다. Model Monitor는 규칙을 사용하여 모델의 드리프트를 감지하고, 드리프트가 발생하면 사용자에게 알려줍니다. 다음 단계는 모델 모니터링을 활성화했을 때 발생하는 상황을 설명합니다.
+ **모델 모니터링 활성화**: 실시간 엔드포인트인 경우, 사용자는 배포된 ML 모델로 들어오는 요청의 데이터와 모델 예측의 결과 데이터를 캡처할 수 있도록 엔드포인트를 활성화해야 합니다. 배치 변환 작업인 경우, 해당 배치 변환 입력 및 출력의 데이터 캡처를 활성화하세요.
+ **기준 처리 작업**: 그 다음에는 해당 모델을 훈련하는 데 사용된 데이터세트를 바탕으로 기준을 생성합니다. 기준은 지표를 계산한 다음 지표에 대한 제약 조건을 제안합니다. 예를 들어, 모델의 재현율 점수가 0.571 미만으로 저하되거나 정밀도 점수가 1.0 미만으로 떨어지지 않아야 합니다. 해당 모델이 수행하는 실시간 또는 배치 예측은 제약 조건과 비교되며, 제약 조건의 값을 벗어나는 경우에는 위반으로 보고됩니다.
+ **모니터링 작업**: 그리고 모니터링 일정을 생성한 다음 수집할 데이터의 종류, 수집 빈도, 분석 방법 및 생성할 보고서를 지정합니다.
+ **병합 작업**: 이는 사용자가 Amazon SageMaker Ground Truth를 활용하는 경우에만 적용됩니다. Model Monitor는 모델의 품질을 측정하기 위해 해당 모델이 수행한 예측과 Ground Truth 레이블을 비교하게 됩니다. 이렇게 하려면, 엔드포인트에서 캡처된 데이터 또는 배치 변환 작업에 주기적으로 레이블을 지정한 다음 이를 Amazon S3에 업로드해야 합니다.

  Ground Truth 레이블을 생성하여 업로드를 마쳤다면, 모니터링 작업을 생성하는 단계에서 해당 레이블의 위치를 매개변수로 포함시킵니다.

Model Monitor를 사용하여 실시간 엔드포인트가 아닌 배치 변환 작업을 모니터링하는 경우, Model Monitor는 엔드포인트에 대한 요청을 수신하고 예측을 추적하는 대신에 추론 입력 및 출력을 모니터링합니다. Model Monitor 일정에서 고객은 처리 작업에 사용할 인스턴스의 개수와 유형을 제공합니다. 이러한 리소스는 현재 실행 상태에 관계없이 해당 일정이 삭제될 때까지는 예약된 상태로 유지됩니다.

**Q: Data Capture란 무엇이며, 왜 필요하며, 활성화하려면 어떻게 해야 하나요?**

모델 엔드포인트로 들어오는 입력과 Amazon S3에 배포된 모델의 추론 출력을 기록하기 위해 [Data Capture](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-data-capture.html)라는 특징을 활성화할 수 있습니다. 실시간 엔드포인트 및 배치 변환 작업 용도로 이 특징을 활성화하는 방법에 대한 자세한 내용은 [Capture data from real-time endpoint](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-data-capture-endpoint.html) 및 [Capture data from batch transform job](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-data-capture-batch.html)를 참조하세요.

**Q: Data Capture를 활성화하면 실시간 엔드포인트의 성능에 영향을 미치나요?**

Data Capture는 프로덕션 트래픽에 영향을 주지 않고 비동기적으로 이루어집니다. 데이터 캡처를 이미 활성화한 상태라면, 요청 및 응답 페이로드는 사용자가 `DataCaptureConfig`에서 지정한 Amazon S3 위치에 일부 추가 메타데이터와 함께 저장되게 됩니다. 참고로, 캡처된 데이터가 Amazon S3로 전파되기까지는 지연이 있을 수 있습니다.

캡처된 데이터는 Amazon S3에 저장된 데이터 캡처 파일을 나열하는 방식으로도 볼 수 있습니다. 해당 Amazon S3 경로의 형식은 `s3:///{endpoint-name}/{variant-name}/yyyy/mm/dd/hh/filename.jsonl`입니다. Amazon S3 Data Capture는 Model Monitor 일정과 동일한 리전에 있어야 합니다. 또한 기준 데이터세트의 열 이름에는 소문자만 포함되어야 하며 구분자로는 밑줄(`_`)만 사용해야 합니다.

**Q: 모델 모니터링에 Ground Truth가 필요한 이유는 무엇인가요?**

다음과 같은 Model Monitor의 특징에는 Ground Truth 레이블이 필수입니다.
+ **모델 품질 모니터링**은 모델의 품질을 측정하기 위해 해당 모델이 수행한 예측과 Ground Truth 레이블을 비교하게 됩니다.
+ **모델 편향 모니터링**은 예측의 편향을 모니터링합니다. 배포된 ML 모델에 편향이 발생할 수 있는 한 가지 가능성은 훈련에 사용되는 데이터가 예측 생성을 위해 사용되는 데이터와 다른 경우입니다. 이는 훈련에 사용되는 데이터가 시간이 지남에 따라 변화하는 경우(예: 모기지 금리 변동)에 특히 두드러지며, 이 때 모델 예측은 업데이트된 데이터로 모델을 재훈련하지 않는 한 이전처럼 정확하지 않게 됩니다. 예를 들어, 주택 가격 예측을 위한 모델에서 해당 모델의 훈련에 사용된 모기지 금리가 가장 최근의 실제 모기지 금리와 다를 경우, 예측이 편향될 수 있습니다.

**Q: 레이블링에 Ground Truth를 활용하는 고객의 경우, 모델 품질을 모니터링하기 위해서는 어떤 단계를 거쳐야 하나요?**

모델 품질 모니터링은 모델의 품질을 측정하기 위해 해당 모델이 수행한 예측과 Ground Truth 레이블을 비교하게 됩니다. 이렇게 하려면 엔드포인트에서 캡처한 데이터 또는 배치 변환 작업에 주기적으로 레이블을 지정하고 Amazon S3에 업로드해야 합니다. 모델 편향 모니터링의 실행 시에는 캡처 이외에 Ground Truth 데이터도 필요합니다. 실제 사용 사례에서는 Ground Truth 데이터를 정기적으로 수집하여 지정된 Amazon S3 위치에 업로드해야 합니다. Ground Truth 레이블을 캡처된 예측 데이터와 일치시키려면, 해당 데이터세트 내의 개별 레코드마다 고유한 식별자가 있어야 합니다. Ground Truth 데이터에 대한 각각의 레코드 구조는 [Ingest Ground Truth Labels and Merge Them With Predictions](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 레이블이 수집된 날짜에 해당합니다. 추론이 생성된 날짜와는 일치하지 않아도 됩니다.

**Q: 고객이 모니터링 일정을 사용자 지정하려면 어떻게 해야 하나요?**

내장된 모니터링 메커니즘을 사용하는 방법 외에도, 사전 처리 및 사후 처리 스크립트를 사용하거나 자체 컨테이너를 사용 또는 빌드함으로써 자체적인 사용자 지정 모니터링 일정과 절차를 생성할 수 있습니다. 사전 처리 및 사후 처리 스크립트는 데이터 품질과 모델 품질 작업에서만 작동한다는 점에 반드시 유의해야 합니다.

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

**Q: 사전 처리 스크립트를 활용할 수 있는 시나리오 또는 사용 사례에는 어떤 것이 있나요?**

모델 모니터에 대한 입력을 변환해야 하는 경우 사전 처리 스크립트를 사용할 수 있습니다. 다음 예제 시나리오를 검토해보세요.

1. 데이터 변환을 위한 사전 처리 스크립트.

   모델의 출력이 `[1.0, 2.1]`배열이라고 가정해 보겠습니다. Model Monitor 컨테이너는 `{“prediction0”: 1.0, “prediction1” : 2.1}`와 같은 형태의 테이블 형식 또는 평면화된 JSON 구조에서만 작동합니다. 해당 배열은 다음 예제와 같은 사전 처리 스크립트를 사용하여 올바른 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에 기록할 수 있습니다. 이는 오류 발생 시 사전 처리 스크립트를 디버깅할 때 유용할 수 있습니다. 다음 예제는 CloudWatch로 기록하기 위해 `preprocess_handler`인터페이스를 사용하는 방법을 보여줍니다.

   ```
   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 사전입니다.

**Q: 사후 처리 스크립트는 언제 활용할 수 있나요?**

모니터링이 성공적으로 실행되면 사후 처리 스크립트를 확장의 형태로 활용할 수 있습니다. 간단한 예제는 다음과 같지만, 모니터링이 성공적으로 실행된 후에는 수행되어야 하는 어떤 비즈니스 함수든 수행하거나 호출할 수 있습니다.

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

**Q: 모델 모니터링을 위해 자체 컨테이너를 가져오는 것을 고려해야 하는 것은 언제인가요?**

SageMaker AI는 테이블 형식 데이터세트에 대해 엔드포인트 또는 배치 변환 작업에서 캡처한 데이터를 분석하기 위한 사전 구축된 컨테이너를 제공합니다. 하지만 자체 컨테이너를 생성하는 것이 권장되는 시나리오도 있습니다. 다음 시나리오를 고려해 보세요.
+ 조직 내부적으로 생성 및 유지 관리되는 컨테이너만 사용하도록 되어 있는 규제 및 규정 준수 요구 사항이 적용되는 경우
+ 서드파티 라이브러리 몇 개를 포함하려는 경우, `requirements.txt` 파일을 로컬 디렉터리에 배치한 다음 [SageMaker AI 예측기](https://sagemaker.readthedocs.io/en/stable/api/training/estimators.html#sagemaker.estimator.Estimator)의 `source_dir` 파라미터를 사용하여 해당 파일을 참조하면 됩니다. 그러면 런타임에 라이브러리를 설치할 수 있습니다. 하지만 훈련 작업을 실행하는 동안 설치 시간이 늘어나게 만드는 라이브러리나 종속성이 많다면, BYOC(Bring Your Own Container)를 활용하는 것이 좋습니다.
+ 인터넷 연결이 불가능한 사용자 환경(또는 사일로)이라서 패키지 다운로드가 어려운 경우
+ 테이블 형식이 아닌 데이터 형식의 데이터를 모니터링하려는 경우(예: NLP 또는 CV 사용 사례)
+ Model Monitor에서 지원하는 것 이외의 추가적인 모니터링 지표가 필요한 경우

**Q: 저는 NLP 및 CV 모델을 가지고 있는데 데이터 드리프트를 모니터링하려면 어떻게 해야 하나요?**

Amazon SageMaker AI의 사전 구축된 컨테이너는 테이블 형식의 데이터세트를 지원합니다. NLP 및 CV 모델을 모니터링하려는 경우, Model Monitor에서 제공하는 확장 지점을 활용하여 사용자 자체 컨테이너를 가져올 수 있습니다. 요구 사항에 대한 자세한 내용은 [Bring your own containers](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-byoc-containers.html)를 참조하세요. 다음은 몇 가지 추가적인 예입니다.
+ 컴퓨터 비전 사용 사례에 Model Monitor를 활용하는 방법에 대한 자세한 설명은 [Detecting and Analyzing incorrect predictions](https://aws.amazon.com/blogs/machine-learning/detecting-and-analyzing-incorrect-model-predictions-with-amazon-sagemaker-model-monitor-and-debugger/)을 참조하세요.
+ Model Monitor를 NLP 사용 사례에 활용할 수 있는 시나리오는 [Detect NLP data drift using custom Amazon SageMaker Model Monitor](https://aws.amazon.com/blogs/machine-learning/detect-nlp-data-drift-using-custom-amazon-sagemaker-model-monitor/)를 참조하세요.

**Q: 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) 사용)해야 합니다. 그 다음에 엔드포인트를 삭제하면 됩니다.

**Q: SageMaker Model Monitor는 입력에 대한 지표와 통계를 계산하나요?**

Model Monitor는 입력이 아닌 출력에 대한 지표과 통계를 계산합니다.

**Q: SageMaker Model Monitor는 다중 모델 엔드포인트를 지원하나요?**

아니요, Model Monitor는 단일 모델을 호스팅하는 엔드포인트만 지원하고 다중 모델 엔드포인트 모니터링은 지원하지 않습니다.

**Q: SageMaker Model Monitor는 추론 파이프라인의 개별 컨테이너에 대한 모니터링 데이터를 제공하나요?**

Model Monitor는 추론 파이프라인 모니터링을 지원하지만 데이터 캡처 및 분석은 파이프라인의 개별 컨테이너가 아닌 전체 파이프라인에 대해 수행됩니다.

**Q: 데이터 캡처가 설정된 경우 추론 요청에 영향을 미치지 않도록 하려면 어떻게 해야 하나요?**

Data Capture는 추론 요청에 영향이 없도록 하기 위해 디스크 사용량이 많은 경우 요청 캡처를 중단합니다. 데이터 캡처가 요청을 계속 캡처하도록 하려면, 디스크 사용률을 75% 미만으로 유지하는 것이 좋습니다.

**Q: Amazon S3 데이터 캡처가 모니터링 일정이 설정된 AWS 리전과 다른 리전에 있을 수 있나요?**

아니요, Amazon S3 Data Capture는 반드시 해당 모니터링 일정과 동일한 리전에 있어야 합니다.

**Q: 기준이란 무엇이며, 어떻게 생성하나요? 사용자 지정 기준을 생성할 수 있나요?**

기준은 모델의 실시간 또는 배치 예측을 비교하기 위한 레퍼런스로서 사용됩니다. 이는 통계 및 지표와 함께 관련 제약 조건을 계산합니다. 모니터링 과정에서는 이러한 모든 항목이 함께 사용되어 위반을 식별합니다.

Amazon SageMaker Model Monitor의 기본 솔루션을 사용하려면 [Amazon SageMaker Python SDK](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`입니다. [Schema for statistics](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-byoc-statistics.html) 및 [schema for constraints](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor-byoc-constraints.html)에 각 파일의 스키마가 나와 있습니다. 생성된 제약 조건을 검토하고 이를 모니터링에 사용하기 전에 수정할 수 있습니다. 해당 분야와 비즈니스 문제에 대한 이해를 바탕으로 제약 조건을 보다 공격적으로 만들거나 완화하는 방식으로 위반의 건수와 특성을 제어하는 것이 가능합니다.

**Q: 기준 데이터세트를 만들기 위한 지침은 무엇인가요?**

모든 종류의 모니터링에 대한 기본적인 요구 사항은 지표와 제약 조건을 계산하는 데 사용되는 기준 데이터세트를 보유하는 것입니다. 일반적으로 이는 모델에서 사용되는 훈련 데이터세트에 해당하지만, 경우에 따라서는 다른 참조 데이터세트를 사용하는 것도 가능합니다.

기준 데이터세트의 열 이름은 Spark와 호환되어야 합니다. Spark, CSV, JSON 및 Parquet 간의 호환성을 극대화하려면 소문자만을 사용하고 구분자로는 `_`만 사용하는 것이 좋습니다. `“ ”` 등의 특수 문자는 문제를 일으킬 수 있습니다.

**Q: `StartTimeOffset`및 `EndTimeOffset`매개변수는 무엇이며 언제 사용되나요?**

모델 품질과 같은 작업을 모니터링하는 데 Amazon SageMaker Ground Truth가 필요한 경우, Ground Truth가 준비되어 있는 데이터만 모니터링 작업에 사용되도록 해야 합니다. [EndpointInput](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html#sagemaker.model_monitor.model_monitoring.EndpointInput)의 `start_time_offset`및 `end_time_offset`매개변수를 사용하면 모니터링 작업에서 사용하는 데이터를 선택할 수 있습니다. 모니터링 작업은 `start_time_offset`및 `end_time_offset`에 의해 정의된 기간 안의 데이터를 사용합니다. 이러한 매개변수는 [ISO8601 기간 형식](https://en.wikipedia.org/wiki/ISO_8601#Durations)으로 지정되어야 합니다. 다음은 몇 가지 예시입니다.
+ 만약 예측이 이루어진 지 3일 후에 Ground Truth 결과가 도착한다면, `start_time_offset="-P3D"`및 `end_time_offset="-P1D"`(각각 3일과 1일에 해당)으로 설정합니다.
+ Ground Truth 결과가 예측 후 6시간 후에 도착하고, 시간별 일정이 설정되어 있는 경우라면, `start_time_offset="-PT6H"`및 `end_time_offset="-PT1H"`(6시간 1시간에 해당)으로 설정합니다.

**Q: 모니터링 작업을 '온디맨드'로 실행할 수 있나요?**

예.SageMaker Processing 작업을 실행하면 '온디맨드' 모니터링 작업을 실행할 수 있습니다. 배치 변환인 경우, [Pipelines](https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-overview.html)에는 온디맨드로 모니터링 작업을 실행하는 SageMaker AI 파이프라인을 만드는 용도로 사용 가능한 [MonitorBatchTransformStep](https://sagemaker.readthedocs.io/en/stable/workflows/pipelines/sagemaker.workflow.pipelines.html#sagemaker.workflow.monitor_batch_transform_step.MonitorBatchTransformStep)이 있습니다. SageMaker AI 예시 리포지토리에는 [데이터 품질](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker_model_monitor/model_monitor_batch_transform/SageMaker-ModelMonitoring-Batch-Transform-Data-Quality-With-SageMaker-Pipelines-On-Demand.ipynb) 및 [모델 품질](https://github.com/aws/amazon-sagemaker-examples/blob/main/sagemaker_model_monitor/model_monitor_batch_transform/SageMaker-ModelMonitoring-Batch-Transform-Model-Quality-With-SageMaker-Pipelines-On-Demand.ipynb) 모니터링 작업을 온디맨드로 실행하기 위한 코드 샘플이 나와 있습니다.

**Q: Model Monitor 설정은 어떻게 해야 하나요?**

다음과 같은 방법으로 Model Monitor를 설정할 수 있습니다.
+ **[Amazon SageMaker AI Python SDK](https://sagemaker.readthedocs.io/en/stable/index.html)** – 기준 제안, 모니터링 일정 생성 등의 작업을 지원하는 클래스와 함수가 포함되어 있는 [Model Monitor 모듈](https://sagemaker.readthedocs.io/en/stable/api/inference/model_monitor.html)이 있습니다. Model Monitor 설정에 SageMaker AI Python SDK를 활용하는 것에 대한 자세한 노트북은 [Amazon SageMaker Model Monitor 노트북 예시](https://github.com/aws/amazon-sagemaker-examples/tree/main/sagemaker_model_monitor)를 참조하세요.
+ **[Pipelines](https://docs.aws.amazon.com/sagemaker/latest/dg/pipelines-overview.html)** – Pipelines은 [QualityCheck Step](https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html#step-type-quality-check) 및 [ClarifyCheckStep](https://docs.aws.amazon.com/sagemaker/latest/dg/build-and-manage-steps.html#step-type-clarify-check) API를 통해 Model Monitor와 통합됩니다. 이러한 단계를 포함하며 파이프라인이 실행될 때마다 모니터링 작업을 온디맨드로 실행하는 용도로 사용이 가능한 SageMaker AI 파이프라인을 생성할 수 있습니다.
+ **[Amazon SageMaker Studio Classic](https://docs.aws.amazon.com/sagemaker/latest/dg/studio.html)** – 배포된 모델 엔드포인트 목록에서 엔드포인트를 선택함으로써 데이터 품질 또는 모델 품질 모니터링 일정을 모델 편향 및 설명 가능성 일정과 함께 UI에서 직접 만들 수 있습니다. 다른 유형의 모니터링 일정은 UI에서 관련 탭을 선택함으로써 생성할 수 있습니다.
+ **[SageMaker Model Dashboard](https://docs.aws.amazon.com/sagemaker/latest/dg/model-dashboard.html)** - 엔드포인트에 배포되어 있는 모델을 선택함으로써 엔드포인트에 대한 모니터링을 활성화할 수 있습니다. 다음 SageMaker AI 콘솔 스크린샷에서는 **모델 대시보드**의 **모델** 섹션에서 `group1`이라는 모델이 선택되었습니다. 이 페이지에서 모니터링 일정을 생성하고 기존 모니터링 일정 및 알림을 편집, 활성화 또는 비활성화하는 작업을 수행할 수 있습니다. 알림 및 모델 모니터 일정을 확인하는 방법에 대한 단계별 지침은 [View Model Monitor schedules and alerts](https://docs.aws.amazon.com/sagemaker/latest/dg/model-dashboard-schedule.html)를 참조하세요.

![\[모니터링 일정을 생성하는 옵션을 보여주고 있는 모델 대시보드의 스크린샷입니다.\]](http://docs.aws.amazon.com/ko_kr/sagemaker/latest/dg/images/model-monitoring-faqs-screenshot.png)


**Q: Model Monitor는 SageMaker Model Dashboard와 어떻게 통합되나요?**

[SageMaker Model Dashboard](https://docs.aws.amazon.com/sagemaker/latest/dg/model-dashboard.html)는 예상 동작과의 편차에 대한 자동 알림 기능 그리고 모델을 검사하여 시간 경과에 따라 모델 성능에 영향을 미치는 요인을 분석하기 위한 문제 해결 기능을 제공함으로써 모든 모델에 대한 통합 모니터링을 구현합니다.