

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

# 在資產的感應器上啟用異常偵測
<a name="anom-detection-sensors-asset"></a>

## 建立運算模型 (AWS CLI)
<a name="create-computation-model"></a>

若要建立運算模型，請使用 AWS 命令列界面 (AWS CLI)。定義運算模型後，請訓練模型並排定推論，以在資產上執行異常偵測 AWS IoT SiteWise。
+ 建立`anomaly-detection-computation-model-payload.json`具有下列內容的檔案：

  ```
  {
      "computationModelName": "anomaly-detection-computation-model-name",
      "computationModelConfiguration": {
          "anomalyDetection": {
              "inputProperties": "${input_properties}",
              "resultProperty": "${result_property}"
          }
      },
      "computationModelDataBinding": {
          "input_properties": {
              "list": [{
                      "assetModelProperty": {
                          "assetModelId": "asset-model-id",
                          "propertyId": "input-property-id-1"
                      }
                  },
                  {
                      "assetModelProperty": {
                          "assetModelId": "asset-model-id",
                          "propertyId": "input-property-id-2"
                      }
                  }
              ]
          },
          "result_property": {
              "assetModelProperty": {
                  "assetModelId": "asset-model-id",
                  "propertyId": "results-property-id"
              }
          }
      }
  }
  ```
+ 執行下列命令來建立運算模型：

  ```
  aws iotsitewise create-computation-model \
      --cli-input-json file://anomaly-detection-computation-model-payload.json
  ```

## ExecuteAction API 承載準備
<a name="create-action-payload"></a>

 執行訓練和推論的後續步驟會使用 [ExecuteAction](https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_ExecuteAction.html) API 執行。訓練和推論都是使用 JSON 動作承載組態來設定。叫用 [ExecuteAction](https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_ExecuteAction.html) API 時，必須提供動作承載做為具有`stringValue`承載的值。

 承載必須嚴格遵守 API 要求。具體而言，該值必須是**扁平字串**，沒有**控制字元** （例如換行、標籤或歸位字元）。

下列選項提供兩種可靠的方式來提供有效的動作承載：

### 選項 1：使用乾淨的承載檔案
<a name="clean-payload-file"></a>

下列程序說明乾淨承載檔案的步驟：

1. 清除 檔案以移除控制字元。

   ```
   tr -d '\n\r\t' < original-action-payload.json > training-or-inference-action-payload.json
   ```

1. 使用 檔案執行 動作`@=file://...`。

   ```
   aws iotsitewise execute-action \
       --target-resource computationModelId=<MODEL_ID> \
       --action-definition-id <ACTION_DEFINITION_ID> \
       --resolve-to assetId=<ASSET_ID> \
       --action-payload stringValue@=file://training-or-inference-action-payload.json
   ```

### 選項 2：具有逸出引號的內嵌字串
<a name="inline-string-quotes"></a>

下列步驟說明內嵌提供承載的步驟，並避免中介檔案：
+ 在 JSON 字串中使用逸出雙引號 (`\"`)。
+ 以雙引號括住整個`StringValue=..`表達式。

**Example 逸出動作承載的 ：**  

```
aws iotsitewise execute-action \
    --target-resource computationModelId=<MODEL_ID> \
    --action-definition-id <ACTION_DEFINITION_ID> \
    --resolve-to assetId=<ASSET_ID> \
    --action-payload "stringValue={\"exportDataStartTime\":1717225200,\"exportDataEndTime\":1722789360,\"targetSamplingRate\":\"PT1M\"}"
```

## 訓練模型 (AWS CLI)
<a name="start-training-cli"></a>

建立運算模型後，您可以針對資產訓練模型。請依照下列步驟來訓練資產的模型：

1. 執行下列命令來尋找 `AWS/ANOMALY_DETECTION_TRAINING`動作`actionDefinitionId`的 。`computation-model-id` 將 取代為上一個步驟中傳回的 ID。

   ```
   aws iotsitewise describe-computation-model \
       --computation-model-id computation-model-id
   ```

1. 建立名為 的檔案`anomaly-detection-training-payload.json`，並新增下列值：
**注意**  
 承載必須符合 [選項 1：使用乾淨的承載檔案](#clean-payload-file)。

   1. `StartTime` 訓練資料的開頭，以 epoch 秒為單位提供。

   1. `EndTime` 訓練資料的結尾，以 epoch 秒提供。

   1. 您可以選擇性地設定 [進階訓練組態](adv-training-configs.md)，以改善模型效能。

      1. （選用） `TargetSamplingRate`搭配資料的取樣率。

      1. （選用） `LabelInputConfiguration` 指定為改善模型訓練而發生異常行為的時段。

      1. （選用） `ModelEvaluationConfiguration` 在訓練完成後，透過在指定的時間範圍執行推論來評估模型效能。

      1. （選用） `ModelMetricsDestination` 以收集完整的效能資料 （精確度、召回率、曲線下的區域）。

   ```
   {
     "trainingMode": "TRAIN_MODEL", 
     "exportDataStartTime": StartTime,
     "exportDataEndTime": EndTime
   }
   ```  
**Example 訓練承載範例：**  

   ```
   {
     "trainingMode": "TRAIN_MODEL",            
     "exportDataStartTime": 1717225200,
     "exportDataEndTime": 1722789360
   }
   ```

1. 執行下列命令以開始訓練。在 命令中取代下列參數：

   1. `computation-model-id` 目標運算模型的 ID。

   1. `asset-id` 使用您將訓練模型的資產 ID。

   1. `training-action-definition-id` 具有步驟 1 中`AWS/ANOMALY_DETECTION_TRAINING`動作的 ID。

   ```
   aws iotsitewise execute-action \
       --target-resource computationModelId=computation-model-id \
       --resolve-to assetId=asset-id \
       --action-definition-id training-action-definition-id \
       --action-payload stringValue@=file://anomaly-detection-training-payload.json
   ```  
**Example 執行動作的 ：**  

   ```
   aws iotsitewise execute-action --target-resource computationModelId=27cb824c-fd84-45b0-946b-0a5b0466d890 --resolve-to assetId=cefd4b68-481b-4735-b466-6a4220cd19ee --action-definition-id e54cea94-5d1c-4230-a59e-4f54dcbc972d --action-payload stringValue@=file://anomaly-detection-training-payload.json
   ```

1. 執行下列命令來檢查模型訓練程序的狀態。最新的執行摘要會顯示執行狀態 (`RUNNING`/`COMPLETED`/`FAILED`)。

   ```
   aws iotsitewise list-executions \
       --target-resource-type COMPUTATION_MODEL \
       --target-resource-id computation-model-id\
       --resolve-to-resource-type ASSET \
       --resolve-to-resource-id asset-id
   ```

1. 執行下列命令來檢查最新訓練模型的組態。只有在至少成功訓練一個模型時，此命令才會產生輸出。

   ```
   aws iotsitewise describe-computation-model-execution-summary \
       --computation-model-id computation-model-id \
       --resolve-to-resource-type ASSET \
       --resolve-to-resource-id asset-id
   ```

1. 當 `ComputationModel` 使用 AssetModelProperty 時，請使用 [ListComputationModelResolveToResources](https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_ListComputationModelResolveToResources.html) API 來識別具有執行動作的資產。

   ```
   aws iotsitewise list-computation-model-resolve-to-resources \
       --computation-model-id computation-model-id
   ```

## 開始和停止重新訓練模型 (AWS CLI)
<a name="start-stop-retraining-cli"></a>

在初始模型訓練後，您可以設定自動重新訓練，以解決資料漂移，並隨著時間維持模型準確性。重新訓練排程器可讓您使用可設定的提升模式設定定期模型更新。

### 開始重新訓練排程器
<a name="start-retraining-scheduler"></a>

1. 執行下列命令來尋找 `AWS/ANOMALY_DETECTION_TRAINING`動作`actionDefinitionId`的 。`computation-model-id` 將 取代為從運算模型建立中傳回的 ID。

   ```
   aws iotsitewise describe-computation-model \
       --computation-model-id computation-model-id
   ```

1. 建立名為 的檔案`anomaly-detection-start-retraining-payload.json`，並新增下列程式碼。將參數取代為所述的值。
**注意**  
 承載必須符合 [選項 1：使用乾淨的承載檔案](#clean-payload-file)。

   1. `lookbackWindow` 與用於重新訓練的歷史資料時段 (`P180D`/`P360D`/`P540D`//`P720D`)。

   1. `retrainingFrequency` 重新訓練模型的頻率 （最小值 `P30D`，最大值 `P1Y`)。

   1. （選用） `promotion` 搭配模型提升模式 (`SERVICE_MANAGED` 或 `CUSTOMER_MANAGED`)。預設值為 `SERVICE_MANAGED`。

   1. （選用） `retrainingStartDate`具有重新訓練排程的開始日期，以 epoch 秒為單位提供。將時間截斷為最接近的 UTC 天。選用，預設為目前日期。

   1. 您可以選擇性地設定 [進階訓練組態](adv-training-configs.md)來改善模型效能。

      1. （選用） `ModelMetricsDestination` 以取得完整的效能資料 （精確度、召回率、曲線下的區域）。

   ```
   {
       "trainingMode": "START_RETRAINING_SCHEDULER",
       "retrainingConfiguration": {
           "lookbackWindow": "P180D",
           "promotion": "SERVICE_MANAGED",
           "retrainingFrequency": "P30D",
           "retrainingStartDate": "StartDate"
       }
   }
   ```

1. 執行下列命令來啟動重新訓練排程器。在 命令中取代下列參數：

   1. `computation-model-id` 目標運算模型的 ID。

   1. `asset-id` 使用您將訓練模型的資產 ID。

   1. `training-action-definition-id` 具有步驟 1 中`AWS/ANOMALY_DETECTION_TRAINING`動作的 ID。

   ```
   aws iotsitewise execute-action \
       --target-resource computationModelId=computation-model-id \
       --resolve-to assetId=asset-id \
       --action-definition-id training-action-definition-id \
       --action-payload stringValue@=file://anomaly-detection-start-retraining-payload.json
   ```  
**Example 執行動作命令的範例**  

   ```
   aws iotsitewise execute-action --target-resource computationModelId=27cb824c-fd84-45b0-946b-0a5b0466d890 --resolve-to assetId=cefd4b68-481b-4735-b466-6a4220cd19ee --action-definition-id e54cea94-5d1c-4230-a59e-4f54dcbc972d --action-payload stringValue@=file://anomaly-detection-start-retraining-payload.json
   ```

### 停止重新訓練排程器
<a name="stop-retraining-scheduler"></a>

1. 執行下列命令來尋找 `AWS/ANOMALY_DETECTION_TRAINING`動作`actionDefinitionId`的 。`computation-model-id` 以先前建立之運算模型的實際 ID 取代 。

   ```
   aws iotsitewise describe-computation-model \
       --computation-model-id computation-model-id
   ```

1. 建立檔案`anomaly-detection-stop-retraining-payload.json`並新增下列項目：
**注意**  
 承載必須符合 [選項 1：使用乾淨的承載檔案](#clean-payload-file)。

   ```
   {
       "trainingMode": "STOP_RETRAINING_SCHEDULER"
   }
   ```

1. 執行下列命令來停止重新訓練排程器。在 命令中取代下列參數：

   1. `computation-model-id` 目標運算模型的 ID。

   1. `asset-id` 使用您將訓練模型的資產 ID。

   1. `training-action-definition-id` 具有步驟 1 中`AWS/ANOMALY_DETECTION_TRAINING`動作的 ID。

   ```
   aws iotsitewise execute-action \
       --target-resource computationModelId=computation-model-id \
       --resolve-to assetId=asset-id \
       --action-definition-id training-action-definition-id \
       --action-payload stringValue@=file://anomaly-detection-stop-retraining-payload.json
   ```

## 啟動和停止推論 (AWS CLI)
<a name="start-stop-inference"></a>

訓練模型後，開始推論。這會指示 AWS IoT SiteWise 主動監控工業資產是否有異常。

### 開始推論
<a name="start-inference"></a>

1. 執行下列命令來尋找 `AWS/ANOMALY_DETECTION_INFERENCE`動作`actionDefinitionId`的 。`computation-model-id` 以先前建立之運算模型的實際 ID 取代 。

   ```
   aws iotsitewise describe-computation-model \
       --computation-model-id computation-model-id
   ```

1. 建立檔案`anomaly-detection-start-inference-payload.json`並新增下列值：
**注意**  
 承載必須符合 [選項 1：使用乾淨的承載檔案](#clean-payload-file)。

   ```
   "inferenceMode": "START",
   "dataUploadFrequency": "DataUploadFrequency"
   ```

   1. `DataUploadFrequency`：設定推論排程執行的頻率，以執行異常偵測。允許的值為：`PT5M, PT10M, PT15M, PT30M, PT1H, PT2H..PT12H, PT1D`。

   1. （選用） `DataDelayOffsetInMinutes` 搭配以分鐘為單位的延遲位移。將此值設定為 0 到 60 分鐘。

   1. （選用） `TargetModelVersion` 搭配要啟用的模型版本。

   1. （選用） `weeklyOperatingWindow`使用輪班組態設定 。

   1. 您可以選擇性地設定 [進階推論組態](advanced-inference-configurations.md)。

      1. [高頻率推論 (5 分鐘 – 1 小時）](advanced-inference-configurations.md#high-frequency-inferencing).

      1. [低頻率推論 (2 小時 – 1 天）](advanced-inference-configurations.md#low-frequency-inferencing).

      1. [彈性排程](advanced-inference-configurations.md#flexible-scheduling).

1. 執行下列命令以開始推論。取代承載檔案中的下列參數。

   1. `computation-model-id` 目標運算模型的 ID。

   1. `asset-id` 使用訓練模型的資產 ID。

   1. `inference-action-definition-id` 具有步驟 1 中`AWS/ANOMALY_DETECTION_INFERENCE`動作的 ID。

   ```
   aws iotsitewise execute-action \
       --target-resource computationModelId=computation-model-id \
       --resolve-to assetId=asset-id \
       --action-definition-id inference-action-definition-id \
       --action-payload stringValue@=file://anomaly-detection-inference-payload.json
   ```

1. 執行下列命令來檢查推論是否仍在執行中。推論作用中`TRUE`時， `inferenceTimerActive` 欄位會設為 。

   ```
   aws iotsitewise describe-computation-model-execution-summary \
       --computation-model-id computation-model-id \
       --resolve-to-resource-type ASSET \
       --resolve-to-resource-id asset-id
   ```

1. 下列命令會列出所有推論執行：

   ```
   aws iotsitewise list-executions \
      --target-resource-type COMPUTATION_MODEL \
      --target-resource-id computation-model-id \
      --resolve-to-resource-type ASSET \
      --resolve-to-resource-id asset-id
   ```

1. 執行下列命令來描述個別執行。`execution-id` 將 取代為先前步驟 5 的 ID。

   ```
   aws iotsitewise describe-execution \
       --execution-id execution-id
   ```

### 停止推論
<a name="stop-inference"></a>

1. 執行下列命令來尋找 `AWS/ANOMALY_DETECTION_INFERENCE`動作`actionDefinitionId`的 。`computation-model-id` 以先前建立的運算模型實際 ID 取代 。

   ```
   aws iotsitewise describe-computation-model \
       --computation-model-id computation-model-id
   ```

1. 建立檔案`anomaly-detection-stop-inference-payload.json`並新增下列程式碼。

   ```
   {
       "inferenceMode": "STOP"
   }
   ```
**注意**  
 承載必須符合 [選項 1：使用乾淨的承載檔案](#clean-payload-file)。

1. 執行下列命令來停止推論。取代承載檔案中的下列參數：

   1. `computation-model-id` 目標運算模型的 ID。

   1. `asset-id` 使用訓練模型的資產 ID。

   1. `inference-action-definition-id` 具有步驟 1 中`AWS/ANOMALY_DETECTION_INFERENCE`動作的 ID。  
**Example 停止推論命令的 ：**  

   ```
   aws iotsitewise execute-action \
       --target-resource computationModelId=computation-model-id \
       --resolve-to assetId=asset-id \
       --action-definition-id inference-action-definition-id \
       --action-payload stringValue@=file://anomaly-detection-stop-inference-payload.json
   ```

## 尋找在資料繫結中使用指定資源的運算模型
<a name="find-computation-models-data-binding"></a>

若要列出繫結至指定資源的運算模型：
+ **資產模型** （擷取所有運算模型，其中任何此資產模型的屬性都已繫結）。
+ **asset** （擷取任何此資產屬性繫結的所有運算模型）
+ **資產模型屬性** （擷取此屬性繫結的所有運算模型）
+ **asset 屬性** （擷取此屬性繫結的所有運算模型。 這可能是為了提供資訊，或者當使用者嘗試將此屬性繫結至另一個運算模型，但已繫結到別處時需要）

使用 [ ListComputationModelDataBindingUsages](https://docs.aws.amazon.com/iot-sitewise/latest/APIReference/API_ListComputationModelDataBindingUsages.html) API 擷取`ComputationModelId`將資產 （屬性） 或資產模型 （屬性） 視為資料繫結的 清單。

準備`request.json`具有下列資訊的 ：

```
{
  "dataBindingValueFilter": {
    "asset": {
      "assetId": "<string>"
    }
    // OR
    "assetModel": {
      "assetModelId": "<string>"
    }
    // OR
    "assetProperty": {
      "assetId": "<string>",
      "propertyId": "<string>"
    }
    // OR
    "assetModelProperty": {
      "assetModelId": "<string>",
      "propertyId": "<string>"
    }
  },
  "nextToken": "<string>",
  "maxResults": "<number>"
}
```

使用 `list-computation-model-data-binding-usages`命令來擷取具有資產或資產模型作為資料繫結的模型。

```
aws iotsitewise list-computation-model-data-binding-usages \
--cli-input-json file://request.json
```