PrecisionRecall.lean

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

/-
PrecisionRecall.lean. Equation 0.28, precision, recall, and F1.

Precision is the fraction of predicted positives that are truly positive and recall is the
fraction of true positives that were predicted. Both lie in the unit interval. F1 is their
harmonic mean, which lies between the smaller of the two and their arithmetic mean, equals
both when they agree, and is zero when either is zero. In counts, F1 is twice the true
positives over twice the true positives plus the false positives and false negatives, the
form the Youden file uses.
-/
import Mathlib

namespace DMO.PrecisionRecall

/-- Precision from counts. -/
noncomputable def precision (tp fp : ℝ) : ℝ := tp / (tp + fp)

/-- Recall from counts. -/
noncomputable def recallOf (tp fn : ℝ) : ℝ := tp / (tp + fn)

/-- **Equation 0.28.** F1 as the harmonic mean of precision and recall. -/
noncomputable def f1 (P R : ℝ) : ℝ := 2 * P * R / (P + R)

/-- **Precision and recall lie in the unit interval.** -/
theorem precision_mem_unit (tp fp : ℝ) (htp : 0 ≤ tp) (hfp : 0 ≤ fp) (hpos : 0 < tp + fp) :
    0 ≤ precision tp fp ∧ precision tp fp ≤ 1 := by
  unfold precision
  refine ⟨div_nonneg htp hpos.le, ?_⟩
  rw [div_le_one hpos]; linarith

theorem recall_mem_unit (tp fn : ℝ) (htp : 0 ≤ tp) (hfn : 0 ≤ fn) (hpos : 0 < tp + fn) :
    0 ≤ recallOf tp fn ∧ recallOf tp fn ≤ 1 := by
  unfold recallOf
  refine ⟨div_nonneg htp hpos.le, ?_⟩
  rw [div_le_one hpos]; linarith

/-- **F1 is at most the arithmetic mean** of precision and recall. -/
theorem f1_le_mean (P R : ℝ) (hpos : 0 < P + R) :
    f1 P R ≤ (P + R) / 2 := by
  unfold f1
  rw [div_le_div_iff₀ hpos (by norm_num)]
  nlinarith [sq_nonneg (P - R)]

/-- **F1 is at least the smaller** of precision and recall. -/
theorem min_le_f1 (P R : ℝ) (hP : 0 ≤ P) (hR : 0 ≤ R) (hpos : 0 < P + R) :
    min P R ≤ f1 P R := by
  unfold f1
  rw [le_div_iff₀ hpos]
  rcases le_total P R with h | h
  · rw [min_eq_left h]; nlinarith
  · rw [min_eq_right h]; nlinarith

/-- **F1 equals precision and recall when they agree.** -/
theorem f1_self (P : ℝ) (hP : 0 < P) : f1 P P = P := by
  unfold f1
  field_simp
  ring

/-- **F1 is zero when either is zero.** -/
theorem f1_zero (R : ℝ) : f1 0 R = 0 := by
  simp [f1]

/-- **The counts form.** With `tp` true positives, `fp` false positives, and `fn` false
negatives, F1 is `2 tp / (2 tp + fp + fn)`. -/
theorem f1_counts (tp fp fn : ℝ) (htp : 0 < tp) (hfp : 0 ≤ fp) (hfn : 0 ≤ fn) :
    f1 (precision tp fp) (recallOf tp fn) = 2 * tp / (2 * tp + fp + fn) := by
  unfold f1 precision recallOf
  have h1 : tp + fp ≠ 0 := by linarith
  have h2 : tp + fn ≠ 0 := by linarith
  have h3 : 2 * tp + fp + fn ≠ 0 := by linarith
  field_simp
  ring

end DMO.PrecisionRecall