ML Foundations

Compute a stable log-sum-exp with NumPy

Reduce log values without exponentiating each large input directly.

Example results for Compute a stable log-sum-exp with NumPy. naive result: inf
Illustration: Original illustration by Tensor Almanac
Evidence and testing

Review record: Tensor Almanac automated evidence gate (no independent human review). Example versions, recorded outputs and limitations appear below.

Stay in log space while adding

Some computations store positive quantities as logarithms. To find the logarithm of their sum, exponentiating large log values first can overflow even when the final logarithm is representable. NumPy logaddexp computes the logarithm of a sum of two exponentials and is designed for log-space calculations. [1]

Because logaddexp is a universal function, its reduce method can combine values along an axis. Select the intended axis for multidimensional data and check the output shape. [2]

References: [1], [2]

Compare a bounded example

Run python examples/numpy_logsumexp_reduction.py. Directly exponentiating the two large inputs overflows, so the naive result is infinite. The example suppresses the expected warning only for that comparison and asserts the observed overflow.

Applying logaddexp.reduce returns a finite value close to 1001.313262. The assertion checks an equivalent expression formed by factoring out the larger input. [1, 2]

Executed with local Python and NumPy; stdout and checksum are stored in private evidence.

import numpy as np

log_values = np.array([1000.0, 1001.0])
with np.errstate(over="ignore"):
    naive = np.log(np.sum(np.exp(log_values)))
stable = np.logaddexp.reduce(log_values)
expected = 1001.0 + np.log1p(np.exp(-1.0))
assert np.isinf(naive)
assert np.isfinite(stable) and np.isclose(stable, expected)
print("naive result:", float(naive))
print("stable result:", round(float(stable), 6))
print("finite:", bool(np.isfinite(stable)))

Recorded output

naive result: inf
stable result: 1001.313262
finite: True

References: [1], [2]

Define the reduction contract

The example uses two finite floating-point values in one dimension. For a matrix, specify the axis that represents alternatives in the same sum, and test the resulting dimensions before using the result downstream. [2]

A finite result for this fixture is not a guarantee of exact arithmetic or a replacement for validating empty inputs, nonfinite values and application-specific requirements. [1, 2]

References: [1], [2]

Sources

  1. NumPy logaddexp
  2. NumPy ufunc reduce