

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

# 使用 Debugger API 執行您自己的自訂規則
<a name="debugger-custom-rules-python-sdk"></a>

下列程式碼範例示範如何使用 [Amazon SageMaker Python SDK](https://sagemaker.readthedocs.io/en/stable) 設定自訂規則。此範例假設您在上一個步驟中建立的自訂規則指令碼位於 '*path/to/my\$1custom\$1rule.py*'。

```
from sagemaker.debugger import Rule, CollectionConfig

custom_rule = Rule.custom(
    name='MyCustomRule',
    image_uri='759209512951.dkr.ecr.us-west-2.amazonaws.com/sagemaker-debugger-rule-evaluator:latest', 
    instance_type='ml.t3.medium',     
    source='path/to/my_custom_rule.py', 
    rule_to_invoke='CustomGradientRule',     
    collections_to_save=[CollectionConfig("gradients")], 
    rule_parameters={"threshold": "20.0"}
)
```

以下清單說明偵錯器 `Rule.custom` API 引數。
+ `name` (str)：根據需要指定自訂規則名稱。
+ `image_uri` (str)：這是容器映像，具備理解您的自訂規則的邏輯。它會取得並評估您在訓練任務中儲存的指定張量集合。您可以從 [自訂規則評估工具的 Amazon SageMaker Debugger 映像 URL](debugger-reference.md#debuger-custom-rule-registry-ids) 找到開放原始碼 SageMaker AI 規則評估器的清單。
+ `instance_type` (str)：您需要指定執行個體來建置規則 Docker 容器。這會與訓練容器同時加速運轉執行個體。
+ `source` (str)：這是您自訂規則指令碼的本機路徑或 Amazon S3 URI。
+ `rule_to_invoke` (str)：這將指定您自訂規則指令碼的特定 Rule 類別實作。SageMaker AI 僅支援在規則任務中一次評估一個規則。
+ `collections_to_save` (str)：這會指定要儲存哪些張量集合來執行規則。
+ `rule_parameters` (字典)：這會接受採字典格式的參數輸入。您可以調整自訂規則指令碼中設定的參數。

設定 `custom_rule` 物件後，您可以將其用於建置任何訓練任務的 SageMaker AI 估算器。請指定 `entry_point` 至您的訓練指令碼。您不需要對訓練指令碼進行任何變更。

```
from sagemaker.tensorflow import TensorFlow

estimator = TensorFlow(
                role=sagemaker.get_execution_role(),
                base_job_name='smdebug-custom-rule-demo-tf-keras',
                entry_point='path/to/your_training_script.py'
                train_instance_type='ml.p2.xlarge'
                ...
                
                # debugger-specific arguments below
                rules = [custom_rule]
)

estimator.fit()
```

有關使用偵錯器自訂規則的更多變化和進階範例，請參閱下列範例筆記本。
+ [使用 Amazon SageMaker Debugger 自訂規則監控您的訓練任務](https://sagemaker-examples.readthedocs.io/en/latest/sagemaker-debugger/tensorflow_keras_custom_rule/tf-keras-custom-rule.html)
+ [ResNet 和 AlexNet 的 PyTorch 反覆運算模型刪減](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/pytorch_iterative_model_pruning)
+ [使用偵錯器規則觸發 Amazon CloudWatch Events，以根據 TensorFlow 的訓練狀態採取行動](https://github.com/awslabs/amazon-sagemaker-examples/tree/master/sagemaker-debugger/tensorflow_action_on_rule)