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
__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, |
required |
method
|
(als, sgd)
|
|
"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 |
1.0
|
robust_scale
|
float
|
The soft outlier threshold |
1.0
|
init_strategy
|
(svd, random)
|
How |
"svd"
|
override_initialiser
|
Initialiser | None
|
Custom initialiser; replaces |
None
|
conv_strategy
|
str
|
Convergence test, checked every |
"max_frac_G"
|
conv_tol
|
float
|
Tolerance for |
1e-3
|
override_conv_tester
|
ConvergenceTester | None
|
Custom convergence tester; replaces |
None
|
override_frame
|
OptFrame | None
|
Custom optimisation frame, which owns how the loop is scheduled.
Defaults to a plain |
None
|
als_ridge
|
float | None
|
Ridge added to the diagonal of every least-squares solve for |
None
|
learning_rate
|
float
|
Learning rate of the default Adafactor optimiser
( |
1e-3
|
rotation
|
(fast, slow, identity)
|
How |
"fast"
|
dtype
|
(float64, float32)
|
Precision of the fit. |
"float64"
|
nan_error
|
bool
|
What |
False
|
**rotation_kwargs
|
Passed to the rotation. For |
{}
|
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 |
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
|
required |
W
|
(Array, shape(N, M))
|
Inverse-variance weights, |
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
|
1
|
conv_check_cadence
|
int
|
Test convergence (and print the loss) every this many iterations. |
10
|
seed
|
int
|
Random seed, used by |
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 |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
state |
RHMFState
|
The fitted factors. Excluded rows of |
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 |
ConvergenceWarning
|
If the fit reaches |
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 |
None
|
indices
|
Array | None
|
If given, reconstruct only these rows (indices into |
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 |
required |
W_infer
|
Array, shape (N', M)
|
Inverse-variance weights for |
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
|
None
|
max_iter
|
int
|
Maximum iterations. |
100
|
conv_strategy
|
str
|
Convergence strategy. |
"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
|
|
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 |
required |
W
|
(Array, shape(N, M))
|
Held-out weights. |
None
|
state
|
RHMFState | None
|
State to score, normally the output of |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
moments |
ZMoments
|
Read |
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 |
coefficients(state=None)
¶
The coefficients, A.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
state
|
RHMFState | None
|
State to use, e.g. the output of |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
A |
(Array, shape(N, K))
|
The coefficients of each row of |
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 |
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 |
required |
state
|
RHMFState | None
|
State to use, e.g. the output of |
None
|
Returns:
| Name | Type | Description |
|---|---|---|
weights |
(Array, shape(N, M))
|
Robust weights in |
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 |
G |
(Array, shape(M, K))
|
Basis vectors, one column per component and one row per column of |
it |
int
|
Number of iterations run to reach this state. |
opt_state |
OptState | None
|
Optimiser state for |
row_excluded |
Array of bool, shape (N,), or None
|
Rows of |
col_excluded |
Array of bool, shape (M,), or None
|
The same for columns of |
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. |
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 |
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 |