BalancedAccuracy.lean

Lean 4 source, lean/DataMiningAsObservation/BalancedAccuracy.lean at commit bccca4f. Appendix C, Machine-checked statements, says what each file proves. All Lean files.

/-
BalancedAccuracy.lean. Equation 0.34, balanced accuracy.

Balanced accuracy is the mean of the per-class recalls, so it lies between the worst and
the best class. Plain accuracy is the size-weighted mean of the same recalls, so a large
class can hide a small one. With a class of 990 rows recalled perfectly and a class of 10
rows never recalled, accuracy is 0.99 and balanced accuracy is 0.5.
-/
import Mathlib

namespace DMO.BalancedAccuracy

open Finset

variable {κ : Type*}

/-- **Equation 0.34.** The mean of the per-class recalls over the classes `C`. -/
noncomputable def balanced (C : Finset κ) (r : κ → ℝ) : ℝ := (∑ c ∈ C, r c) / C.card

/-- Plain accuracy, the size-weighted mean of the per-class recalls. -/
noncomputable def accuracy (C : Finset κ) (n r : κ → ℝ) : ℝ :=
  (∑ c ∈ C, n c * r c) / ∑ c ∈ C, n c

/-- **Balanced accuracy is at least the worst class.** -/
theorem min_le_balanced (C : Finset κ) (hC : C.Nonempty) (r : κ → ℝ) :
    C.inf' hC r ≤ balanced C r := by
  unfold balanced
  have hpos : (0 : ℝ) < C.card := by exact_mod_cast hC.card_pos
  rw [le_div_iff₀ hpos]
  calc C.inf' hC r * C.card = ∑ _c ∈ C, C.inf' hC r := by
        rw [Finset.sum_const, nsmul_eq_mul, mul_comm]
    _ ≤ ∑ c ∈ C, r c := Finset.sum_le_sum fun c hc => Finset.inf'_le r hc

/-- **Balanced accuracy is at most the best class.** -/
theorem balanced_le_max (C : Finset κ) (hC : C.Nonempty) (r : κ → ℝ) :
    balanced C r ≤ C.sup' hC r := by
  unfold balanced
  have hpos : (0 : ℝ) < C.card := by exact_mod_cast hC.card_pos
  rw [div_le_iff₀ hpos]
  calc ∑ c ∈ C, r c ≤ ∑ _c ∈ C, C.sup' hC r :=
        Finset.sum_le_sum fun c hc => Finset.le_sup' r hc
    _ = C.sup' hC r * C.card := by rw [Finset.sum_const, nsmul_eq_mul, mul_comm]

/-- **A large class hides a small one in plain accuracy.** Two classes, 990 rows recalled
perfectly and 10 rows never recalled, give accuracy 0.99 and balanced accuracy 0.5. -/
theorem hidden_class :
    accuracy ({0, 1} : Finset (Fin 2)) (![990, 10]) (![1, 0]) = 0.99 ∧
      balanced ({0, 1} : Finset (Fin 2)) (![1, 0]) = 0.5 := by
  unfold accuracy balanced
  constructor
  · simp [Finset.sum_insert, Finset.sum_singleton]
    norm_num
  · simp [Finset.sum_insert, Finset.sum_singleton]
    norm_num

end DMO.BalancedAccuracy