R/metrics.R

Defines functions f1_aggregate cm_metrics

Documented in cm_metrics f1_aggregate

#' @title Metrics from a confusion matrix
#' @description Metrics of a batch from the counts of its confusion matrix, vectorised over
#' batches. A metric whose denominator is zero comes back as `NA`.
#' @param TP True positives, one value per batch.
#' @param FP False positives, one value per batch.
#' @param TN True negatives, one value per batch.
#' @param FN False negatives, one value per batch.
#' @return A list with `accuracy`, `precision`, `recall` and `f1`, one value per batch.
#' @examples
#' cm_metrics(TP = 8, FP = 2, TN = 85, FN = 5)
#' @export
cm_metrics <- function(TP, FP, TN, FN) {
  precision <- ifelse(TP + FP > 0, TP / (TP + FP), NA_real_)
  recall    <- ifelse(TP + FN > 0, TP / (TP + FN), NA_real_)
  list(
    accuracy  = (TP + TN) / (TP + TN + FP + FN),
    precision = precision,
    recall    = recall,
    f1        = ifelse(!is.na(precision) & !is.na(recall) & precision + recall > 0,
                       2 * precision * recall / (precision + recall), NA_real_)
  )
}

#' @title Aggregate F1
#' @description Sums the confusion matrices of several batches and computes the F1 once. Batches
#' therefore weigh by their number of positives, not equally, which is how the F1 of a scenario is
#' reported.
#' @param TP True positives, one value per batch.
#' @param FP False positives, one value per batch.
#' @param FN False negatives, one value per batch.
#' @return The aggregate F1, or `NA` when no batch has a positive, real or predicted.
#' @examples
#' f1_aggregate(TP = c(8, 6), FP = c(2, 3), FN = c(5, 4))
#' @export
f1_aggregate <- function(TP, FP, FN) {
  den <- 2 * sum(TP) + sum(FP) + sum(FN)
  if (den > 0) 2 * sum(TP) / den else NA_real_
}

# The per-batch F1 is `mt_fscore(f = 1)` (see ac_metrics.R): computed from the confusion-matrix counts,
# it returns 0 when a concept gets all positives wrong and NA only when a batch has no positive at all —
# the behaviour the error-based and hybrid selectors need. The former `mt_f1()` was merged into it.

Try the heimdall package in your browser

Any scripts or data that you put into this service are public.

heimdall documentation built on Dec. 2, 2026, 5:08 p.m.