cjd_flows.data¶
Datasets and preprocessing for CJD flows.
preprocess– dequantization, constant-det scalings, standardization, bits/dim conversion.toy– 2-D toy datasets and an n-D asymmetric GMM.tabular– MAF benchmarks (POWER, GAS, HEPMASS, MINIBOONE, BSDS300).images– MNIST, Fashion-MNIST, CIFAR-10.
Downloads go to $CJD_FLOWS_DATA or ~/.cache/cjd_flows.
The main functions and classes are also importable from cjd_flows.data.
Preprocessing¶
Data preprocessing with tracked log-determinants.
CJD flows have a constant Jacobian determinant. To report likelihoods in the
original data space (e.g. bits/dim on 8-bit images) the change of variables
of the preprocessing must be accounted for. All preprocessing steps here record
log|det ∂y/∂x| per sample:
affine steps (
AffineScale,ToUnitInterval,ToSymmetric,Standardize) have a constant log-det and therefore preserve the CJD property of the overall modelx -> preprocessing -> flow;Logitis not constant-det (constant_det = False): composing it with a CJD flow yields a model whose density level sets are no longer pre-images of base level sets. Use it only if you know what you are doing.
Bits/dim convention (bits_per_dim()): 8-bit data x ∈ {0,…,255}^D is
dequantized to x̃ = x + u ∈ [0, 256)^D with u ~ U[0,1)^D. The model sees
y = g(x̃) and
bpd = (−log p_model(y) − log|det ∂y/∂x̃|) / (D ln 2),
which is the negative (variational lower bound of the) discrete log-likelihood in bits per dimension.
- class cjd_flows.data.preprocess.Preprocessing[source]¶
Bases:
objectBase class of a (fixed, non-learnable) preprocessing map
y = g(x).
- class cjd_flows.data.preprocess.UniformDequantize[source]¶
Bases:
PreprocessingAdds fresh uniform noise
u ~ U[0,1)to integer data.x ∈ {0, …, n_bins−1}becomesx̃ = x + u ∈ [0, n_bins). The map is stochastic but volume preserving (log-det 0); the inverse isfloor.
- class cjd_flows.data.preprocess.AffineScale[source]¶
Bases:
Preprocessingy = scale · x + shiftwith a scalar (or broadcastable)scale.
- class cjd_flows.data.preprocess.ToUnitInterval[source]¶
Bases:
AffineScaleMaps
[0, n_bins)to[0, 1):y = x / n_bins(log-det−D log n_bins).
- class cjd_flows.data.preprocess.ToSymmetric[source]¶
Bases:
AffineScaleMaps
[0, n_bins)to[−1, 1):y = 2x / n_bins − 1(log-detD log(2/n_bins)).
- cjd_flows.data.preprocess.to_unit_interval(x, n_bins=256)[source]¶
x / n_bins; per-sample log-det−D log n_bins.
- cjd_flows.data.preprocess.to_symmetric(x, n_bins=256)[source]¶
2x / n_bins − 1; per-sample log-detD (log 2 − log n_bins).
- class cjd_flows.data.preprocess.Logit[source]¶
Bases:
PreprocessingRealNVP-style logit transform
y = logit(α + (1−2α) u)foru ∈ [0, 1].Warning
NOT constant-det (
constant_det = False). Combined with a CJD flow the overall model loses the density level-set preservation property.
- class cjd_flows.data.preprocess.Standardize[source]¶
Bases:
PreprocessingFeature-wise standardization
y = (x − mean) / std(constant log-det−Σ log std).- Parameters:
- class cjd_flows.data.preprocess.Compose[source]¶
Bases:
PreprocessingSequential composition; log-dets add up.
- __init__(*steps)[source]¶
- Parameters:
steps (Preprocessing)
- property constant_det: bool¶
bool(x) -> bool
Returns True when the argument x is true, False otherwise. The builtins True and False are the only two instances of the class bool. The class bool is a subclass of the class int, and cannot be subclassed.
- cjd_flows.data.preprocess.bits_per_dim(log_prob, dim, preprocessing_log_det=None, n_bins=256)[source]¶
Converts model log-likelihoods to bits/dim in the dequantized data space.
- Parameters:
log_prob (
Union[Tensor,float]) –log p_model(y)in model space (nats), per sample or averaged.dim (
int) – number of dimensionsD.preprocessing_log_det (
Union[Tensor,float,None]) –log|det ∂y/∂x̃|of the preprocessing from the dequantized raw datax̃ ∈ [0, n_bins)^Dto model spacey(per sample).Nonemeans the model data isx̃ / n_bins ∈ [0,1)^D, i.e.−D log n_bins.n_bins (
int) – number of quantization levels (only used whenpreprocessing_log_detisNone).
- Return type:
- Returns:
(−log p(y) − log|det ∂y/∂x̃|) / (D ln 2). Equivalently, ifLdenotes the log-det relative to the[0, 1)scaling,(−log p(y) − L + D log n_bins) / (D ln 2).
Example
The uniform density on
[0, 256)^D(identity preprocessing) haslog p = −D log 256and gives exactly 8 bits/dim.
Toy datasets¶
Toy datasets (2-D benchmarks and an n-D asymmetric Gaussian mixture).
All samplers return float32 tensors of shape (n, d) and accept a
seed (or a torch.Generator) for reproducibility. The 2-D generators
follow the widely used FFJORD / “inf_train_gen” definitions.
Exact log densities are available for eight_gaussians(),
checkerboard() and GaussianMixture (e.g. asymmetric_gmm())
via toy_log_prob() / GaussianMixture.log_prob.
- cjd_flows.data.toy.two_moons(n, noise=0.1, seed=None)[source]¶
Two interleaving half circles (sklearn
make_moons), scaled by 2 and centred.
- cjd_flows.data.toy.circles(n, factor=0.5, noise=0.08, seed=None)[source]¶
Two concentric circles (sklearn
make_circles) scaled by 3.
- cjd_flows.data.toy.rings(n, noise=0.08, seed=None)[source]¶
Four concentric rings with radii 3, 2.25, 1.5, 0.75.
- cjd_flows.data.toy.eight_gaussians(n, seed=None)[source]¶
Mixture of 8 isotropic Gaussians on a circle (radius 4/1.414, std 0.5/1.414).
- cjd_flows.data.toy.eight_gaussians_mixture()[source]¶
The exact density of
eight_gaussians()as aGaussianMixture.- Return type:
- cjd_flows.data.toy.checkerboard(n, seed=None)[source]¶
Uniform density on 8 squares of a 4x4 checkerboard on
[-4, 4]^2(density 1/32).
- cjd_flows.data.toy.checkerboard_log_prob(x)[source]¶
Exact log density of
checkerboard()(-log 32on the support,-infoutside).
- cjd_flows.data.toy.pinwheel(n, num_classes=5, radial_std=0.3, tangential_std=0.1, rate=0.25, seed=None)[source]¶
Pinwheel with
num_classesspiralling arms.
- cjd_flows.data.toy.swiss_roll(n, noise=1.0, seed=None)[source]¶
2-D swiss roll (sklearn
make_swiss_rollprojected to(x, z), scaled by 1/5).
- class cjd_flows.data.toy.GaussianMixture[source]¶
Bases:
ModuleGaussian mixture with diagonal covariances and exact
log_prob/sample.- Parameters:
- __init__(means, variances, weights=None)[source]¶
Initialize internal Module state, shared by both nn.Module and ScriptModule.
- forward(x)[source]¶
Define the computation performed at every call.
Should be overridden by all subclasses.
Note
Although the recipe for forward pass needs to be defined within this function, one should call the
Moduleinstance afterwards instead of this since the former takes care of running the registered hooks while the latter silently ignores them.
- cjd_flows.data.toy.asymmetric_gmm(d, high=5.0, low=0.5)[source]¶
Asymmetric two-component GMM of the USF paper.
Means
+1_dand−1_d, equal weights,Σ1 = IandΣ2 = diag(high, …, high, low, …, low)(firstd // 2entrieshigh).- Return type:
- Parameters:
- cjd_flows.data.toy.asymmetric_gmm_data(n, d=2, seed=None)[source]¶
Samples from
asymmetric_gmm().
Tabular benchmarks¶
MAF tabular density-estimation benchmarks (POWER, GAS, HEPMASS, MINIBOONE, BSDS300).
The raw data is the archive of Papamakarios et al. (2017), “Masked
Autoregressive Flow for Density Estimation” (zenodo record 1161203,
data.tar.gz). The preprocessing replicates datasets/*.py of
github.com/gpapamak/maf exactly (same random seed, column removal, noise,
normalization and splits), so numbers are comparable with the literature.
Processed splits are cached as .npy files under
<root>/maf/processed (root defaults to $CJD_FLOWS_DATA or
~/.cache/cjd_flows).
Expected shapes (train, val, test):
name |
D |
train |
val |
test |
|---|---|---|---|---|
power |
6 |
1,659,917 |
184,435 |
204,928 |
gas |
8 |
852,174 |
94,685 |
105,206 |
hepmass |
21 |
315,123 |
35,013 |
174,987 |
miniboone |
43 |
29,556 |
3,284 |
3,648 |
bsds300 |
63 |
1,000,000 |
50,000 |
250,000 |
Optional dependencies (pip install "cjd-flows[tabular]"): pandas
(gas, hepmass) and h5py (bsds300), needed only for the first
preprocessing; cached splits load without them.
Image datasets¶
Image datasets (MNIST, Fashion-MNIST, CIFAR-10) with on-the-fly dequantization.
The raw 8-bit images are kept as uint8 tensors; every access draws fresh
uniform dequantization noise and applies a constant-det affine scaling:
scale="unit":y = (x + u) / 256 ∈ [0, 1)scale="symmetric":y = 2 (x + u) / 256 − 1 ∈ [−1, 1)
dataset.preprocessing_log_det is the per-sample log|det ∂y/∂x̃| w.r.t.
the dequantized raw data x̃ = x + u ∈ [0, 256)^D; use
dataset.bits_per_dim(log_prob) to report bits/dim.
Data is loaded through torchvision if it is installed (backend="auto")
and otherwise downloaded directly (MNIST/Fashion IDX files and the binary
CIFAR-10 archive – no pickle involved).
- cjd_flows.data.images.load_image_tensors(name, split='train', root=None, download=True, backend='auto')[source]¶
Raw
uint8images(N, C, H, W)andint64labels(N,).
- class cjd_flows.data.images.DequantizedImageDataset[source]¶
Bases:
DatasetDataset of 8-bit images returning
(y, label)with fresh dequantization noise.- Parameters:
- event_shape, dim, preprocessing, preprocessing_log_det (per sample,
- w.r.t. ``x̃ ∈ [0,256)^D``), n_bins.
Besides
__getitem__it provides a vectorizedget_batch()(used bycjd_flows.train.fit()) andto()to keep theuint8storage on the GPU.
- cjd_flows.data.images.load_images(name, root=None, classes=None, split='train', dequantize=True, scale='symmetric', flatten=False, download=True, backend='auto', exclude_classes=False)[source]¶
Loads MNIST / Fashion-MNIST / CIFAR-10 as a dequantized dataset.
- Parameters:
name (
str) –"mnist","fashion_mnist"or"cifar10".root (
Union[str,PathLike,None]) – cache directory (default$CJD_FLOWS_DATAor~/.cache/cjd_flows).classes (
Union[int,Sequence[int],None]) – keep only these labels (one-class / subset filter).split (
str) –"train"or"test".dequantize (
bool) – uniform dequantization (fresh noise on every access).scale (
str) –"symmetric"([-1, 1)) or"unit"([0, 1)).flatten (
bool) – return flat vectors.download (
bool) – download if missing.backend (
str) –"auto"(torchvision if installed),"torchvision"or"raw".exclude_classes (
bool) – ifTruekeep all labels exceptclasses(handy for the “rest” set in one-class protocols).
- Return type:
- Returns: