File size: 2,356 Bytes
b389bd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
"""Same 8-mode Gaussian ring target as main_mixtureGaussian2.py, but trains
AmortizedPhiFunctionMixtureCDF: Q(tau | theta) is the inverse CDF of a learned
1D Gaussian mixture (trainable per-component mean/std/weight, output by a
hypernetwork conditioned on theta), rather than a generic spline. Since the
target itself is a Gaussian mixture, this is the best-matched inductive bias
we've tried: the projection of the ring mixture onto any direction is again
exactly a Gaussian mixture, so the hypernetwork only needs to learn simple
(here linear/quadratic/constant) relationships instead of an arbitrary shape.
"""
import math
import torch
from models import AmortizedPhiFunctionMixtureCDF
from sw_common import (
    set_seed,
    train_amortized_phi,
    evaluate_and_plot,
    sample_mixture_gaussian,
    mixture_gaussian_true_quantiles,
    plain_quantile_loss,
    PinballLoss,
)

set_seed(42)

device = 'cuda'

n_dim = 2
n_components = 8
radius = 5.0
std = 0.3
embedding_dim = 256

angles = torch.arange(n_components, dtype=torch.float32) * (2 * math.pi / n_components)
means = (radius * torch.stack([torch.cos(angles), torch.sin(angles)], dim=1)).to(device)  # 8 components on a ring
covs = (std ** 2) * torch.eye(2, device=device).unsqueeze(0).repeat(n_components, 1, 1)  # isotropic per component
weights = torch.full((n_components,), 1.0 / n_components)  # equal weights


def sample_fn(n_samples):
    return sample_mixture_gaussian(n_samples, means, covs, weights, n_dim, device)


def true_quantile_fn(test_thetas, taus_test):
    return mixture_gaussian_true_quantiles(test_thetas, taus_test, means, covs, weights)


mixture_model = AmortizedPhiFunctionMixtureCDF(embedding_dim=embedding_dim, d=n_dim, num_components=n_components)

model = train_amortized_phi(
    sample_fn,
    d=n_dim,
    device=device,
    n_samples=256,
    L=100,
    epochs=20000,
    lr=5e-4,
    lambda_reg=0.0,  # monotonic by construction (a mixture CDF is strictly increasing)
    loss_fn=plain_quantile_loss,
    criterion=PinballLoss(),
    model=mixture_model,
)

evaluate_and_plot(
    model, d=n_dim, device=device,
    true_quantile_fn=true_quantile_fn,
    sample_fn=sample_fn,
    title="Amortized Quantile Function (Mixture-CDF) — Gaussian Mixture",
    seed=123,  # same fixed test directions/data as the other main_mixtureGaussian2_*.py variants
)