You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
When `ClosedFormExpectations.jl` provides `ClosedFormExpectation` (i.e. ``\mathbb{E}_q[f]``) for a target–variational pair but does **not** yet have a hand-coded `ClosedWilliamsProduct` (i.e. ``\mathbb{E}_q[f \nabla_\eta \log q]``), you can still use `ClosedFormStrategy` by passing an `EnzymeBackend`. This exploits the identity
and lets Enzyme.jl compute the gradient automatically by differentiating the closed-form expectation with respect to the natural parameters.
494
+
495
+
#### Example: Gamma projected to LogNormal
496
+
497
+
For this pair the `ClosedFormExpectation` is available but there is no hand-coded `ClosedWilliamsProduct`, so the default `ClosedFormStrategy()` would fail. With `EnzymeBackend` it works out of the box:
498
+
499
+
```@example enzymebackend
500
+
using ExponentialFamilyProjection, ClosedFormExpectations, Enzyme
501
+
using ExponentialFamily, BayesBase, Distributions
502
+
using Plots
503
+
504
+
target_dist = Gamma(3.0, 2.0)
505
+
506
+
result = project_to(
507
+
ProjectedTo(
508
+
LogNormal;
509
+
parameters = ProjectionParameters(
510
+
strategy = ClosedFormStrategy(EnzymeBackend()),
511
+
niterations = 100,
512
+
tolerance = 1e-6,
513
+
),
514
+
),
515
+
target_dist,
516
+
)
517
+
518
+
xs = 0.01:0.05:20.0
519
+
520
+
plot(xs, x -> pdf(target_dist, x),
521
+
label="Target (Gamma)", linewidth=2,
522
+
fill=0, fillalpha=0.2, color=:blue)
523
+
plot!(xs, x -> pdf(result, x),
524
+
label="Projection (LogNormal)", linewidth=2,
525
+
linestyle=:dash, color=:red)
526
+
xlabel!("x")
527
+
ylabel!("Density")
528
+
title!("Gamma → LogNormal (EnzymeBackend)")
529
+
```
530
+
531
+
The `EnzymeBackend` supports both reverse and forward mode:
The projection can be done given a set of samples instead of the function directly. For example, let's project an set of samples onto a Beta distribution:
0 commit comments