[英]What is the most efficient way of computing a confusion matrix from 2 logical vectors in R?
給定兩個邏輯向量(即 R 中只有 TRUE 或 FALSE 值),長度均為 n(一個向量是預測,另一個是基本事實),計算真陽性和真陰性的最有效方法是什么,假陽性和假陰性? 只需執行tp = pred & truth
即可輕松完成真正的肯定。 但是,我認為 R 中沒有其他邏輯運算符可以直接幫助計算其他統計信息。
一個明顯的解決方案是遍歷這兩個向量並只做案例(例如,如果預測為 FALSE 且真值 FALSE 則將真負數加一),但我覺得必須有一種更快的方法。 真正的肯定情況非常好,因為它可以通過向量化的 AND 運算符來完成(我認為?)。
編輯:我的錯,忘了提幾個重要的細節:我的真實數據中的向量有數億長,我需要計算混淆矩陣大約 30,000 次。 使用表格的答案很有用,因為我之前完全錯過了這個選項,但我擔心轉換為因子並且使用表格太慢了。 我認為此時最好的選擇可能是使用 Rcpp。
您可以使用caret
package 中的confusionMatrix ()
function:
代碼:
library(caret)
set.seed(123)
confusionMatrix(
prediction <- factor(sample(c(0,1), 100, replace = TRUE)),
ground_truth <- factor(sample(c(0,1), 100, replace = TRUE)))
Output:
Confusion Matrix and Statistics
Reference
Prediction 0 1
0 26 31
1 20 23
Accuracy : 0.49
95% CI : (0.3886, 0.592)
No Information Rate : 0.54
P-Value [Acc > NIR] : 0.8650
Kappa : -0.0087
Mcnemar's Test P-Value : 0.1614
Sensitivity : 0.5652
Specificity : 0.4259
Pos Pred Value : 0.4561
Neg Pred Value : 0.5349
Prevalence : 0.4600
Detection Rate : 0.2600
Detection Prevalence : 0.5700
Balanced Accuracy : 0.4956
'Positive' Class : 0
首先將二進制向量轉換為因子,
pred = factor(pred, levels = c(F,T))
truth = factor(truth, levels = c(F,T))
即使沒有某些配對的實例,這也將確保返回完整的 2x2 表。 列聯表由下式計算
table(pred, truth)
首先轉換為因子將確保沒有實例的組合在結果表中將獲得0
值。 例如,
pred = rep(T, 10)
truth = rep(F, 10)
table(pred,truth) # RETURNS A 1x1 TABLE
pred = factor(pred, levels = c(F,T))
truth = factor(truth, levels = c(F,T))
table(pred,truth) # RETURNS A 2x2 TABLE
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.