

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

# 評估模型
<a name="ex1-test-model"></a>

既然您已使用 Amazon SageMaker AI 訓練並部署模型，則請評估該模型，以確保其會根據新資料產生準確的預測。要評估模型，請使用您已在 [準備資料集](ex1-preprocess-data.md) 中建立的測試資料集。

## 評估部署至 SageMaker AI 託管服務的模型。
<a name="ex1-test-model-endpoint"></a>

要評估模型並在生產環境中使用它，請使用測試資料集調用端點，並檢查您獲得的推論是否傳回要實現的目標準確性。

**若要評估模型**

1. 設定下列函式以預測測試集的每一行。在下列範例程式碼中，`rows` 引數是指定一次要預測的行數。您可以變更它的值，以執行完全利用執行個體硬體資源的批次推論。

   ```
   import numpy as np
   def predict(data, rows=1000):
       split_array = np.array_split(data, int(data.shape[0] / float(rows) + 1))
       predictions = ''
       for array in split_array:
           predictions = ','.join([predictions, xgb_predictor.predict(array).decode('utf-8')])
       return np.fromstring(predictions[1:], sep=',')
   ```

1. 執行以下程式碼以對測試資料集進行預測並繪製長條圖。您只需要測試資料集的功能列，不包括第 0 列的實際值。

   ```
   import matplotlib.pyplot as plt
   
   predictions=predict(test.to_numpy()[:,1:])
   plt.hist(predictions)
   plt.show()
   ```  
![\[預測值的長條圖。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/get-started-ni/gs-ni-eval-predicted-values-histogram.png)

1. 預測值是浮點類型。要確定 `True` 或 `False` 基於浮點值，你需要設置一個截止值。如下列範例程式碼所示，使用 Scikit-學習程式庫傳回輸出混淆量度和分類報告，截止值為 0.5。

   ```
   import sklearn
   
   cutoff=0.5
   print(sklearn.metrics.confusion_matrix(test.iloc[:, 0], np.where(predictions > cutoff, 1, 0)))
   print(sklearn.metrics.classification_report(test.iloc[:, 0], np.where(predictions > cutoff, 1, 0)))
   ```

   這應該會傳回下列混淆矩陣：  
![\[取得已部署模型的推論後，混淆矩陣和統計資料的範例。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/get-started-ni/gs-ni-evaluate-confusion-matrix.png)

1. 為了找到特定測試集的最佳截止，請運算邏輯迴歸的日誌遺失函式。日誌遺失函式定義為物流模型的負對數可能性，該物流模型會傳回其接地真值標籤的預測機率。下列範例程式碼會以數值和反覆方式計算日誌遺失值 (`-(y*log(p)+(1-y)log(1-p)`)，其中 `y` 是真實的標籤，而且 `p` 是對應測試樣本的概率估計。它傳回一個日誌遺失與截止圖。

   ```
   import matplotlib.pyplot as plt
   
   cutoffs = np.arange(0.01, 1, 0.01)
   log_loss = []
   for c in cutoffs:
       log_loss.append(
           sklearn.metrics.log_loss(test.iloc[:, 0], np.where(predictions > c, 1, 0))
       )
   
   plt.figure(figsize=(15,10))
   plt.plot(cutoffs, log_loss)
   plt.xlabel("Cutoff")
   plt.ylabel("Log loss")
   plt.show()
   ```

   這應該會傳回下列日誌遺失曲線。  
![\[遵循日誌遺失曲線的範例。\]](http://docs.aws.amazon.com/zh_tw/sagemaker/latest/dg/images/get-started-ni/gs-ni-evaluate-logloss-vs-cutoff.png)

1. 使用 NumPy `argmin` 和 `min` 函式找到誤差曲線的最小點：

   ```
   print(
       'Log loss is minimized at a cutoff of ', cutoffs[np.argmin(log_loss)], 
       ', and the log loss value at the minimum is ', np.min(log_loss)
   )
   ```

   這應該傳回：`Log loss is minimized at a cutoff of 0.53, and the log loss value at the minimum is 4.348539186773897`。

   您可以估算成本函式作為替代方案，而不是計算和最小化日誌遺失函式。例如，如果您想要訓練模型來針對企業問題 (例如客戶流失率預測問題) 執行二進制分類，您可以設定混淆矩陣元素的權重，並相應地計算成本函式。

現在您已在 SageMaker AI 中訓練、部署和評估您的第一個模型。

**提示**  
若要監控模型品質、資料品質和偏差偏離，請使用 Amazon SageMaker Model Monitor 和 SageMaker AI Clarify。要瞭解更多資料，請參閱 [Amazon SageMaker Model Monitor](https://docs.aws.amazon.com/sagemaker/latest/dg/model-monitor.html)、[監控資料品質](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)。

**提示**  
若要取得低信賴度機器學習 (ML) 預測的人工審查或隨機預測樣本，請使用 Amazon 增強版 AI 人工審核工作流程。有關詳細資料，請參閱[使用 Amazon 增強版 AI 進行人工審核](https://docs.aws.amazon.com/sagemaker/latest/dg/a2i-use-augmented-ai-a2i-human-review-loops.html)。