Skip to content

VBPCA

VBPCA

VBPCA(n_components: int, *, bias: bool = True, maxiters: int | None = None, tol: float | None = None, verbose: int | bool = 0, hp_va: float | None = None, hp_vb: float | None = None, hp_v: float | None = None, niter_broadprior: int | None = None, va_init: float | None = None, xprobe_fraction: float = 0.0, criterion_order: list[str] | None = None, convergence_criteria: dict[str, bool] | None = None, random_state: int | Generator | None = None, init: object = 'random', max_dense_bytes: int | None = 2000000000, uniquesv: bool = False, auto_pattern_masked: bool = False, angle_every: int = 1, minangle: float = 1e-08, algorithm: Algorithm | str = 'vb', earlystop: bool = False, rmsstop: ArrayLike | None = (100.0, 0.0001, 0.001), cfstop: ArrayLike | None = (), cfstop_rel: float | None = None, cfstop_curv: float | None = None, record_cost: bool = False, cost_diagnostics: CostDiagnostics | str = 'trace', record_prior_trace: bool = False, composite_stop: Mapping[str, float] | None = None, patience: int = 1, num_cpu: int | None = None, num_cpu_score_update: int | None = None, num_cpu_loadings_update: int | None = None, num_cpu_noise_update: int | None = None, num_cpu_rms: int | None = None, runtime_tuning: RuntimeTuning | str = 'safe', runtime_profile: str | Path | None = None, dense_sufficient_statistics: StatisticsMode | str = 'auto', noise_sufficient_statistics: StatisticsMode | str = 'auto', masked_batch_size: int = 0, cov_writeback_mode: CovarianceWriteback | str | None = None, log_progress_stride: int | None = None, accessor_mode: AccessorMode | str | None = None, rotate2pca: bool = True, display: bool = False, bias_update_order: BiasUpdateOrder | str = 'auto', variance_update_order: VarianceUpdateOrder | str = 'auto', compat_mode: CompatMode | str = 'modern', return_diagnostics: bool = True, runtime_report: bool = False, explained_var_solver: ExplainedVarianceSolver | str = 'auto', explained_var_gram_ratio: float = 4.0)

Bases: FeatureNamesMixin, TypedEstimator

Variational PCA on samples x features, including missing observations.

scores_ contains joint variational training means. transform returns conditional new-row means under the fixed fitted state; these need not equal the joint means. Use vbpca_py.legacy.VBPCA for the pre-0.5 layout/API.

Examples:

These bounded fits demonstrate contracts, not posterior convergence. Input rows are samples; output arrays use float64 by default.

>>> import numpy as np
>>> from sklearn.base import clone
>>> from vbpca_py import VBPCA
>>> x = np.random.default_rng(19).normal(size=(12, 3))
>>> x[0, 0] = np.nan
>>> estimator = VBPCA(
...     2,
...     maxiters=4,
...     niter_broadprior=0,
...     random_state=19,
...     num_cpu=1,
...     runtime_tuning="off",
...     verbose=0,
... )
>>> model = clone(estimator).fit(x)
>>> model.components_.shape, model.scores_.shape
((2, 3), (12, 2))
>>> model.get_config().compat_mode.value
'modern'
>>> new_rows = np.array([[0.0, 1.0, 2.0], [np.nan, np.nan, np.nan]])
>>> projected = model.transform(new_rows)
>>> projected.shape, projected.dtype.name
((2, 2), 'float64')
>>> posterior = model.transform_posterior(new_rows)
>>> posterior.covariance.shape
(2, 2, 2)
>>> np.testing.assert_allclose(projected, posterior.mean)
>>> np.testing.assert_allclose(posterior.covariance[1], np.eye(2))
>>> bool(np.shares_memory(posterior.mean, model.scores_))
False
>>> model.inverse_transform(projected).shape
(2, 3)
>>> model.get_feature_names_out().tolist()
['vbpca0', 'vbpca1']
>>> row_scores = model.score_samples(new_rows)
>>> bool(np.isfinite(row_scores).all()), float(row_scores[1])
(True, 0.0)
>>> bool(np.isclose(model.score(new_rows), row_scores.mean()))
True
>>> try:
...     model.transform(np.ones((2, 4)))
... except ValueError as error:
...     print("features" in str(error))
True

scores_ is the joint variational fit; projected is conditional on the fixed fitted factors. A wholly missing row has a unit latent prior covariance and contributes zero to the plug-in row log density. A scoring table must contain at least one observed entry overall.

Initialize the estimator with common VB-PCA options.

Parameters:

Name Type Description Default
n_components int

Number of principal components to infer.

required
bias bool

If True, include a bias (mean) term in the model.

True
maxiters int | None

Maximum number of iterations for the training loop.

None
tol float | None

Deprecated compatibility parameter. It has no effect; use an explicit convergence criterion such as rmsstop, cfstop_rel, or minangle instead.

None
verbose int | bool

Verbosity level; can be an integer or a boolean.

0
hp_va float | None

Hyperprior term in the automatic relevance determination (ARD) update of each component's loading prior variance, Va[k] = (|a_k|^2 + tr(cov a_k) + 2 hp_va) / ((n_features + 2 hp_vb) / observed_fraction). Small values let unused components shrink toward zero (strong pruning); larger values put a floor under every Va[k] (default 0.001). Also enters the bias prior variance.

None
hp_vb float | None

Hyperprior term in the denominator of the same update; larger values shrink every component's prior variance (default 0.001).

None
hp_v float | None

Hyperprior term in the noise variance update, V = (residual + 2 hp_v) / (n_observed + 2 hp_v) (default 0.001).

None
niter_broadprior int | None

Number of initial iterations with the loading prior variances held at va_init before ARD updates start; convergence checks also wait for it (default 100).

None
va_init float | None

Initial (broad) prior variance for loadings and bias (default 1000).

None
xprobe_fraction float

Fraction of observed entries to hold out as probe data (default 0.0, disabled). When positive and no explicit xprobe is passed to :meth:fit, a random probe set is generated automatically.

0.0
criterion_order list[str] | None

Priority order for convergence criteria. Defaults to DEFAULT_CRITERION_ORDER when None.

None
convergence_criteria dict[str, bool] | None

Per-criterion enable/disable dict. Keys are criterion names, values are booleans. Criteria set to False are still evaluated for diagnostics but excluded from the stop decision. Supported criteria default to enabled. slowing_down is unavailable in live fitting and resolves to disabled; explicitly requesting it emits a warning.

None
random_state int | Generator | None

Seed (or existing Generator) controlling internal randomness: parameter initialization when no explicit init value is supplied, and the automatically generated probe mask when xprobe_fraction is positive and no explicit xprobe is passed to :meth:fit. None (default) draws fresh entropy each call, matching prior behaviour; set an int for reproducible fits.

None
init object

Random initialization, a MAT filename or a warm-start payload.

'random'
max_dense_bytes int | None

Combined reconstruction/variance output limit in bytes; None disables it. This does not bound peak fit memory.

2000000000
uniquesv bool

Group identical sample missingness patterns.

False
auto_pattern_masked bool

Enable automatic grouped-pattern handling.

False
angle_every int

Iteration stride for principal-angle diagnostics.

1
minangle float

Angle stopping threshold.

1e-08
algorithm Algorithm | str

VB, MAP or PPCA numerical update policy.

'vb'
earlystop bool

Restore/stop according to held-out probe diagnostics.

False
rmsstop ArrayLike | None

RMS plateau window and absolute/relative thresholds.

(100.0, 0.0001, 0.001)
cfstop ArrayLike | None

Cost plateau window and absolute/relative thresholds.

()
cfstop_rel float | None

Relative cost improvement threshold.

None
cfstop_curv float | None

Cost curvature threshold.

None
record_cost bool

Record the per-iteration variational objective.

False
cost_diagnostics CostDiagnostics | str

Full trace or endpoint objective evaluation.

'trace'
record_prior_trace bool

Record loading prior variances each iteration.

False
composite_stop Mapping[str, float] | None

Composite angle/RMS/cost stopping thresholds.

None
patience int

Consecutive qualifying iterations required for stopping.

1
num_cpu int | None

Global native-kernel thread hint; None inherits policy.

None
num_cpu_score_update int | None

Score-update thread override.

None
num_cpu_loadings_update int | None

Loading-update thread override.

None
num_cpu_noise_update int | None

Noise-update thread override.

None
num_cpu_rms int | None

RMS thread override.

None
runtime_tuning RuntimeTuning | str

Off, safe or aggressive runtime tuning.

'safe'
runtime_profile str | Path | None

Optional runtime-profile file.

None
dense_sufficient_statistics StatisticsMode | str

Dense observed/complement execution.

'auto'
noise_sufficient_statistics StatisticsMode | str

Noise observed/complement execution.

'auto'
masked_batch_size int

Grouped-pattern batch size; zero selects policy.

0
cov_writeback_mode CovarianceWriteback | str | None

Covariance writeback execution mode.

None
log_progress_stride int | None

Progress logging stride.

None
accessor_mode AccessorMode | str | None

Sparse/grouped-pattern accessor implementation.

None
rotate2pca bool

Rotate factors to principal axes while fitting.

True
display bool

Enable legacy progress display.

False
bias_update_order BiasUpdateOrder | str

Mean-update ordering, or compatibility default.

'auto'
variance_update_order VarianceUpdateOrder | str

Prior-variance ordering relative to rotation, or the compatibility default.

'auto'
compat_mode CompatMode | str

Legacy or modern numerical compatibility policy.

'modern'
return_diagnostics bool

Include reconstruction and variance fit outputs.

True
runtime_report bool

Retain execution-policy diagnostics after fit.

False
explained_var_solver ExplainedVarianceSolver | str

Factor/SVD/Gram explained-variance computation.

'auto'
explained_var_gram_ratio float

Gram solver aspect-ratio threshold.

4.0

get_config

get_config() -> PCAOptions

Resolve current estimator parameters into typed solver configuration.

Returns:

Type Description
PCAOptions

A fresh immutable configuration with owned small policy containers.

__getstate__

__getstate__() -> dict[str, object]

Serialize an explicit layout version without modifying live state.

Returns:

Type Description
dict[str, object]

Native estimator state with a samples-first layout marker.

__setstate__

__setstate__(state: dict[str, object]) -> None

Refuse unmarked pre-0.5 artifacts instead of guessing array axes.

Raises:

Type Description
ValueError

The artifact lacks the current native layout marker.

__sklearn_tags__

__sklearn_tags__() -> Tags

Advertise the implemented sparse, missing-data and float64 contracts.

Returns:

Type Description
Tags

Native sklearn tags reflecting actual input/output behavior.

fit

fit(X: object, y: object = None, *, mask: object | None = None, xprobe: object | None = None) -> Self

Fit samples x features, with optional aligned mask/probe tables.

y is ignored. Sparse stored entries, including numeric zeros, are observations; absent entries and NaNs are missing. Entirely unobserved training features are rejected. Warm-start A/S payloads retain the explicitly documented low-level feature-first axes.

Returns:

Type Description
Self

This fitted estimator.

Invalid data, capacity, masks or probes raise ValueError during fit.

transform

transform(X: object, *, mask: object | None = None) -> Float64Array

Return conditional latent means for new rows without refitting.

transform_posterior

transform_posterior(X: object, *, mask: object | None = None) -> ProjectionPosterior

Return fresh conditional means and full latent covariance matrices.

fit_transform

fit_transform(X: object, y: object = None, *, mask: object | None = None, xprobe: object | None = None) -> Float64Array

Fit and condition X; joint training variational means are in scores_.

Returns:

Type Description
Float64Array

Conditional scores with one row per input sample.

inverse_transform

inverse_transform(Z: object) -> Float64Array

Reconstruct samples x features from samples x components.

Returns:

Type Description
Float64Array

The dense reconstruction.

Raises:

Type Description
ValueError

Latent dimensions or the dense output budget are invalid.

score_samples

score_samples(X: object, *, mask: object | None = None) -> Float64Array

Return observed-row plug-in Gaussian log densities; empty rows give 0.

Empty scoring tables are rejected; returned row storage is budgeted.

score

score(X: object, y: object = None, *, sample_weight: object | None = None, mask: object | None = None) -> float

Average row marginal log densities with optional scoring-only weights.

This is distinct from the variational objective and cellwise capacity CV. Entry masks are separate from one-dimensional row weights.

Returns:

Type Description
float

The weighted mean row log density.

Raises:

Type Description
ValueError

Scoring weights are invalid or no entries are observed.

effective_rank

effective_rank(threshold: float = 0.01) -> int

Count returned components above the reconstruction-energy share.

Returns:

Type Description
int

Number of components exceeding the threshold.

get_options

get_options() -> dict[str, object]

Export fresh numerical options; low-level warm-start axes are retained.

Returns:

Type Description
dict[str, object]

A fresh legacy-key numerical option mapping.