Nous.Eval.Stats (nous v0.21.1)

Copy Markdown View Source

Statistics for evaluation runs, hand-rolled in pure Elixir (no Nx, no NIFs).

This module holds descriptive statistics, standard errors, proportion intervals, the pass@k / pass^k estimators and inter-rater agreement (Cohen's κ, unweighted and weighted). The rest lives in submodules:

Conventions

  • Every data-facing function returns {:ok, result} or {:error, reason}. They never raise on empty or degenerate data and never return NaN or infinities; undefined quantities are nil and are documented per function.
  • Interval results are maps with :estimate and :ci ({lower, upper}).
  • :confidence options are two-sided levels in (0, 1), default 0.95.
  • The unit of analysis is the case. With k samples per case, reduce each case to its mean first (or use clustered_se/1 with one cluster per case); pooling all samples as independent understates the error (Miller 2024, "Adding Error Bars to Evals", §3.1).

Which interval for what

Quantityn ≥ ~100 casesn < ~100 cases
Single proportion (pass rate, FPR, recall)wilson/3wilson/3; jeffreys/3 or beta_posterior/3 as options
Mean of fractional per-case scoresmean_ci/2Nous.Eval.Stats.Bootstrap.paired_cluster/2, flagged "small n"
Paired Δ, binary per caseNous.Eval.Stats.Hypothesis.mcnemar/2, Nous.Eval.Stats.Hypothesis.tango_ci/4same
Paired Δ, fractional per casepaired_se/2 or the paired cluster bootstrapNous.Eval.Stats.Bootstrap.paired_cluster/2, flagged "small n"

Intervals based on the normal approximation (and percentile bootstrap) undercover below a few hundred cases (Bowyer et al. 2025); Wilson and the Beta intervals keep nominal coverage for single proportions.

Summary

Types

A two-sided interval {lower, upper}.

An interval estimate.

Reasons returned by the validating functions of Nous.Eval.Stats.*.

Functions

Beta-Bernoulli posterior for a pass rate: Beta(a₀ + successes, b₀ + n − successes), its mean (:estimate) and equal-tailed credible interval (:ci). The default prior {1, 1} is uniform (Bowyer et al. 2025, eq. 7).

Clopper–Pearson ("exact") interval from Beta quantiles. Conservative: coverage is at least nominal. The lower bound is 0.0 when successes == 0 and the upper bound is 1.0 when successes == n.

Mean and cluster-robust standard error of the mean of all observations, where each inner list is one cluster.

Cohen's κ for two raters labelling the same items (e.g. a human and an LLM judge). pairs is a list of {label_a, label_b}, one per item; labels are any terms.

Mean, sample variance, standard deviation and standard error of the mean, computed in one pass with Welford's algorithm.

Jeffreys interval: equal-tailed quantiles of Beta(successes + ½, n − successes + ½). Close to nominal coverage with shorter intervals than Clopper–Pearson.

Student-t confidence interval for the mean of per-case values (Inspect's ci() style), with n - 1 degrees of freedom.

Paired difference of per-case values (Miller eq. 7): d_i = candidate_i - baseline_i, mean difference and SE = sd(d) / √n.

Unbiased pass@k for one case with n samples of which c passed: the probability that at least one of k samples drawn without replacement passes, 1 − C(n−c, k) / C(n, k) (Chen et al. 2021, "Evaluating Large Language Models Trained on Code", eq. 1).

Unbiased pass^k for one case (τ-bench, Yao et al. 2024, §3): the probability that all k samples drawn without replacement pass, C(c, k) / C(n, k) = Π_{i=0}^{k−1} (c − i)/(n − i). Measures reliability, where pass@k measures capability; pass^1 == pass@1 == c/n.

Sample quantile at probability p (0 <= p <= 1), linear interpolation between order statistics (Hyndman–Fan type 7; R and NumPy default).

Several type-7 quantiles of one list (sorts once). See quantile/2.

Weighted Cohen's κ for ordinal labels (e.g. a 1–5 Likert scale), with the labels' order given by labels. :weights is :quadratic (default) or :linear. Same results and errors as cohen_kappa/2.

Wilson score interval for successes out of n trials.

Types

ci()

@type ci() :: {float(), float()}

A two-sided interval {lower, upper}.

error()

@type error() :: {:error, reason()}

interval()

@type interval() :: %{estimate: float(), ci: ci()}

An interval estimate.

reason()

@type reason() ::
  :empty
  | :insufficient_data
  | :insufficient_clusters
  | :length_mismatch
  | :invalid_values
  | :invalid_counts
  | :invalid_confidence
  | :invalid_k
  | :k_exceeds_n
  | {:invalid_option, atom()}

Reasons returned by the validating functions of Nous.Eval.Stats.*.

Functions

beta_posterior(successes, n, opts \\ [])

@spec beta_posterior(non_neg_integer(), non_neg_integer(), keyword()) ::
  {:ok, %{estimate: float(), ci: ci(), posterior: {number(), number()}}}
  | {:error, :invalid_counts | :invalid_confidence | {:invalid_option, :prior}}

Beta-Bernoulli posterior for a pass rate: Beta(a₀ + successes, b₀ + n − successes), its mean (:estimate) and equal-tailed credible interval (:ci). The default prior {1, 1} is uniform (Bowyer et al. 2025, eq. 7).

n == 0 is allowed and returns the prior.

Options: :confidence (credible mass, default 0.95), :prior ({a₀, b₀}, both > 0, default {1, 1}).

Examples

iex> {:ok, r} = Nous.Eval.Stats.beta_posterior(8, 10)
iex> {r.posterior, Float.round(r.estimate, 4)}
{{9, 3}, 0.75}

clopper_pearson(successes, n, opts \\ [])

@spec clopper_pearson(non_neg_integer(), non_neg_integer(), keyword()) ::
  {:ok, interval()} | {:error, :empty | :invalid_counts | :invalid_confidence}

Clopper–Pearson ("exact") interval from Beta quantiles. Conservative: coverage is at least nominal. The lower bound is 0.0 when successes == 0 and the upper bound is 1.0 when successes == n.

For a one-sided upper bound at level 1 - α (e.g. "0 false positives in n benign items"), ask for the two-sided confidence: 1 - 2α and read the upper bound.

Returns {:error, :empty} when n == 0. Options: :confidence.

Examples

iex> {:ok, r} = Nous.Eval.Stats.clopper_pearson(0, 100, confidence: 0.90)
iex> r.ci |> elem(1) |> Float.round(4)
0.0295

clustered_se(clusters)

@spec clustered_se([[number()]]) ::
  {:ok,
   %{mean: float(), se: float(), n: pos_integer(), clusters: pos_integer()}}
  | {:error, :insufficient_clusters | :invalid_values}

Mean and cluster-robust standard error of the mean of all observations, where each inner list is one cluster.

Use one cluster per case with its k sample scores ("cluster = case, samples = k"), or one cluster per scenario/template with per-case means. For a paired, clustered comparison pass the per-case differences grouped by cluster (Miller eq. 8).

The variance is the CR1 sandwich estimator of an intercept-only model, G/(G-1) · Σ_c (Σ_i (s_ic − s̄))² / N² (what statsmodels' cov_type="cluster" computes). With singleton clusters it equals the ordinary standard error; with equal-size clusters it equals the standard error of the cluster means, so the case stays the unit of analysis.

Needs at least two non-empty clusters ({:error, :insufficient_clusters}). Empty inner lists are ignored.

Examples

iex> {:ok, r} = Nous.Eval.Stats.clustered_se([[1, 1, 0], [0, 0, 0], [1, 1, 1]])
iex> {r.n, r.clusters, Float.round(r.mean, 6), Float.round(r.se, 6)}
{9, 3, 0.555556, 0.293972}

cohen_kappa(pairs, opts \\ [])

@spec cohen_kappa([{term(), term()}], keyword()) ::
  {:ok, float() | nil}
  | {:error, :empty | :invalid_values | {:invalid_option, :labels | :weights}}

Cohen's κ for two raters labelling the same items (e.g. a human and an LLM judge). pairs is a list of {label_a, label_b}, one per item; labels are any terms.

κ = 1 − Σ w·O / Σ w·E, where O is the observed confusion matrix, E the matrix expected by chance from the two raters' label frequencies, and w the disagreement weight of each cell. Matches scikit-learn's cohen_kappa_score.

Options

  • :labels - the label set, in order (default: every label seen, sorted). A pair with a label outside it is {:error, :invalid_values}. For weighted κ the position in this list is the label's rank
  • :weights - nil (default, unweighted: every disagreement weighs 1), :linear (|i − j|) or :quadratic ((i − j)²). Weighted κ needs an explicit :labels order ({:error, {:invalid_option, :labels}} otherwise); see weighted_kappa/3

Returns {:ok, nil} when κ is undefined: the chance disagreement Σ w·E is zero, as when both raters give every item the same single label (scikit-learn returns NaN). {:error, :empty} for no pairs, {:error, :invalid_values} for an element that is not a 2-tuple.

Examples

iex> {:ok, k} = Nous.Eval.Stats.cohen_kappa([{"pass", "pass"}, {"pass", "fail"}, {"fail", "fail"}, {"fail", "fail"}])
iex> Float.round(k, 4)
0.5

describe(values)

@spec describe([number()]) ::
  {:ok,
   %{
     n: pos_integer(),
     mean: float(),
     variance: float() | nil,
     sd: float() | nil,
     se: float() | nil
   }}
  | {:error, :empty | :invalid_values}

Mean, sample variance, standard deviation and standard error of the mean, computed in one pass with Welford's algorithm.

:variance, :sd and :se use the n - 1 denominator and are nil when n == 1. Returns {:error, :empty} for [] and {:error, :invalid_values} if any element is not a number.

Examples

iex> Nous.Eval.Stats.describe([1, 2, 3, 4])
{:ok, %{n: 4, mean: 2.5, variance: 1.6666666666666667, sd: 1.2909944487358056, se: 0.6454972243679028}}

iex> Nous.Eval.Stats.describe([0.5])
{:ok, %{n: 1, mean: 0.5, variance: nil, sd: nil, se: nil}}

jeffreys(successes, n, opts \\ [])

@spec jeffreys(non_neg_integer(), non_neg_integer(), keyword()) ::
  {:ok, interval()} | {:error, :empty | :invalid_counts | :invalid_confidence}

Jeffreys interval: equal-tailed quantiles of Beta(successes + ½, n − successes + ½). Close to nominal coverage with shorter intervals than Clopper–Pearson.

Returns {:error, :empty} when n == 0. Options: :confidence.

Examples

iex> {:ok, r} = Nous.Eval.Stats.jeffreys(5, 10)
iex> Tuple.to_list(r.ci) |> Enum.map(&Float.round(&1, 4))
[0.2235, 0.7765]

mean_ci(values, opts \\ [])

@spec mean_ci([number()], keyword()) ::
  {:ok, %{estimate: float(), se: float(), df: pos_integer(), ci: ci()}}
  | {:error,
     :empty | :insufficient_data | :invalid_values | :invalid_confidence}

Student-t confidence interval for the mean of per-case values (Inspect's ci() style), with n - 1 degrees of freedom.

Needs at least two values ({:error, :insufficient_data} otherwise). Constant data gives a zero-width interval.

Options: :confidence (default 0.95).

Examples

iex> {:ok, r} = Nous.Eval.Stats.mean_ci([0.2, 0.4, 0.6, 0.8])
iex> {Float.round(r.estimate, 6), r.df, Tuple.to_list(r.ci) |> Enum.map(&Float.round(&1, 6))}
{0.5, 3, [0.089148, 0.910852]}

paired_se(candidate, baseline)

@spec paired_se([number()], [number()]) ::
  {:ok,
   %{
     n: pos_integer(),
     mean_difference: float(),
     se: float(),
     correlation: float() | nil
   }}
  | {:error, :length_mismatch | :insufficient_data | :invalid_values | :empty}

Paired difference of per-case values (Miller eq. 7): d_i = candidate_i - baseline_i, mean difference and SE = sd(d) / √n.

Both lists hold one value per case in the same case order. :correlation is the Pearson correlation between the two runs (Miller reports it next to Δ); it is nil when either run is constant.

Needs at least two cases.

Examples

iex> {:ok, r} = Nous.Eval.Stats.paired_se([0.9, 0.8, 0.7, 1.0], [0.8, 0.8, 0.5, 0.9])
iex> {r.n, Float.round(r.mean_difference, 6), Float.round(r.se, 6)}
{4, 0.1, 0.040825}

pass_at_k(n, c, k)

@spec pass_at_k(non_neg_integer(), non_neg_integer(), pos_integer()) ::
  {:ok, float()} | {:error, :invalid_counts | :invalid_k | :k_exceeds_n}

Unbiased pass@k for one case with n samples of which c passed: the probability that at least one of k samples drawn without replacement passes, 1 − C(n−c, k) / C(n, k) (Chen et al. 2021, "Evaluating Large Language Models Trained on Code", eq. 1).

Uses the numerically stable product 1 − Π_{i=n−c+1}^{n} (1 − k/i), so no binomial coefficients are formed. The plug-in 1 − (1 − c/n)^k is biased and is not used.

Requires 1 <= k <= n and 0 <= c <= n ({:error, :k_exceeds_n}, {:error, :invalid_k}, {:error, :invalid_counts}).

Examples

iex> Nous.Eval.Stats.pass_at_k(10, 3, 1)
{:ok, 0.30000000000000004}

iex> Nous.Eval.Stats.pass_at_k(5, 3, 3)
{:ok, 1.0}

pass_hat_k(n, c, k)

@spec pass_hat_k(non_neg_integer(), non_neg_integer(), pos_integer()) ::
  {:ok, float()} | {:error, :invalid_counts | :invalid_k | :k_exceeds_n}

Unbiased pass^k for one case (τ-bench, Yao et al. 2024, §3): the probability that all k samples drawn without replacement pass, C(c, k) / C(n, k) = Π_{i=0}^{k−1} (c − i)/(n − i). Measures reliability, where pass@k measures capability; pass^1 == pass@1 == c/n.

Same argument rules as pass_at_k/3.

Examples

iex> Nous.Eval.Stats.pass_hat_k(4, 3, 2)
{:ok, 0.5}

iex> Nous.Eval.Stats.pass_hat_k(4, 1, 2)
{:ok, 0.0}

quantile(values, p)

@spec quantile([number()], number()) ::
  {:ok, float()} | {:error, :empty | :invalid_values | {:invalid_option, :p}}

Sample quantile at probability p (0 <= p <= 1), linear interpolation between order statistics (Hyndman–Fan type 7; R and NumPy default).

Examples

iex> Nous.Eval.Stats.quantile([4, 1, 3, 2], 0.5)
{:ok, 2.5}

quantiles(values, ps)

@spec quantiles([number()], [number()]) ::
  {:ok, [float()]} | {:error, :empty | :invalid_values | {:invalid_option, :p}}

Several type-7 quantiles of one list (sorts once). See quantile/2.

weighted_kappa(pairs, labels, opts \\ [])

@spec weighted_kappa([{term(), term()}], [term()], keyword()) ::
  {:ok, float() | nil}
  | {:error, :empty | :invalid_values | {:invalid_option, :labels | :weights}}

Weighted Cohen's κ for ordinal labels (e.g. a 1–5 Likert scale), with the labels' order given by labels. :weights is :quadratic (default) or :linear. Same results and errors as cohen_kappa/2.

Examples

iex> {:ok, k} = Nous.Eval.Stats.weighted_kappa([{1, 1}, {2, 3}, {3, 3}, {4, 5}, {5, 5}], [1, 2, 3, 4, 5])
iex> Float.round(k, 4)
0.9091

wilson(successes, n, opts \\ [])

@spec wilson(non_neg_integer(), non_neg_integer(), keyword()) ::
  {:ok, interval()} | {:error, :empty | :invalid_counts | :invalid_confidence}

Wilson score interval for successes out of n trials.

The recommended default for single proportions at any n. Returns {:error, :empty} when n == 0. Bounds are clamped to [0, 1].

Options: :confidence (default 0.95).

Examples

iex> {:ok, r} = Nous.Eval.Stats.wilson(33, 41)
iex> Tuple.to_list(r.ci) |> Enum.map(&Float.round(&1, 3))
[0.66, 0.898]