Skip to content

Robusta

The model class, the state it returns, and saving and loading that state. These are all importable from the top-level robusta_hmf namespace, except RHMFState, which lives in robusta_hmf.state and is what fit() and infer() return.

Robusta

robusta_hmf.Robusta dataclass

Robust heteroskedastic matrix factorisation (RHMF) of a data matrix.

Factorises an (N, M) data matrix Y with inverse-variance weights W as Y ≈ A @ G.T, where A (N, K) holds per-row coefficients and G (M, K) holds K shared basis vectors (K is rank). Missing entries are entries with W = 0.

With robust=True (the default) the fit maximises a Student-t likelihood by iteratively reweighted least squares: each iteration computes per-entry robust weights Q² / (Q² + W r²), where r is the residual and Q² = robust_nu · robust_scale², then solves weighted least squares for A and then G, then rotates so the columns of G are orthonormal. Entries the model cannot explain get robust weights near 0, which flags them as outliers. With robust=False it is plain heteroskedastic matrix factorisation (HMF).

The interface follows scikit-learn: fit() learns A and G, infer() finds coefficients for new rows with G held fixed, score() scores held-out data for choosing rank and robust_scale, and robust_weights() returns the per-entry outlier weights. The model keeps the state of its last fit(), which the other methods use when no state is passed.

Examples:

>>> import jax
>>> jax.config.update("jax_enable_x64", True)
>>> from robusta_hmf import Robusta
>>> model = Robusta(rank=5, robust_scale=3.0)
>>> state, loss_history = model.fit(Y, W)
>>> weights = model.robust_weights(Y, W)        # (N, M), 1 = inlier
>>> per_row = jnp.quantile(weights, 0.01, axis=1)  # one outlier score per row

A property

A (N, K) from the last fit(), or None before fitting.

G property

G (M, K) from the last fit(), or None before fitting.

state property

The RHMFState of the last fit().

None before fitting.

loss_history property

The loss after each iteration of the last fit(), or None before fitting.

fit_info property

The FitInfo of the last fit(), or None before fitting.

Not updated by infer().

__init__(rank, method='als', robust=True, robust_nu=1.0, robust_scale=1.0, init_strategy='svd', override_initialiser=None, conv_strategy='max_frac_G', conv_tol=0.001, override_conv_tester=None, override_frame=None, als_ridge=None, learning_rate=0.001, rotation='fast', dtype=None, nan_error=False, **rotation_kwargs)

Configure a model. Nothing is computed until fit().

Parameters:

Name Type Description Default
rank int

Number of basis vectors, K. It must be chosen before fitting (unlike PCA, the components of a rank-K fit are not the first K of a larger fit); score() on held-out data helps choose it.

required
method (als, sgd)

"als": iteratively reweighted alternating least squares, the algorithm of the paper. "sgd": gradient descent on the loss with optax (Adafactor unless overridden).

"als"
robust bool

If True, use the Student-t likelihood, which downweights outliers; if False, use a Gaussian likelihood (plain HMF, all robust weights 1).

True
robust_nu float

Student-t degrees of freedom. The fit depends on robust_nu and robust_scale only through Q² = robust_nu · robust_scale², so the default of 1 (a Cauchy likelihood) loses nothing.

1.0
robust_scale float

The soft outlier threshold Q (with robust_nu=1), in units of the measurement uncertainty: residuals much smaller than Q / sqrt(W) are treated as Gaussian noise, much larger ones are downweighted. Values of roughly 2 to 5 are typical starting points.

1.0
init_strategy (svd, random)

How A and G are seeded. "svd" uses the leading rank singular vectors of Y (scaled by the square roots of the singular values); "random" draws standard normals from seed. To start from factors you already have, pass init_state to fit() instead.

"svd"
override_initialiser Initialiser | None

Custom initialiser; replaces init_strategy if given.

None
conv_strategy str

Convergence test, checked every conv_check_cadence iterations: "max_frac_G" (largest squared change in G relative to the mean square of G), "max_frac_A" (the same for A), "rel_frac_loss" (relative change in the loss) or "none" (run to max_iter).

"max_frac_G"
conv_tol float

Tolerance for conv_strategy.

1e-3
override_conv_tester ConvergenceTester | None

Custom convergence tester; replaces conv_strategy and conv_tol if given.

None
override_frame OptFrame | None

Custom optimisation frame, which owns how the loop is scheduled. Defaults to a plain OptFrame that evaluates each step over the whole matrix. Pass ShardedFrame to chunk and shard the row axis, for data larger than one device's memory.

None
als_ridge float | None

Ridge added to the diagonal of every least-squares solve for A and G (method="als" only). Without it, rows and columns with fewer non-zero weights than rank are excluded from the fit; with it they are kept and shrunk towards zero, and an UnderdeterminedWarning names them.

None
learning_rate float

Learning rate of the default Adafactor optimiser (method="sgd" only).

1e-3
rotation (fast, slow, identity)

How A and G are rotated after each update to remove the factorisation's K × K degeneracy, leaving A @ G.T unchanged. "fast" makes the columns of G orthonormal by symmetric whitening (K × K eigendecomposition). "slow" uses an SVD so that G is orthonormal and the columns of A are orthogonal and ordered by decreasing norm, like PCA. "identity" does not rotate.

"fast"
dtype (float64, float32)

Precision of the fit. Y, W, A and G are cast to it. float64 needs JAX's float64 support, enabled with jax.config.update("jax_enable_x64", True) before any JAX array is created; without it, fitting raises PrecisionError rather than silently running in float32. float32 is faster, especially on GPUs, but can diverge when rows or columns of W have fewer non-zero weights than rank, so it has to be requested explicitly. When None, a compute_dtype set on override_frame is used, else float64.

"float64"
nan_error bool

What fit(), infer() and score() do with entries where Y or W is NaN or infinite. With False they are treated as missing (Y = W = 0 there) and one DataWarning is issued; with True they raise ValueError. Negative weights always raise.

False
**rotation_kwargs

Passed to the rotation. For "fast": target ("G", the default, or "A": which factor is made orthonormal), whiten (default True) and eps (default 1e-6, floor on the eigenvalues).

{}

set_state(state)

Return a copy of this model holding state as its fitted state.

Use it to restore a saved fit without refitting, e.g. with a state from load_state_from_npz(), so that methods called without state use it. The model itself is left unchanged.

Parameters:

Name Type Description Default
state RHMFState

The state the copy should hold.

required

Returns:

Name Type Description
model Robusta

A deep copy of this model with state set. Its loss_history and fit_info are those of this model.

fit(Y, W=None, max_iter=1000, rotation_cadence=1, conv_check_cadence=10, seed=0, init_state=None)

Fit A and G to data, and keep the result on the model.

Iterates until the convergence test passes or max_iter is reached, printing the loss at every convergence check. Rows and columns of W with fewer non-zero weights than rank are excluded first (unless als_ridge is set), since the data cannot determine their factors; see FitInfo for how the run is recorded.

Parameters:

Name Type Description Default
Y (Array, shape(N, M))

Data matrix. May instead be a handle returned by the frame's prepare() (e.g. a ShardedData), in which case W is carried inside it and the W argument is ignored. Reuse that handle to fit several models to one sample without re-transferring it.

required
W (Array, shape(N, M))

Inverse-variance weights, 1 / σ². Required unless Y is a prepared handle. Zero marks a missing entry. Entries where Y or W is NaN or infinite are treated as missing (or raise, with nan_error=True); negative weights raise ValueError.

None
max_iter int

Maximum number of iterations.

1000
rotation_cadence int

Rotate every this many iterations. ALS always rotates every iteration (another value only triggers a warning); this matters for method="sgd".

1
conv_check_cadence int

Test convergence (and print the loss) every this many iterations.

10
seed int

Random seed, used by init_strategy="random".

0
init_state RHMFState | None

Start from this state instead of initialising, e.g. to continue a fit or to start from factors computed elsewhere. Its A and G must have shapes (N, rank) and (M, rank). Exclusions are recomputed from W, so rows and columns the state excluded come back if W now covers them.

None

Returns:

Name Type Description
state RHMFState

The fitted factors. Excluded rows of A and G are NaN and marked by state.row_excluded / state.col_excluded.

loss_history (Array, shape(n_iter))

The loss after each iteration.

Raises:

Type Description
PrecisionError

If the model's dtype is float64 and JAX's float64 support is off.

FloatingPointError

If the loss or the factors become NaN or infinite.

Warns:

Type Description
UnderdeterminedWarning

If rows or columns are excluded (or, with als_ridge, are determined only by the ridge).

ConvergenceWarning

If the fit reaches max_iter without converging, or the loss rises by more than round-off allows.

DataWarning

If NaN or infinite entries were treated as missing.

Notes

After the fit, fit_info records whether it converged, the number of iterations, any loss rises and any exclusions.

synthesize(state=None, indices=None)

The model's reconstruction of the data, A @ G.T.

Because outliers are downweighted in the fit, this is the low-rank description of each row without its outliers; Y minus this is where they show up (see residuals()).

Parameters:

Name Type Description Default
state RHMFState | None

State to use, e.g. the output of infer(). If None, use the last fit.

None
indices Array | None

If given, reconstruct only these rows (indices into A).

None

Returns:

Name Type Description
synthesis (Array, shape(N, M) or (len(indices), M))

The reconstruction. NaN in rows and columns the state excludes, where the model is undefined.

infer(Y_infer, W_infer=None, state=None, max_iter=100, conv_strategy='max_frac_A', conv_tol=0.001, conv_check_cadence=10)

Infer coefficients for new rows with the basis G held fixed.

Alternates the robust-weight update and the least-squares solve for A (never G), starting from a weighted least-squares fit with the data weights alone. Always uses least squares, even for a model fitted with method="sgd". Runs through the same frame as fit(), so a sharded model infers on sharded data with the same chunking. The model's stored state is not changed, since one model is often applied to many datasets.

Use it to apply a trained basis to held-out data before score(), or to new data; then call robust_weights() with the returned state to find outliers in the new rows.

Parameters:

Name Type Description Default
Y_infer Array, shape (N', M)

New data with the same M columns as the training data, or a handle from the frame's prepare().

required
W_infer Array, shape (N', M)

Inverse-variance weights for Y_infer. Required unless Y_infer is a prepared handle.

None
state RHMFState | None

State supplying the fixed basis. If None, use the last fit. Columns it excludes stay excluded; new rows with fewer than rank non-zero weights in the other columns are excluded.

None
max_iter int

Maximum iterations.

100
conv_strategy str

Convergence strategy. "max_frac_G" is meaningless here (G is fixed) and is switched to "max_frac_A" with a warning.

"max_frac_A"
conv_tol float

Convergence tolerance.

1e-3
conv_check_cadence int

How often to check convergence.

10

Returns:

Name Type Description
state RHMFState

A of shape (N', rank) for the new rows (NaN for excluded rows), with G unchanged.

loss_history (Array, shape(n_iter))

The loss after each iteration.

score(Y, W=None, state=None)

Held-out scores for a state, as sufficient statistics.

Computes the standardised residuals z = (Y - A @ G.T) · sqrt(W · w_robust), which follow N(0, 1) when the model is calibrated and the outliers are correctly downweighted, and summarises them. .kl, the KL divergence of a Gaussian with the mean and standard deviation of z from N(0, 1), is the model-selection score of the paper: lower is better. Read it alongside a goodness-of-fit measure such as .chi2_red, since a rank that is too small with an aggressive robust_scale can also score well by downweighting most of the data.

Typical use is cross-validation over rank and robust_scale: fit() on a training split, infer() on the held-out split, then score the inferred state.

Parameters:

Name Type Description Default
Y (Array, shape(N, M))

Held-out data, or a handle from the frame's prepare().

required
W (Array, shape(N, M))

Held-out weights.

None
state RHMFState | None

State to score, normally the output of infer(). If None, use the last fit.

None

Returns:

Name Type Description
moments ZMoments

Read .kl for the paper's model-selection score (Eq. 20), or .std_z, .chi2_red, .rmse. Accumulated chunk by chunk when the frame is sharded, so this never forms an (N, M) array.

See Also

robusta_hmf.metrics.mad_z : needs the full residual array, so it is not available here.

basis_vectors(state=None)

The basis vectors, G.

Parameters:

Name Type Description Default
state RHMFState | None

State to use. If None, use the last fit.

None

Returns:

Name Type Description
G (Array, shape(M, K))

One basis vector per column. With the default rotation the columns are orthonormal; they are not ordered by explained variance. Rows for excluded columns of Y are NaN.

coefficients(state=None)

The coefficients, A.

Parameters:

Name Type Description Default
state RHMFState | None

State to use, e.g. the output of infer(). If None, use the last fit.

None

Returns:

Name Type Description
A (Array, shape(N, K))

The coefficients of each row of Y on the basis vectors. Rows for excluded rows of Y are NaN.

residuals(Y, state=None)

Residuals of the data from the model, Y - A @ G.T.

Large residuals relative to the uncertainties mark outliers; multiply by sqrt(W) to put them in units of the uncertainty.

Parameters:

Name Type Description Default
Y (Array, shape(N, M))

The data the state describes (the training data for the last fit, or the data passed to infer() for its state).

required
state RHMFState | None

State to use. If None, use the last fit.

None

Returns:

Name Type Description
residuals (Array, shape(N, M))

The residuals. NaN in rows and columns the state excludes.

mse(Y, state=None)

Not implemented: always raises NotImplementedError.

Use score() for goodness-of-fit statistics (.chi2_red, .rmse) instead.

Parameters:

Name Type Description Default
Y (Array, shape(N, M))

Data matrix.

required
state RHMFState | None

State to use. If None, use the last fit.

None

Raises:

Type Description
NotImplementedError

Always.

robust_weights(Y, W, state=None)

Per-entry robust weights, the outlier measure of RHMF.

w = Q² / (Q² + W r²) with r = Y - A @ G.T and Q² = robust_nu · robust_scale²: 1 for an entry the model fits exactly, falling towards 0 as the residual grows past about Q standard deviations. Summarise them per row for an outlier score per object, e.g. the median or a low quantile (the paper uses the 1% quantile and flags rows below 0.5), or per column for one per feature. With robust=False every weight is 1.

Parameters:

Name Type Description Default
Y (Array, shape(N, M))

The data the state describes.

required
W (Array, shape(N, M))

Inverse-variance weights for Y. Entries with W = 0 get weight 1.

required
state RHMFState | None

State to use, e.g. the output of infer() for new data. If None, use the last fit.

None

Returns:

Name Type Description
weights (Array, shape(N, M))

Robust weights in (0, 1]. Entries in rows or columns the state excludes are treated like missing data and get weight 1, so per-row summaries stay finite; state.row_excluded / col_excluded mark them.

RHMFState

robusta_hmf.state.RHMFState

Bases: Module

The factors A and G of Y ≈ A Gᵀ, plus loop bookkeeping.

Returned by Robusta.fit() and Robusta.infer(), and accepted by the other methods of Robusta as state. An Equinox module, so it is an immutable JAX pytree. Save and load it with save_state_to_npz() and load_state_from_npz().

Attributes:

Name Type Description
A (Array, shape(N, K))

Coefficients, one row per row of Y.

G (Array, shape(M, K))

Basis vectors, one column per component and one row per column of Y.

it int

Number of iterations run to reach this state.

opt_state OptState | None

Optimiser state for method="sgd"; None for ALS.

row_excluded Array of bool, shape (N,), or None

Rows of Y the fit excluded because the data did not determine them (fewer non-zero weights than the rank). Their rows of A are NaN. None means no row is excluded.

col_excluded Array of bool, shape (M,), or None

The same for columns of Y, whose rows of G are NaN.

Saving and loading

robusta_hmf.save_state_to_npz(state, filepath)

Save a state to a .npz file.

Saves A, G, it and any exclusion masks. The optimiser state of an SGD fit is not saved.

Parameters:

Name Type Description Default
state RHMFState

The state to save.

required
filepath str or Path

Destination. numpy.savez appends .npz if it is missing.

required

robusta_hmf.load_state_from_npz(filepath, opt_state=None)

Load a state saved by save_state_to_npz().

Parameters:

Name Type Description Default
filepath str or Path

The .npz file.

required
opt_state OptState | None

Optimiser state to attach, for continuing an SGD fit.

None

Returns:

Name Type Description
state RHMFState

The saved state. Exclusion masks that were not saved load as None. Pass it as state to Robusta's methods, or use Robusta.set_state().