# `Nous.Eval.Stats.Classifier`
[🔗](https://github.com/nyo16/nous/blob/v0.21.1/lib/nous/eval/stats/classifier.ex#L1)

Binary classifier metrics for guards and judges.

"Positive" means the item should be flagged (for a guard: should be
blocked). Labels are booleans (`true` = positive). Scored items are
`{score, positive?}` tuples; an item is predicted positive at threshold `t`
when `score >= t`.

Rates whose denominator is zero (precision with no predicted positives,
recall with no positives, FPR with no negatives) are `nil`, never NaN.
Curve functions return one point per distinct score, in descending
threshold order; the "flag nothing" operating point, where needed, has
`threshold: nil`.

For guard reports pair the false-allow rate (`fnr`) with the false-block
rate (`fpr`), attach Wilson intervals (`Nous.Eval.Stats.wilson/3`) to both,
and re-estimate precision at the production prevalence with
`prevalence_adjusted/3`: precision measured on a balanced corpus does not
transfer.

# `counts`

```elixir
@type counts() :: %{
  tp: non_neg_integer(),
  fp: non_neg_integer(),
  tn: non_neg_integer(),
  fn: non_neg_integer()
}
```

# `metrics`

```elixir
@type metrics() :: %{
  precision: float() | nil,
  recall: float() | nil,
  fnr: float() | nil,
  fpr: float() | nil,
  specificity: float() | nil,
  accuracy: float() | nil,
  prevalence: float() | nil,
  f_beta: float() | nil,
  beta: float()
}
```

# `scored`

```elixir
@type scored() :: [{number(), boolean()}]
```

# `average_precision`

```elixir
@spec average_precision(scored()) ::
  {:ok, float()} | {:error, :no_positives | :invalid_values}
```

Average precision, `Σ_n (R_n − R_{n−1})·P_n` over the PR points in
descending threshold order (the step-wise area without interpolation;
the definition of scikit-learn's `average_precision_score`). Llama Guard
reports it (AUPRC) as its primary metric.

Needs at least one positive (`{:error, :no_positives}`).

## Examples

    iex> Nous.Eval.Stats.Classifier.average_precision([{0.9, true}, {0.8, false}, {0.7, true}, {0.1, false}])
    {:ok, 0.8333333333333333}

# `confusion`

```elixir
@spec confusion([{boolean(), boolean()}]) ::
  {:ok, counts()} | {:error, :invalid_values}
```

Confusion counts from `{predicted?, actual?}` boolean pairs. An empty list
gives all-zero counts.

## Examples

    iex> Nous.Eval.Stats.Classifier.confusion([{true, true}, {true, false}, {false, false}, {false, true}, {true, true}])
    {:ok, %{tp: 2, fp: 1, tn: 1, fn: 1}}

# `confusion_at`

```elixir
@spec confusion_at(scored(), number()) :: {:ok, counts()} | {:error, :invalid_values}
```

Confusion counts of scored items at `threshold` (`score >= threshold` is
predicted positive).

# `cost_weighted_threshold`

```elixir
@spec cost_weighted_threshold(scored(), keyword()) ::
  {:ok,
   %{
     threshold: number() | nil,
     expected_cost: float(),
     recall: float(),
     fpr: float()
   }}
  | {:error,
     :single_class
     | :invalid_values
     | {:invalid_option, :cost_fp | :cost_fn | :prevalence}}
```

Threshold minimising the expected misclassification cost per item,
`cost_fn·π·FNR + cost_fp·(1 − π)·FPR`, over every distinct score and the
"flag nothing" point (`threshold: nil`). Ties go to the higher threshold.

Options:

  * `:cost_fp` - cost of a false positive (false block), default `1.0`
  * `:cost_fn` - cost of a false negative (false allow), default `1.0`
  * `:prevalence` - expected production share of positives π in
    `[0, 1]`; defaults to the share in `scored`

Needs both classes.

## Examples

    iex> scored = [{0.9, true}, {0.8, false}, {0.7, true}, {0.1, false}]
    iex> {:ok, r} = Nous.Eval.Stats.Classifier.cost_weighted_threshold(scored, cost_fn: 5.0)
    iex> {r.threshold, r.expected_cost}
    {0.7, 0.25}

# `metrics`

```elixir
@spec metrics(counts(), keyword()) ::
  {:ok, metrics()} | {:error, :invalid_counts | {:invalid_option, :beta}}
```

Rates from confusion counts: precision, recall (TPR), false-negative rate
(`fnr`, a guard's false-allow rate), false-positive rate (`fpr`, a guard's
false-block rate), specificity, accuracy, prevalence and F-beta.

F-beta is `(1 + β²)·P·R / (β²·P + R)`; `nil` when precision or recall is
undefined and `0.0` when both are zero.

Options: `:beta` (> 0, default `1.0`).

## Examples

    iex> {:ok, m} = Nous.Eval.Stats.Classifier.metrics(%{tp: 8, fp: 2, tn: 85, fn: 5})
    iex> {m.precision, m.recall, Float.round(m.f_beta, 4)}
    {0.8, 0.6153846153846154, 0.6957}

# `pr_curve`

```elixir
@spec pr_curve(scored()) ::
  {:ok, [%{threshold: number(), precision: float(), recall: float()}]}
  | {:error, :no_positives | :invalid_values}
```

Precision–recall points `%{threshold, precision, recall}`, one per distinct
score in descending order.

Needs at least one positive (`{:error, :no_positives}`).

# `prevalence_adjusted`

```elixir
@spec prevalence_adjusted(number(), number(), number()) ::
  {:ok, %{ppv: float() | nil, npv: float() | nil}}
  | {:error, {:invalid_option, :tpr | :fpr | :prevalence}}
```

Predictive values re-estimated at prevalence `π` from the
prevalence-independent rates TPR (recall) and FPR:

`PPV(π) = TPR·π / (TPR·π + FPR·(1 − π))`,
`NPV(π) = (1 − FPR)(1 − π) / ((1 − FPR)(1 − π) + (1 − TPR)·π)`.

A value whose denominator is zero is `nil`. For a conservative interval,
plug the Wilson bounds of TPR and FPR into these monotone formulas.

## Examples

    iex> {:ok, r} = Nous.Eval.Stats.Classifier.prevalence_adjusted(0.9, 0.05, 0.01)
    iex> Float.round(r.ppv, 3)
    0.154

# `recall_at_fpr`

```elixir
@spec recall_at_fpr(scored(), number()) ::
  {:ok, %{recall: float(), fpr: float(), threshold: number() | nil}}
  | {:error, :single_class | :invalid_values | {:invalid_option, :max_fpr}}
```

Highest recall reachable with a false-positive rate of at most `max_fpr`,
and the highest threshold that reaches it (Prompt Guard 2 reports
"Recall @ 1% FPR").

FPR moves in steps of `1 / negatives`: with fewer than `1 / max_fpr`
negatives the only admissible point may be "flag nothing"
(`threshold: nil`, `recall: 0.0`). Needs both classes.

## Examples

    iex> scored = [{0.9, true}, {0.8, false}, {0.7, true}, {0.1, false}]
    iex> Nous.Eval.Stats.Classifier.recall_at_fpr(scored, 0.5)
    {:ok, %{recall: 1.0, fpr: 0.5, threshold: 0.7}}

# `roc_auc`

```elixir
@spec roc_auc(scored()) :: {:ok, float()} | {:error, :single_class | :invalid_values}
```

Area under the ROC curve in its rank (Mann–Whitney) form: the probability
that a random positive scores above a random negative, ties counting ½
(mid-ranks).

Needs at least one positive and one negative (`{:error, :single_class}`).

## Examples

    iex> Nous.Eval.Stats.Classifier.roc_auc([{0.9, true}, {0.8, false}, {0.7, true}, {0.1, false}])
    {:ok, 0.75}

# `roc_curve`

```elixir
@spec roc_curve(scored()) ::
  {:ok, [%{threshold: number() | nil, tpr: float(), fpr: float()}]}
  | {:error, :single_class | :invalid_values}
```

ROC points `%{threshold, tpr, fpr}` from the "flag nothing" point
(`threshold: nil`, `tpr: 0.0`, `fpr: 0.0`) down to the lowest score.

Needs both classes (`{:error, :single_class}`).

# `threshold_sweep`

```elixir
@spec threshold_sweep(scored(), keyword()) ::
  {:ok, [map()]} | {:error, :empty | :invalid_values | {:invalid_option, :beta}}
```

Confusion counts and rates at every distinct score threshold, highest
first. Each entry has `:threshold`, `:tp`, `:fp`, `:tn`, `:fn` and the
`metrics/2` keys `:precision`, `:recall`, `:fpr`, `:f_beta`.

Single-class data is allowed (the undefined rates are `nil`).

Options: `:beta` (default `1.0`).

---

*Consult [api-reference.md](api-reference.md) for complete listing*
