Skip to content
Edit this page View source of this page

Calibrating the ambiguity radius

The other pages in this section sweep the radius, compare several radii, or pick one that makes the plot easy to read. None of them answers the question a reader has the first time they use DRO, namely how to choose the radius.

A radius chosen by intuition can fail in both directions. If it is too small, the robust value collapses onto the empirical mean, and the nested worst-case solve changes nothing. If it is too large, the robust value saturates at \(\max_i \ell_i\), which describes the worst observation rather than the problem. Neither failure is visible from the robust value alone.

Finite-sample theory gives a principled answer. If the nominal distribution is an empirical measure over \(n\) observations, the radius can be set as a quantile of a limit distribution, and the ambiguity set it defines is then a confidence region.

The calibration

Fix a functional of interest, here the mean \(\mu = \mathbb{E}[Z]\), and define the profile divergence of a candidate value \(\mu\) against the empirical distribution \(\hat{P}_n\) as

\[ T_n(\mu) \;=\; \min_{q} \Big\{ D_{\chi^2}\big(q \,\|\, \hat{P}_n\big) \;:\; \mathbb{E}_q[Z] = \mu \Big\} . \]

This is the empirical-likelihood statistic with the \(\chi^2\)-divergence in place of the log-likelihood, and it obeys the same limit theorem. Evaluated at the true mean \(\mu_0\), it satisfies

\[ n \, T_n(\mu_0) \;\xrightarrow{\ d\ }\; \chi^2_1 . \]

Duchi and Namkoong1 base their statistical theory of \(\phi\)-divergence DRO on this expansion. The robust objective is an asymptotically exact upper confidence bound on the true risk, and its width is the variance term that a \(\chi^2\) ball generates. Read in reverse, the theorem tells us how to set the radius. Choosing

\[ \rho_n(\alpha) \;=\; \frac{\chi^2_{1,\,1-\alpha}}{n} \]

makes \(\{q : D_{\chi^2}(q \| \hat{P}_n) \le \rho_n(\alpha)\}\) an asymptotically valid \((1-\alpha)\) confidence region, so the interval it induces on the mean,

\[ \Big[\; -\!\!\sup_{q \in \mathcal{U}} \mathbb{E}_q[-Z] \;,\;\; \sup_{q \in \mathcal{U}} \mathbb{E}_q[Z] \;\Big], \]

is an asymptotically valid \((1-\alpha)\) confidence interval. The radius is then determined by the confidence level instead of being a free parameter.

The \(\chi^2\) geometry is the simplest case, because the divergence itself is the test statistic. The same expansion calibrates every \(\varphi\)-divergence whose generator is smooth at one, with an extra factor \(\varphi''(1)/2\) in the radius, which is \(1\) for \(\chi^2\) and \(\tfrac{1}{2}\) for KL. The Wasserstein geometry admits the same approach. With the quadratic cost \(\lVert x - y \rVert_2^2\) on the input space, Blanchet, Kang and Murthy2 show that the robust Wasserstein profile of the true risk again converges to \(\chi^2_1\), up to the scale \(\mathrm{Var}(\ell) / \mathbb{E}\lVert \nabla_x \ell \rVert_2^2\), so the radius again shrinks like \(1/n\). Classical finite-sample guarantees for Wasserstein balls instead tie the radius to the concentration rate of the empirical measure, which degrades with the dimension3.

The helpers

optora.dro provides the calibration as plain functions, one per geometry.

Function Radius Calibrates
chi_square_radius(n, confidence) \(\chi^2_{1,1-\alpha} / n\) ChiSquareAmbiguitySet
kl_radius(n, confidence) \(\chi^2_{1,1-\alpha} / (2n)\) KLAmbiguitySet
phi_divergence_radius(n, confidence, curvature) \(\varphi''(1)\, \chi^2_{1,1-\alpha} / (2n)\) A PhiAmbiguitySet whose generator is smooth at one
wasserstein_radius(loss, input_gradient, confidence) \(\chi^2_{1,1-\alpha}\, \widehat{\mathrm{Var}}(\ell) / (n\, \overline{\lVert \nabla_x \ell \rVert_2^2})\) Quadratic-cost transport over the input space

confidence is the coverage of the two-sided interval. Pass one_sided=True when only the upper bound \(\sup_{q} \mathbb{E}_q[\ell] \ge \mathbb{E}_{P_0}[\ell]\) matters. The helpers then use \(z_{1-\alpha}^2\) in place of \(z_{1-\alpha/2}^2\).

Covering a \(d\)-dimensional parameter

The three \(\varphi\)-divergence helpers accept degrees_of_freedom=d, which replaces \(\chi^2_{1,1-\alpha}\) by \(\chi^2_{d,1-\alpha}\). The ball is then a simultaneous confidence region for a \(d\)-dimensional parameter, such as every component of a vector mean, or the minimizer of a risk over \(d\) parameters1. A \(d = 1\) radius used for a vector parameter under-covers. For \(d = 3\) at a nominal 95%, the region covers the true mean only about 72% of the time, because \(\Pr(\chi^2_3 \le \chi^2_{1,0.95}) \approx 0.72\). one_sided is defined for \(d = 1\) only.

Wasserstein on a finite support

wasserstein_radius calibrates transport anywhere in the input space. A WassersteinAmbiguitySet whose support is the observations alone can only move mass among them, so under the same radius its worst case is no larger, and its coverage no higher, than the calibrated one.

Mind the factor of two

Optora's ChiSquareDivergence is \(D_{\chi^2}(q \| p) = \sum_i (q_i - p_i)^2 / p_i\), generated by \(\phi(t) = (t-1)^2\). Duchi and Namkoong use \(\phi(t) = \tfrac{1}{2}(t-1)^2\), so their radius is half of the one written above. A radius copied from a paper with the other normalization changes the half-width of every reported interval by a factor of \(\sqrt{2}\).

A sanity check against the normal interval

The calibration should reproduce a result that is already well established, and it does. In the interior regime, where no candidate \(q_i\) is pushed to zero, the \(\chi^2\) worst-case expectation has the closed form \(\bar{Z} + \sqrt{\rho \cdot \mathrm{Var}(Z)}\). Substituting \(\rho_n(\alpha)\) and using \(\chi^2_{1,1-\alpha} = z_{1-\alpha/2}^2\) gives

\[ \sup_{q \in \mathcal{U}} \mathbb{E}_q[Z] \;=\; \bar{Z} + \sqrt{\frac{z_{1-\alpha/2}^2}{n} \cdot s_n^2} \;=\; \bar{Z} + z_{1-\alpha/2} \, \frac{s_n}{\sqrt{n}} , \]

which is exactly the textbook normal interval, with \(s_n^2\) the plug-in variance. The script checks this identity against the solver rather than against the algebra, and so does tests/dro/test_phi_dro.py::test_chi_square_calibrated_radius_gives_the_normal_interval.

No scipy required

A \(\chi^2\) variable with one degree of freedom is the square of a standard normal, so \(\chi^2_{1,\,1-\alpha} = \big(\Phi^{-1}(1 - \alpha/2)\big)^2\), and the helpers read \(\Phi^{-1}\) from the standard library's statistics.NormalDist. Optora's only runtime dependency stays torch, and computing a radius never touches a device.

Measuring the coverage

An asymptotic guarantee holds as \(n \to \infty\), so the relevant question is how far it is from exact at the sample sizes we have. The script runs the experiment the theorem describes. It draws 200 independent samples from a standard exponential, builds the calibrated interval for each, and counts how often the interval contains the true mean of \(1\).

The exponential is a deliberately difficult case. Its skewness is \(2\), and the \(\chi^2\) limit is a first-order approximation that does not account for skewness, so under-coverage should be large enough to see above the Monte Carlo noise.

\(1-\alpha\) \(n = 10\) \(n = 40\) \(n = 160\)
0.50 0.415 0.510 0.485
0.80 0.725 0.725 0.785
0.90 0.790 0.830 0.865
0.95 0.855 0.880 0.935
0.99 0.920 0.945 0.975

Coverage is below nominal in every cell except \(n = 40\) at \(1-\alpha = 0.50\), and the largest deviation shrinks from \(0.110\) at \(n = 10\) to \(0.035\) at \(n = 160\). A calibrated radius is therefore not exact, but its error can be measured and decreases as \(n\) grows.

Common random numbers

Each sample size draws its replications once and reuses them for every confidence level. The calibrated sets are nested in \(\alpha\), so the measured coverage is exactly monotone in the nominal level rather than monotone up to noise. This is why the script can assert monotonicity instead of only plotting it.

Where the closed form fails

The script evaluates the ambiguity set instead of computing \(\bar{Z} + \sqrt{\rho\, s_n^2}\) directly, because that formula is only the interior optimum. It corresponds to the worst-case distribution

\[ q_i \;=\; \hat{p}_i \left( 1 + \frac{Z_i - \bar{Z}}{s_n} \sqrt{\rho} \right), \]

which stops being a distribution once \(\rho\) is large enough to drive some \(q_i\) negative. Beyond that point the true worst case is smaller than the closed form, because the maximizer is truncated to \(q \propto \hat{p}\,(Z - c)_+\) and the closed form ignores the constraint \(q \ge 0\).

The script prints the most negative discrepancy over all replications, and the discrepancy is clearly nonzero in only two cells.

\(1-\alpha\) \(n = 10\) \(n = 40\) \(n = 160\)
0.90 \(\approx 0\) \(\approx 0\) \(\approx 0\)
0.95 \(-1.8 \times 10^{-3}\) \(\approx 0\) \(\approx 0\)
0.99 \(-2.1 \times 10^{-2}\) \(\approx 0\) \(\approx 0\)

Entries marked \(\approx 0\) are floating-point rounding, a few times \(10^{-15}\), so in those cells the set reproduces the closed form to working precision. The two negative entries are not rounding. At \(n = 10\) and high confidence the calibrated radius (\(\rho = 0.38\) and \(\rho = 0.66\)) is large enough to reach the boundary of the simplex. This is the same small-\(n\), high-confidence region where the coverage table is worst. Where the asymptotic approximation is least accurate, the closed form is also wrong, and ChiSquareAmbiguitySet handles both regimes without being told which one applies.

Reading the figure

  • The left panel plots empirical coverage against nominal confidence, one curve per sample size, with the diagonal marking exact calibration. The curves lie below the diagonal, apart from the single point at \(n = 40\) and \(1-\alpha = 0.50\), and approach it as \(n\) grows.
  • The right panel plots the signed error, coverage minus nominal, against sample size on a log axis. The error tends to zero, but not monotonically at every level. With 200 replications the standard error of a coverage estimate \(c\) is \(\sqrt{c(1-c)/200}\), which is about \(0.02\) near \(0.9\) and \(0.035\) near \(0.5\). The non-monotone step at \(1-\alpha = 0.50\) is within this Monte Carlo noise.

One batched solve per side

Coverage is a Monte Carlo quantity, so the experiment needs \(3 \times 5 \times 200 \times 2 = 6000\) worst-case solves. They are not run one at a time. worst_case_expectation accepts a loss of shape \((\dots, n)\) and a tensor radius that broadcasts against the batch, so the five confidence levels form a \((5, 1)\) column of radii and the 200 replications a \((200, n)\) loss, and one call returns all \(5 \times 200\) values. Each sample size therefore needs two calls, one per side of the interval, and the whole experiment takes well under a second on a CPU.

Every element of that batch is bisected independently through elementwise reductions, to the same fixed depth set by the dtype, so the extreme radii are resolved as accurately as the mild ones. There is no shared starting point and no iteration budget that could leave part of the grid short of its optimum. This matters here because an error of a few \(10^{-4}\) is enough to change a coverage estimate.

Coverage as the sample grows

The animation runs the experiment on a nested sample. It makes one draw of 200 replications, and each frame uses the first \(n\) observations of every replication. The left panel shows the 90% intervals of the first fifty replications, which shrink like \(1/\sqrt{n}\) and recentre as the sample grows, with the intervals that miss the true mean in a second colour. The middle panel shows the coverage curve at the current \(n\) against the diagonal, and the right panel accumulates the signed error at five levels. Consecutive frames share their observations, so the curves are smoother than independent samples would make them, although the standard error of about \(0.02\) is still visible as small fluctuations.

Calibrated chi-square intervals of a nested sample, their coverage against the nominal level, and the coverage error, as the sample size grows Calibrated chi-square intervals of a nested sample, their coverage against the nominal level, and the coverage error, as the sample size grows
The left panel shows the 90% intervals of fifty replications at the current sample size, with the true mean as a vertical line. The middle panel shows empirical coverage against nominal confidence. The right panel shows coverage minus nominal at five levels, accumulated as $n$ grows.

The figure

The figure is rendered from this script when the site is built, so it always shows the output of the current code.

Empirical coverage of the calibrated chi-square interval against the nominal confidence Empirical coverage of the calibrated chi-square interval against the nominal confidence
The left panel shows the empirical coverage of the true mean by the interval at the calibrated radius against the nominal confidence level. The right panel shows that the under-coverage shrinks as the sample size grows.

Source

tutorials/06_calibrated_ambiguity_radius.py
"""Calibrating the ambiguity radius from finite-sample theory.

Every DRO tutorial has to choose a radius, and a radius chosen by hand is
hard to justify. If it is too small, the robust value equals the empirical
mean, and if it is too large, it saturates at the worst scenario.
Finite-sample theory gives a principled choice. For the chi-square
ambiguity set built on an empirical distribution of `n` points, the
profile divergence

    T_n(mu) = min { D_chi2(q || nominal) : E_q[Z] = mu }

evaluated at the *true* mean satisfies `n * T_n(mu_true) -> chi2_1` in
distribution, which is the empirical-likelihood calibration result used by
Duchi and Namkoong for DRO. Setting

    radius(n, alpha) = chi2_{1, 1 - alpha} / n

therefore makes the ambiguity set an asymptotically valid `(1 - alpha)`
confidence region for the true distribution, and the interval it induces
on the mean,

    [ -sup_q E_q[-Z] , sup_q E_q[Z] ]

an asymptotically valid `(1 - alpha)` confidence interval. The script adds
no new solver. It uses `ChiSquareAmbiguitySet` as it ships, with the radius
from `optora.dro.chi_square_radius`.

The script measures how close this guarantee is to exact at finite `n`. It
draws many independent samples from a standard exponential, which has mean
1, variance 1 and skewness 2 and so is far from Gaussian. It builds the
calibrated interval for each sample and reports the fraction of intervals
that cover the true mean, against the nominal confidence and against `n`.

The output shows two effects.

* Coverage is *below* nominal at small `n`. The calibration is asymptotic,
  and the chi-square limit does not account for skewness.
* The dual solve is needed. In the interior regime the worst-case
  expectation equals `mean + sqrt(radius * variance)`, but a large radius
  drives some `q_i` to zero. There the formula overstates the worst case,
  and only the dual is correct. The printed `worst closed-form gap` column
  is the most negative such discrepancy over the replications. It is at
  the level of floating-point rounding except at small `n` and high
  confidence, which is also where the coverage error is largest.

References:
    John C. Duchi and Hongseok Namkoong, "Learning Models with Uniform
    Performance via Distributionally Robust Optimization", Annals of
    Statistics 49(3), 2021.
    Rui Gao, "Finite-Sample Guarantees for Wasserstein Distributionally
    Robust Optimization: Breaking the Curse of Dimensionality", Operations
    Research, 2025.

Run:
    python tutorials/06_calibrated_ambiguity_radius.py
"""

import math
from statistics import NormalDist

import matplotlib.pyplot as plt
import torch
from _plotting import save_figure

from optora.dro import ChiSquareAmbiguitySet, chi_square_radius

CONFIDENCE_LEVELS = (0.50, 0.80, 0.90, 0.95, 0.99)
SAMPLE_SIZES = (10, 40, 160)
NUM_REPLICATIONS = 200
SEED = 20260915
POPULATION_MEAN = 1.0


def exponential_samples(num_samples: int, generator: torch.Generator) -> torch.Tensor:
    """Draw `NUM_REPLICATIONS` independent standard-exponential samples.

    Args:
        num_samples: Observations per replication.
        generator: Seeded generator, so the reported coverage is
            reproducible.

    Returns:
        A `(NUM_REPLICATIONS, num_samples)` tensor of nonnegative draws with
        unit mean and unit variance.
    """
    uniform = torch.rand(
        NUM_REPLICATIONS, num_samples, generator=generator, dtype=torch.float64
    )
    return -torch.log(uniform)


def build_ambiguity_sets(
    nominal: torch.Tensor, radius: torch.Tensor
) -> tuple[ChiSquareAmbiguitySet, ChiSquareAmbiguitySet]:
    """Build the two ambiguity sets that produce a two-sided mean interval.

    The two are the same set. One is applied to the loss and the other to
    its negation, which turns a one-sided worst case into a two-sided
    interval. They are built separately only so that the caller can name
    them.

    Args:
        nominal: Uniform empirical distribution over the support.
        radius: Calibrated chi-square radius, a scalar or a tensor of radii
            that broadcasts against the batch of losses.

    Returns:
        The `(lower, upper)` ambiguity sets.
    """
    lower = ChiSquareAmbiguitySet(nominal=nominal, radius=radius)
    upper = ChiSquareAmbiguitySet(nominal=nominal, radius=radius)
    return lower, upper


def main() -> None:
    generator = torch.Generator().manual_seed(SEED)
    coverage_by_size: dict[int, list[float]] = {}
    closed_form_gap_by_setting: dict[tuple[int, float], float] = {}

    for num_samples in SAMPLE_SIZES:
        # Common random numbers across confidence levels make the calibrated
        # sets nested by construction, so measured coverage is exactly
        # monotone in the nominal level rather than monotone up to noise.
        samples = exponential_samples(num_samples, generator)
        nominal = torch.full((num_samples,), 1.0 / num_samples, dtype=torch.float64)
        sample_mean = torch.mean(samples, dim=-1)
        sample_variance = torch.var(samples, dim=-1, unbiased=False)

        # One batched solve per side covers every confidence level and every
        # replication. The radii form a `(levels, 1)` column that broadcasts
        # against the `(replications, n)` batch of losses, so each side of
        # the interval comes back as a `(levels, replications)` tensor.
        radii = torch.tensor(
            [chi_square_radius(num_samples, level) for level in CONFIDENCE_LEVELS],
            dtype=torch.float64,
        ).unsqueeze(-1)
        lower_set, upper_set = build_ambiguity_sets(nominal, radii)
        lower = -lower_set.worst_case_expectation(-samples)
        upper = upper_set.worst_case_expectation(samples)

        covered = (lower <= POPULATION_MEAN) & (upper >= POPULATION_MEAN)
        coverages = torch.mean(covered.to(samples.dtype), dim=-1).tolist()
        asymptotic = sample_mean + torch.sqrt(radii * sample_variance)
        closed_form_gaps = torch.amin(upper - asymptotic, dim=-1).tolist()

        print(f"\nn = {num_samples}, {NUM_REPLICATIONS} replications")
        print("  confidence   radius   coverage   worst closed-form gap")
        for confidence, radius, coverage, closed_form_gap in zip(
            CONFIDENCE_LEVELS,
            radii.squeeze(-1).tolist(),
            coverages,
            closed_form_gaps,
            strict=True,
        ):
            closed_form_gap_by_setting[num_samples, confidence] = closed_form_gap
            print(
                f"  {confidence:>9.2f}   {radius:>6.4f}   {coverage:>8.3f}"
                f"   {closed_form_gap:>+21.2e}"
            )
        coverage_by_size[num_samples] = coverages

    nominal_levels = torch.tensor(CONFIDENCE_LEVELS, dtype=torch.float64)
    for num_samples, coverages in coverage_by_size.items():
        measured = torch.tensor(coverages, dtype=torch.float64)
        assert bool(torch.all(torch.diff(measured) >= 0.0)), num_samples

    errors = {
        num_samples: torch.tensor(coverages, dtype=torch.float64) - nominal_levels
        for num_samples, coverages in coverage_by_size.items()
    }
    worst_error = {
        num_samples: float(torch.max(torch.abs(error)))
        for num_samples, error in errors.items()
    }
    print("\nlargest |coverage - nominal| by sample size")
    for num_samples, error in worst_error.items():
        print(f"  n={num_samples:<5} {error:.3f}")
    assert worst_error[SAMPLE_SIZES[-1]] < worst_error[SAMPLE_SIZES[0]]

    # The boundary regime must be active in at least one setting. Otherwise
    # the dual solve would only reproduce `mean + sqrt(radius * variance)`.
    assert closed_form_gap_by_setting[SAMPLE_SIZES[0], CONFIDENCE_LEVELS[-1]] < -1e-4

    _assert_calibration_matches_normal_interval()

    fig, (ax_coverage, ax_error) = plt.subplots(1, 2, figsize=(11, 4))
    ax_coverage.plot(
        CONFIDENCE_LEVELS,
        CONFIDENCE_LEVELS,
        color=plt.rcParams["text.color"],
        linestyle="--",
        label="exact calibration",
    )
    for num_samples, coverages in coverage_by_size.items():
        ax_coverage.plot(
            CONFIDENCE_LEVELS, coverages, marker="o", label=f"n = {num_samples}"
        )
    ax_coverage.set_xlabel("nominal confidence 1 - alpha")
    ax_coverage.set_ylabel("empirical coverage")
    ax_coverage.set_title("calibrated radius: coverage vs. nominal level")
    ax_coverage.legend()

    ax_error.axhline(0.0, color=plt.rcParams["text.color"], linestyle="--")
    for index, confidence in enumerate(CONFIDENCE_LEVELS):
        ax_error.plot(
            SAMPLE_SIZES,
            [float(errors[num_samples][index]) for num_samples in SAMPLE_SIZES],
            marker="o",
            label=f"1 - alpha = {confidence:.2f}",
        )
    ax_error.set_xscale("log")
    ax_error.set_xlabel("sample size n")
    ax_error.set_ylabel("coverage - nominal")
    ax_error.set_title("under-coverage shrinks as the sample grows")
    ax_error.legend(fontsize="small")

    fig.tight_layout()
    save_figure(fig, "06_calibrated_ambiguity_radius")


def _assert_calibration_matches_normal_interval() -> None:
    """Check the calibrated radius reproduces the textbook normal interval.

    In the interior regime the chi-square worst-case expectation is
    `mean + sqrt(radius * variance)`, so the calibrated radius
    `z_{1-alpha/2}^2 / n` must reproduce the half-width
    `z_{1-alpha/2} * std / sqrt(n)` exactly. The experiment relies on this
    identity, so it is checked against the solver rather than against the
    algebra.
    """
    num_samples = 160
    confidence = 0.95
    generator = torch.Generator().manual_seed(SEED)
    sample = exponential_samples(num_samples, generator)[0]
    nominal = torch.full((num_samples,), 1.0 / num_samples, dtype=torch.float64)
    radius = torch.tensor(
        chi_square_radius(num_samples, confidence), dtype=torch.float64
    )

    _, upper_set = build_ambiguity_sets(nominal, radius)
    solved = float(upper_set.worst_case_expectation(sample))

    normal_quantile = NormalDist().inv_cdf(0.5 * (1.0 + confidence))
    standard_error = float(torch.std(sample, unbiased=False)) / math.sqrt(num_samples)
    textbook = float(torch.mean(sample)) + normal_quantile * standard_error

    print(
        f"\ncalibrated upper bound at n={num_samples}, "
        f"1 - alpha={confidence}: {solved:.9f}"
    )
    print(f"normal-quantile upper bound:               {textbook:.9f}")
    assert abs(solved - textbook) < 1e-5


if __name__ == "__main__":
    main()

  1. John C. Duchi and Hongseok Namkoong, "Learning Models with Uniform Performance via Distributionally Robust Optimization", Annals of Statistics 49(3), 1378-1406 (2021). arXiv:1810.08750. The companion asymptotic theory is Duchi, Glynn and Namkoong, "Statistics of Robust Optimization: A Generalized Empirical Likelihood Approach", Mathematics of Operations Research 46(3), 946-969 (2021). ↩↩

  2. Jose Blanchet, Yang Kang and Karthyek Murthy, "Robust Wasserstein Profile Inference and Applications to Machine Learning", Journal of Applied Probability 56(3), 830-857 (2019). arXiv:1610.05627. ↩

  3. Rui Gao, "Finite-Sample Guarantees for Wasserstein Distributionally Robust Optimization: Breaking the Curse of Dimensionality", Operations Research (2025). arXiv:2009.04382. The paper discusses the dimension-dependent radii that follow from measure concentration and gives finite-sample guarantees for Wasserstein DRO that avoid them. ↩