Created
July 9, 2020 18:41
-
-
Save phil8192/e42c85397888292f861cf3e9389217bc to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##' calculate summary statistics from a confusion matrix. | |
##' | |
##' @param cm a confusion matrix, where rows = predicted, cols = actual. | |
##' @param dp round decimal place (default 2). | |
##' @return a classification report, similar to sklean. | |
##' @examples | |
##' \dontrun{ | |
##' # 3 classes. | |
##' cm <- matrix(c(4, 6, 3, 1, 2, 0, 1, 2, 6), ncol=3, byrow=T) | |
##' cr(cm) | |
##' | |
##' $summary | |
##' tp tn fp fn precision recall f1_score support | |
##' 1 4 10 9 2 0.31 0.67 0.42 6 | |
##' 2 2 14 1 8 0.67 0.20 0.31 10 | |
##' 3 6 13 3 3 0.67 0.67 0.67 9 | |
##' | |
##' $accuracy | |
##' [1] 0.48 | |
##' | |
##' $support | |
##' [1] 25 | |
##' | |
##' } | |
cr <- function(cm, dp=2) { | |
ct <- sum(cm) | |
cs <- colSums(cm) | |
rs <- rowSums(cm) | |
tp <- diag(cm) | |
tn <- ct - (rs + cs - tp) | |
fp <- rs - tp | |
fn <- cs - tp | |
pr <- tp / (tp + fp) | |
re <- tp / (tp + fn) | |
f1 <- 2 * pr * re / (pr + re) | |
ac <- sum(tp) / ct | |
list(summary=round(data.frame(tp, tn, fp, fn, precision=pr, recall=re, f1_score=f1, support=cs), dp), | |
accuracy=round(ac, dp), | |
support=ct) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment