開始使用免費開始

計算混淆矩陣

就像你在影片中看到的,混淆矩陣是校準模型輸出並檢視所有可能預測結果(真陽性、真陰性、假陽性、假陰性)的一個非常實用的工具。

在建立混淆矩陣之前,你需要在某個臨界值上「切」預測機率,將機率轉換為類別預測的因子。將 ifelse()factor() 如下結合:

pos_or_neg <- ifelse(probability_prediction > threshold, positive_class, negative_class)
p_class <- factor(pos_or_neg, levels = levels(test_values))

caret 套件中的 confusionMatrix() 在 base R 的 table() 基礎上加強,除了表中的基本比率外,還加入許多實用的輔助統計量。你可以同時使用預測結果與實際結果來計算混淆矩陣(以及相關統計量),例如:

confusionMatrix(p_class, test_values)

本練習屬於課程

使用 R 的 caret 進行 Machine Learning

檢視課程

練習說明

  • 使用 ifelse() 建立字元向量 m_or_r:當 p 大於 0.5 時為正類別 "M",否則為負類別 "R"
  • m_or_r 轉換為因子 p_class,其層級需與 test[["Class"]] 的層級相同。
  • 使用 confusionMatrix() 建立混淆矩陣,並傳入 p_classtest 資料集中 "Class" 這個欄位。

動手互動練習

試著完成這個範例程式碼,體驗一下這個練習。

# If p exceeds threshold of 0.5, M else R: m_or_r


# Convert to factor: p_class


# Create confusion matrix
編輯並執行程式碼