Skip to content

Add a generic trial-level Alignment transformer (Euclidean/Riemannian, inductive, robust) #1108

Closed

Description

@bruAristimunha

Summary

moabb has no trial-level alignment preprocessing. Euclidean Alignment (He & Wu, 2020) and
Riemannian Alignment (Zanini et al., 2018) are among the most-used cross-subject/session transfer
techniques, but every project re-implements them. (pyriemann.transfer.TLCenter recenters
covariance matrices — for Riemannian pipelines — not the raw trials a deep network ingests.)

I'd like to add a single generic, inductive, robust alignment transformer.

Design

class Alignment(BaseEstimator, TransformerMixin):
    """Align trials by whitening each one with the inverse sqrt of a reference mean covariance,
    removing per-domain covariance shift before a (trial-input) model sees the data.

    Inductive by default: ``fit`` learns the reference from the *training* trials, ``transform``
    applies it to unseen trials (no test leakage). ``fit_transform`` gives the transductive,
    per-recording form. Distinct from ``pyriemann.transfer.TLCenter`` (covariance-matrix level).

    Parameters
    ----------
    metric : str, default "euclid"
        Reference mean (pyriemann ``mean_covariance``): "euclid" = Euclidean Alignment,
        "riemann" = Riemannian Alignment, "logeuclid", ...
    estimator : str, default "lwf"
        pyriemann covariance estimator; shrinkage keeps it SPD/robust on short or noisy trials.
    """
    def __init__(self, metric="euclid", estimator="lwf"):
        self.metric, self.estimator = metric, estimator

    def fit(self, X, y=None):
        covs = covariances(self._array(X), estimator=self.estimator)
        self.inv_sqrt_ref_ = invsqrtm(mean_covariance(covs, metric=self.metric))
        return self

    def transform(self, X):
        check_is_fitted(self, "inv_sqrt_ref_")
        return np.matmul(self.inv_sqrt_ref_, self._array(X))     # (n_trials, n_chans, n_times)

Why this shape

  • Inductive & leakage-free — fit stores inv_sqrt_ref_ from train only; transform reuses
    it on test. The transductive form people usually hand-roll is just fit_transform on one
    recording — same object, no second class.
  • Generic — metric selects the reference mean (Euclidean / Riemannian / log-Euclidean) via
    pyriemann.utils.mean.mean_covariance; verified all three yield finite SPD whiteners.
  • Robust — shrinkage covariance (estimator="lwf") + pyriemann.utils.base.invsqrtm +
    check_is_fitted, instead of bare scipy.linalg.sqrtm with manual real()/finite guards.
  • Works on an ndarray (n_trials, n_channels, n_times) or an Epochs (via get_data).
  • pyriemann >= 0.11 is already a hard moabb dependency, so no new requirement.

Placement & usage

moabb/datasets/preprocessing.py (next to the other transforms; it's a real fit/transform
estimator rather than a FixedTransformer, or a small alignment.py if you'd rather group a
future family). Inductive in a pipeline (CV fits on train, applies to test); transductive as an
ARRAY-stage process-pipeline step via insert_step.

Happy to PR this (with tests covering both metrics, the inductive fit→transform contract, and the
Epochs/ndarray inputs).

Activity

  1. bruAristimunha commented on Jun 27, 2026

    @bruAristimunha
    CollaboratorAuthor

    partial_fit — yes, and it falls out naturally

    The reference is a mean covariance, so incremental fitting is just an incremental mean — which
    also gives online / streaming / out-of-core alignment and online target adaptation for free.

    def fit(self, X, y=None):
        self._sum, self._ref, self._n = None, None, 0     # reset
        return self.partial_fit(X, y)
    
    def partial_fit(self, X, y=None):
        covs = covariances(self._array(X), estimator=self.estimator)
        if self.metric == "euclid":                        # exact running arithmetic mean
            self._sum = covs.sum(0) if self._sum is None else self._sum + covs.sum(0)
            self._n += len(covs)
            ref = self._sum / self._n
        else:                                              # online Fréchet mean (recursive geodesic)
            for c in covs:
                self._n += 1
                self._ref = c.copy() if self._ref is None else geodesic(self._ref, c, 1/self._n, metric=self.metric)
            ref = self._ref
        self.inv_sqrt_ref_ = invsqrtm(ref)
        return self

    fit is just reset + partial_fit, so there's one code path.

    Verified on (60, 8, 200):

    • Euclidean: incremental running mean is bit-exact vs the batch mean (Σcov/N).
    • Riemannian / log-Euclidean: recursive geodesic update Mₖ = geodesic(Mₖ₋₁, cₖ, 1/k) matches
      the batch Fréchet mean (rel.err ≈ 0 here; approximate + order-dependent in general, the standard
      online Riemannian-mean caveat — worth a docstring note).

    So the one transformer covers transductive (fit_transform), inductive (fit/transform),
    and online (partial_fit) from the same reference-mean machinery.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions