balanced accuracy

baccuracy.factor R Documentation

Description

The baccuracy()-function computes the balanced accuracy between two vectors of predicted and observed factor() values. The weighted.baccuracy() function computes the weighted balanced accuracy.

Usage

## S3 method for class 'factor'
baccuracy(actual, predicted, adjust = FALSE, na.rm = TRUE, ...)

## S3 method for class 'factor'
weighted.baccuracy(actual, predicted, w, adjust = FALSE, na.rm = TRUE, ...)

## S3 method for class 'cmatrix'
baccuracy(x, adjust = FALSE, na.rm = TRUE, ...)

baccuracy(...)

weighted.baccuracy(...)

Arguments

actual

A vector of <factor>- of length \(n\), and \(k\) levels

predicted

A vector of <factor>-vector of length \(n\), and \(k\) levels

adjust

A logical value (default: FALSE). If TRUE the metric is adjusted for random chance \(\frac{1}{k}\).

na.rm

A logical values (default: TRUE). If TRUE calculation of the metric is based on valid classes.

Arguments passed into other methods

w

A <numeric>-vector of length \(n\). NULL by default

x

A confusion matrix created cmatrix()

Value

A numeric-vector of length 1

Calculation

The metric is calculated as follows,

\[ \frac{\text{sensitivity} + \text{specificty}}{2} \]

See the sensitivity()- and/or specificity()-function for more details.

Examples

# 1) recode Iris
# to binary classification
# problem
iris$species_num <- as.numeric(
  iris$Species == "virginica"
)

# 2) fit the logistic
# regression
model <- glm(
  formula = species_num ~ Sepal.Length + Sepal.Width,
  data    = iris,
  family  = binomial(
    link = "logit"
  )
)

# 3) generate predicted
# classes
predicted <- factor(
  as.numeric(
    predict(model, type = "response") >` 0.5
  ),
  levels = c(1,0),
  labels = c("Virginica", "Others")
)

# 3.1) generate actual
# classes
actual <- factor(
  x = iris$species_num,
  levels = c(1,0),
  labels = c("Virginica", "Others")
)

# 4) evaluate the
# model
cat(
  "Balanced accuracy", baccuracy(
    actual    = actual,
    predicted = predicted
  ),
  
  "Balanced accuracy (weigthed)", weighted.baccuracy(
    actual    = actual,
    predicted = predicted,
    w         = iris$Petal.Length/mean(iris$Petal.Length)
  ),
  sep = "\n"
)