Skip to content

Cubic: Adaptive Transport Map from Density ​

This example demonstrates the adaptive map construction from a given density . The target is the normalized joint density

Here is the standard-normal density.

This density is similar to the banana density, however, it has a cubic instead of a quadratic term in the second term of the product.

Key Differences from Sample-Based ATM ​

Unlike the sample-based adaptive transport map approach (see Banana: Adaptive Transport Map from Samples), this method constructs the map directly from the analytical density function without requiring samples. The key differences are:

  • Global term budget: Instead of specifying maximum terms per component, we provide a single global budget that is shared across all components. The algorithm decides which component to enrich at each iteration.

  • Quadrature-based optimization: Uses numerical integration via quadrature rules rather than empirical sample averages to evaluate the KL divergence.

  • Simultaneous enrichment: At each iteration, the algorithm evaluates candidate terms from all components and selects the one with the largest gradient magnitude, leading to a more flexible enrichment strategy.

  • No cross-validation: The density-based approach uses a simple train-validation split rather than k-fold cross-validation, making it more computationally efficient.

More information is found in the manual page Adaptive Transport Maps.

We start with loading the necessary packages:

julia
using TransportMaps
using Distributions
using LinearAlgebra
using CairoMakie
using LaTeXStrings

Defining the Target Density ​

We define the log-density function and wrap it in a MapTargetDensity object. MapTargetDensity uses automatic differentiation by default to compute gradients.

julia
logtarget(x) = logpdf(Normal(0, 0.5), x[1]) + logpdf(Normal(0, 0.1), x[2] - x[1]^3)

target = MapTargetDensity(logtarget)

Choosing a Quadrature Method ​

For density-based ATM, we need to specify quadrature points and weights for numerical integration. Here, we use Smolyak sparse grid quadrature with level 3 in 2 dimensions, which provides a good balance between accuracy and computational cost.

julia
quadrature = SparseSmolyakWeights(3, 2)
SparseSmolyakWeights:
  Number of points: 49
  Dimensions: 2
  Knots: GaussHermiteKnots(0.0, 1.0)

Adaptive Map Construction ​

We construct the adaptive transport map with a global budget of 10 terms (including the initial constant terms). The algorithm will iteratively add terms to the components that maximize the reduction in KL divergence.

For model selection, we provide validation quadrature points using Latin hypercube sampling. The algorithm returns the map with the best validation KL divergence.

julia
T, hist = optimize_adaptive_transportmap(
    target, quadrature, 10;
    validation = LatinHypercubeWeights(100, 2)
)
println(hist)
┌ Info: Selected best adaptive map
│   iteration = 8
│   training_objective = 0.07564449977668079
└   validation_objective = 0.0808055236885882
OptimizationResult for 9 components:
 Component 1:
  Train : 104.89991520771609
  Test  : 85.29312416838606
 Component 2:
  Train : 22.078325483399283
  Test  : 22.250177413117676
 Component 3:
  Train : 0.49174690058682385
  Test  : 0.43077470156243525
 Component 4:
  Train : 0.3781995637063364
  Test  : 0.33682761143829537
 Component 5:
  Train : 0.3781995637063365
  Test  : 0.33682761143829537
 Component 6:
  Train : 0.075676365706244
  Test  : 0.08180027143098209
 Component 7:
  Train : 0.075676365706244
  Test  : 0.08180027143098209
 Component 8:
  Train : 0.07564449977668079
  Test  : 0.0808055236885882
 Component 9:
  Train : 0.07564449977668106
  Test  : 0.0808055236885882

The function uses default parameters:

  • rectifier = Softplus(): Monotonicity-enforcing function

  • basis = LinearizedHermiteBasis(): Polynomial basis (Hermite polynomials with linearization)

  • reference_density = Normal(): Reference distribution (standard normal)

Convergence Analysis ​

The optimization history allows us to analyze the convergence behavior and model selection. We can plot both the training and validation KL divergence over iterations, as well as the maximum gradient magnitude among all candidate terms at each iteration. The gradient plot shows the maximum absolute gradient value among all candidate terms at each iteration. This indicates how much improvement we expect from adding the best term.

julia
convergence_fig = Figure(size = (600, 650))
objective_ax = Axis(
    convergence_fig[1, 1]; xlabel = "Iteration", yscale = log10,
    ylabel = "KL divergence"
)
convergenceplot!(objective_ax, hist; show_test = true)
axislegend(objective_ax)

grad_norms = [maximum(abs, g; init = 0.0) for g in hist.gradients[2:end]]
gradient_ax = Axis(
    convergence_fig[2, 1]; xlabel = "Iteration", yscale = log10,
    ylabel = "Maximum Absolute Gradient"
)
scatterlines!(gradient_ax, 2:length(hist.gradients), grad_norms)
linkxaxes!(objective_ax, gradient_ax)
Cubic density: ConvergenceCubic density: Convergence

We observe that:

  • The training objective decreases monotonically as expected

  • The validation objective reaches a minimum and then may increase, indicating potential overfitting

  • The gradient magnitudes decrease over iterations, showing diminishing returns from adding new terms

  • The algorithm automatically selects the model with the best validation performance. Here, it is the map fitted at iteration 7.

Generate samples and compare response

julia
samples_z = randn(2000, 2)
mapped_samples = evaluate(T, samples_z)

We compare the computed map with the target pdf

julia
x1 = -2:0.01:2
x2 = -2:0.01:2

pdf_val = [pdf(target, [x₁, x₂]) for x₁ in x1, x₂ in x2]

density_fig, density_ax, plt = sampleplot(
    mapped_samples; color = (:steelblue, 0.5),
    axis = (; xlabel = L"x_1", ylabel = L"x_2"),
)
contour!(density_ax, x1, x2, pdf_val; colormap = :viridis)
Cubic density: TM samples and density contourCubic density: TM samples and density contour

Selected Multi-Index Sets ​

We can visualize which polynomial terms were selected for each map component. The adaptive algorithm automatically determines the sparsity pattern based on the gradient information, potentially discovering non-trivial interaction structures.

julia
terms_fig = Figure(size = (600, 600))
for k in 1:2
    indices = getmultiindexsets(T[k])
    ys = k == 1 ? zeros(size(indices, 1)) : indices[:, 2]
    ax = Axis(
        terms_fig[k, 1]; title = "Component $k", aspect = DataAspect(),
        xlabel = L"Multi-index $\alpha_1$", ylabel = k == 1 ? "" : L"Multi-index $\alpha_2$",
        xticks = 0:maximum(indices[:, 1]), yticks = 0:maximum(ys),
        limits = (-0.5, maximum(indices[:, 1]) + 0.5, -0.5, maximum(ys) + 0.5)
    )
    scatter!(ax, indices[:, 1], ys; markersize = 20)
end
Cubic density: Terms in the multi-index sets of the two map componentsCubic density: Terms in the multi-index sets of the two map components

The selected terms reveal the structure the algorithm discovered:

  • Component 1 only contains univariate terms due to the triangular structure, i.e.,

  • Component 2 also only contains terms with no-mixed multivariate polynomials. This means, does depend on both and , but there are no non-linear interaction terms.

  • The adaptive approach avoids unnecessary terms, resulting in a sparse representation. This is shown by the final form which contains 7 terms instead of the maximum possible 10 terms.


This page was generated using Literate.jl.