Skip to content
Edit this page View source of this page

Examples

Each example is one short script that shows one part of Optora. It runs on a plain pip install optora, and a script that uses a recent component says from which version. It prints the numbers it computes and checks them against a closed form or an independent computation, so a script that runs to the end has verified its own output. CI runs every script on Linux, macOS and Windows.

The scripts live under examples/ in the repository, one folder per group. For longer experiments that combine several components and discuss the results, see the Tutorials.

python examples/01_divergences/01_phi_divergences.py

Divergences

Example What it shows
Phi-divergences Evaluate the KL, chi-square and total-variation divergences, define a new one (the squared Hellinger distance) from its convex generator with PhiDivergence, and compare a whole batch of candidates in one call.
Sinkhorn divergence Build a ground cost on a one-dimensional grid, evaluate the debiased SinkhornDivergence for decreasing entropic strength, and watch it approach the exact type-1 Wasserstein distance, which on the real line is the area between the two cumulative distribution functions.
Maximum mean discrepancy Build a Gaussian-kernel Gram matrix on a finite support, evaluate MMDDivergence, and check it against the closed form \(\sqrt{(p - q)^\top K (p - q)}\). Unlike a phi-divergence, the MMD stays finite between distributions with disjoint supports.

Ambiguity sets

Example What it shows
KL ball Evaluate KLAmbiguitySet.worst_case_expectation for a sweep of radii in one batched call, check its two closed-form limits, and read the worst-case distribution off the gradient with respect to the loss.
Chi-square, total-variation and CVaR balls Solve the worst case over three phi-divergence balls on the same loss, check each one against its closed form, and rebuild the KL ball from a general generator with PhiAmbiguitySet.
Wasserstein and Sinkhorn balls Solve the worst case over a type-1 WassersteinAmbiguitySet, where the adversary moves mass along a ground cost instead of reweighting it, and check the closed form for a Lipschitz loss. Then solve the entropic relaxation SinkhornAmbiguitySet and watch it approach the exact value as the entropic strength shrinks.
MMD ball Solve the worst case over an MMDAmbiguitySet built from a Gaussian kernel. A KL ball can only reweight the scenarios the nominal already contains. The MMD ball can also move probability onto a scenario the nominal gives no mass, at a price set by the kernel.
Choosing the radius Turn a sample size and a confidence level into a radius with chi_square_radius, and check that the worst case over the resulting ChiSquareAmbiguitySet is the upper end of the normal confidence interval for the mean.
Batched ground costs Solve the Wasserstein worst case of several datasets in one call. Each dataset has its own support points, so each needs its own ground cost, and WassersteinAmbiguitySet takes them stacked as one tensor of shape (..., n, n). The batched values are checked against one set per dataset and against the closed form for a Lipschitz loss, and a batch of radii is then solved for every dataset at once.

Solvers

Example What it shows
Gradient descent Wrap an objective and a starting point in a MinimizationProblem, solve it with GradientDescent, and read the minimizer, the optimal value and the convergence diagnostics from the result.
Saddle point of a Lagrangian Project a point onto the half-space \(\{x : \sum_i x_i \le 1\}\) by solving the Lagrangian saddle point with SaddlePointSolver, using dual_projection to keep the multiplier nonnegative, and compare with the closed-form projection.
Robust decision with MinimaxSolver Choose the decision \(x\) that minimizes the worst-case squared error over a KL ball of distributions on four outcomes. MinimaxSolver runs an outer GradientDescent on \(x\) and lets the ambiguity set solve the inner maximization exactly at every step.

Training

Example What it shows
Training with torch.optim Fit an nn.Linear with Adam on the worst case over a KL ball by passing the per-sample losses to KLAmbiguitySet.worst_case_expectation. Radius zero is ordinary least squares. The data mix a large group with a small one that follows a different slope, and a larger radius trades some majority loss for a lower minority loss.
Minibatch estimators The worst case of a minibatch is a biased estimate of the worst case of the full dataset. Measure that bias for the plug-in estimate, remove most of it with MultilevelMonteCarloEstimator, and recover the full-batch value from minibatches alone with StochasticPhiDual.
Group DRO Average the per-sample losses within each group with group_losses, and train on the worst group in two ways: exactly on the full batch with CVaRAmbiguitySet(alpha=0), whose worst case is the largest group loss, and on minibatches with the exponentiated-gradient adversary OnlineGroupDRO.
Penalized adversarial training Train a classifier on the penalized Wasserstein objective of Sinha, Namkoong and Duchi (2018), in which an adversary may move every input at a squared Euclidean cost. transport_map finds the moved inputs and squared_distance measures how far they moved, which gives the radius of the Wasserstein ball that the reported worst-case loss refers to. transport_map and squared_distance need Optora 0.5.0 or later. Before 0.5.0 is on PyPI, run this script on an install from the repository (pip install -e .).

Paper reproductions

The examples above check Optora against closed forms. The optora-reproductions repository checks it against published experiments. Each reproduction installs the released package from PyPI, uses the public API only, and fixes its tolerances before the full run. Paper reproductions lists the papers, what each run found and what it changed in the library, and one Colab notebook holds every report with its recorded results.

Adding an example

Put a numbered script into a numbered group folder, for example examples/02_ambiguity_sets/07_new_ball.py. The first line of its module docstring is the title, and the paragraph after it is the summary shown above. python -m tools.docs generate then writes the page, this overview and the sidebar entry, and python -m tools.docs check fails in CI until they are regenerated.