pyRiemann: Biosignals classification with Riemannian geometry


pyRiemann is a Python machine learning package based on scikit-learn API. It provides a high-level interface for processing and classification of multivariate time series through the Riemannian geometry of symmetric positive definite (SPD) matrices.

pyRiemann aims at being a generic package for multivariate time series classification but has been designed around multichannel biosignals (like EEG, MEG or EMG) manipulation applied to brain-computer interface (BCI), transforming multichannel time series into covariance matrices, and classifying them using the Riemannian geometry of SPD matrices.

For a brief introduction to the ideas behind the package, you can read the introductory notes. More practical information is on the installation page. You may also want to browse the example gallery to get a sense for what you can do with pyRiemann and API reference to find out how.

To see the code or report a bug, please visit the github repository.

Content

Introduction to pyRiemann

What’s new in the package

A catalog of new features, improvements, and bug-fixes in each release.

v0.4 (Feb 2023)

v0.3 (July 2022)

v0.2.7 (June 2021)

v0.2.6 (March 2020)

  • Updated for better Scikit-Learn v0.22 support

v0.2.5 (January 2018)

  • Added BilinearFilter

  • Added a permutation test for generic scikit-learn estimator

  • Stats module refactoring, with distance based t-test and f-test

  • Removed two way permutation test

  • Added FlatChannelRemover

  • Support for python 3.5 in travis

  • Added Shrinkage transformer

  • Added Coherences transformer

  • Added Embedding class.

v0.2.4 (June 2016)

  • Improved documentation

  • Added TSclassifier for out-of the box tangent space classification.

  • Added Wasserstein distance and mean.

  • Added NearestNeighbor classifier.

  • Added Softmax probabilities for MDM.

  • Added CSP for covariance matrices.

  • Added Approximate Joint diagonalization algorithms (JADE, PHAM, UWEDGE).

  • Added ALE mean.

  • Added Multiclass CSP.

  • API: param name changes in CospCovariances to comply to Scikit-Learn.

  • API: attributes name changes in most modules to comply to the Scikit-Learn naming convention.

  • Added HankelCovariances estimation

  • Added SPoC spatial filtering

  • Added Harmonic mean

  • Added Kullback leibler mean

v0.2.3 (November 2015)

  • Added multiprocessing for MDM with joblib.

  • Added kullback-leibler divergence.

  • Added Riemannian Potato.

  • Added sample_weight for mean estimation and MDM.

Installing pyRiemann

The easiest way to install a stable version of pyRiemann is through pypi, the python package manager :

pip install pyriemann

For a bleeding edge version, you can clone the source code on github and install directly the package from source.

pip install -e .

The install script will install the required dependencies. If you want also to build the documentation and to run the test locally, you could install all development dependencies with

pip install -e .[docs,tests]

If you use a zsh shell, you need to write pip install -e .[docs,tests]. If you do not know what zsh is, you could use the above command.

Dependencies

  • Python (>= 3.7)

Mandatory dependencies

API reference

SPD Matrices Estimation

Covariances([estimator])

Estimation of covariance matrix.

ERPCovariances([classes, estimator, svd])

Estimate special form covariance matrix for ERP.

XdawnCovariances([nfilter, applyfilters, ...])

Estimate special form covariance matrix for ERP combined with Xdawn.

BlockCovariances(block_size[, estimator])

Estimation of block covariance matrix.

CospCovariances([window, overlap, fmin, ...])

Estimation of cospectral covariance matrix.

Coherences([window, overlap, fmin, fmax, ...])

Estimation of squared coherence matrices.

HankelCovariances([delays, estimator])

Estimation of covariance matrix with time delayed Hankel matrices.

Kernels([metric, n_jobs])

Estimation of kernel matrix between channels of time series.

Shrinkage([shrinkage])

Regularization of SPD matrices by shrinkage.

Embedding

locally_linear_embedding(X, *[, ...])

Perform a Locally Linear Embedding (LLE) of SPD matrices.

barycenter_weights(X, Y, indices[, metric, reg])

Compute Riemannian barycenter weights of X from Y along the first axis.

SpectralEmbedding([n_components, metric, eps])

Spectral embedding of SPD matrices into an Euclidean space.

LocallyLinearEmbedding([n_components, ...])

Locally Linear Embedding (LLE) of SPD matrices.

Classification

MDM([metric, n_jobs])

Classification by Minimum Distance to Mean.

FgMDM([metric, tsupdate, n_jobs])

Classification by Minimum Distance to Mean with geodesic filtering.

TSclassifier([metric, tsupdate, clf])

Classification in the tangent space.

KNearestNeighbor([n_neighbors, metric, n_jobs])

Classification by k-nearest neighbors.

SVC(*[, metric, kernel_fct, Cref, C, ...])

Classification by support-vector machine.

MeanField([power_list, method_label, ...])

Classification by Minimum Distance to Mean Field.

class_distinctiveness(X, y[, exponent, ...])

Measure class distinctiveness between classes of SPD matrices.

Regression

KNearestNeighborRegressor([n_neighbors, metric])

Regression by k-nearest-neighbors.

SVR(*[, metric, kernel_fct, Cref, tol, C, ...])

Regression by support-vector machine.

Clustering

Kmeans([n_clusters, max_iter, metric, ...])

Clustering by k-means with SPD matrices as inputs.

KmeansPerClassTransform([n_clusters])

Clustering by k-means for each class with SPD matrices as inputs.

Potato([metric, threshold, n_iter_max, ...])

Artefact detection with the Riemannian Potato.

PotatoField([n_potatoes, p_threshold, ...])

Artefact detection with the Riemannian Potato Field.

Tangent Space

TangentSpace([metric, tsupdate])

Tangent space project TransformerMixin.

FGDA([metric, tsupdate])

Fisher Geodesic Discriminant analysis.

Spatial Filtering

Xdawn([nfilter, classes, estimator, ...])

Xdawn algorithm.

CSP([nfilter, metric, log])

CSP spatial filtering with covariance matrices as inputs.

SPoC([nfilter, metric, log])

SPoC spatial filtering with covariance matrices as inputs.

BilinearFilter(filters[, log])

Bilinear spatial filter.

AJDC([window, overlap, fmin, fmax, fs, ...])

AJDC algorithm.

Preprocessing

Whitening([metric, dim_red, verbose])

Whitening, and optional unsupervised dimension reduction.

Channel selection

ElectrodeSelection([nelec, metric, n_jobs])

Channel selection based on a Riemannian geometry criterion.

FlatChannelRemover()

Finds and removes flat channels.

Transfer Learning

encode_domains(X, y, domain)

Encode the domains of the matrices in the labels.

decode_domains(X_enc, y_enc)

Decode the domains of the matrices in the labels.

TLSplitter(target_domain, cv)

Class for handling the cross-validation splits of multi-domain data.

TLEstimator(target_domain, estimator[, ...])

Transfer learning wrapper for estimators.

TLClassifier(target_domain, estimator[, ...])

Transfer learning wrapper for classifiers.

TLRegressor(target_domain, estimator[, ...])

Transfer learning wrapper for regressors.

TLDummy()

No transformation on data for transfer learning.

TLCenter(target_domain[, metric])

Recenter data for transfer learning.

TLStretch(target_domain[, final_dispersion, ...])

Stretch data for transfer learning.

TLRotate(target_domain[, weights, metric, ...])

Rotate data for transfer learning.

MDWM(domain_tradeoff, target_domain[, ...])

Classification by Minimum Distance to Weighted Mean.

Stats

PermutationDistance([n_perms, metric, mode, ...])

Permutation test based on distance.

PermutationModel([n_perms, model, cv, ...])

Permutation test using any scikit-learn model for scoring.

Datasets

make_gaussian_blobs([n_matrices, n_dim, ...])

Generate SPD dataset with two classes sampled from Riemannian Gaussian.

make_outliers(n_matrices, mean, sigma[, ...])

Generate a set of outlier points.

make_covariances(n_matrices, n_channels[, ...])

Generate a set of covariances matrices, with the same eigenvectors.

make_masks(n_masks, n_dim0, n_dim1_min[, rs])

Generate a set of masks, defined as semi-orthogonal matrices.

sample_gaussian_spd(n_matrices, mean, sigma)

Sample a Riemannian Gaussian distribution.

generate_random_spd_matrix(n_dim[, ...])

Generate a random SPD matrix.

make_classification_transfer(n_matrices[, ...])

Generate source and target toy datasets for transfer learning examples.

Utils function

Utils functions are low level functions that implement most base components of Riemannian Geometry.

Covariance preprocessing

covariances(X[, estimator])

Estimation of covariance matrix.

covariance_mest(X, m_estimator, *[, init, ...])

Robust M-estimators.

covariance_sch(X)

Schaefer-Strimmer shrunk covariance estimator.

covariances_EP(X, P[, estimator])

Special form covariance matrix, concatenating a prototype P.

covariances_X(X[, estimator, alpha])

Special form covariance matrix, embedding input X.

block_covariances(X, blocks[, estimator])

Compute block diagonal covariance.

cross_spectrum(X[, window, overlap, fmin, ...])

Compute the complex cross-spectral matrices of a real signal X.

cospectrum(X[, window, overlap, fmin, fmax, fs])

Compute co-spectral matrices, the real part of cross-spectra.

coherence(X[, window, overlap, fmin, fmax, ...])

Compute squared coherence.

normalize(X, norm)

Normalize a set of square matrices, using corr, trace or determinant.

get_nondiag_weight(X)

Compute non-diagonality weights of a set of square matrices.

Distances

distance(A, B[, metric])

Distance between SPD matrices according to a metric.

distance_euclid(A, B)

Euclidean distance between SPD matrices.

distance_harmonic(A, B)

Harmonic distance between SPD matrices.

distance_kullback(A, B)

Kullback-Leibler divergence between SPD matrices.

distance_kullback_sym(A, B)

Symmetrized Kullback-Leibler divergence between SPD matrices.

distance_logdet(A, B)

Log-det distance between SPD matrices.

distance_logeuclid(A, B)

Log-Euclidean distance between SPD matrices.

distance_riemann(A, B)

Affine-invariant Riemannian distance between SPD matrices.

distance_wasserstein(A, B)

Wasserstein distance between SPD matrices.

distance_mahalanobis(X, cov[, mean])

Mahalanobis distance between vectors and a Gaussian distribution.

Means

mean_covariance(covmats[, metric, sample_weight])

Mean of SPD matrices according to a metric.

mean_ale(covmats[, tol, maxiter, sample_weight])

AJD-based log-Euclidean (ALE) mean of SPD matrices.

mean_alm(covmats[, tol, maxiter, sample_weight])

Ando-Li-Mathias (ALM) mean of SPD matrices.

mean_euclid(covmats[, sample_weight])

Mean of matrices according to the Euclidean metric.

mean_harmonic(covmats[, sample_weight])

Harmonic mean of SPD matrices.

mean_identity(covmats[, sample_weight])

Identity matrix corresponding to the matrices dimension.

mean_kullback_sym(covmats[, sample_weight])

Mean of SPD matrices according to Kullback-Leibler divergence.

mean_logdet(covmats[, tol, maxiter, init, ...])

Mean of SPD matrices according to the log-det metric.

mean_logeuclid(covmats[, sample_weight])

Mean of SPD matrices according to the log-Euclidean metric.

mean_power(covmats, p, *[, sample_weight, ...])

Power mean of SPD matrices.

mean_riemann(covmats[, tol, maxiter, init, ...])

Mean of SPD matrices according to the Riemannian metric.

mean_wasserstein(covmats[, tol, maxiter, ...])

Mean of SPD matrices according to the Wasserstein metric.

maskedmean_riemann(covmats, masks[, tol, ...])

Masked Riemannian mean of SPD matrices.

nanmean_riemann(covmats[, tol, maxiter, ...])

Riemannian NaN-mean of SPD matrices.

Medians

median_euclid(X, *[, tol, maxiter, init, ...])

Euclidean geometric median of matrices.

median_riemann(X, *[, tol, maxiter, init, ...])

Affine-invariant Riemannian geometric median of SPD matrices.

Geodesics

geodesic(A, B, alpha[, metric])

Geodesic between SPD matrices according to a metric.

geodesic_euclid(A, B[, alpha])

Euclidean geodesic between SPD matrices.

geodesic_logeuclid(A, B[, alpha])

Log-Euclidean geodesic between SPD matrices.

geodesic_riemann(A, B[, alpha])

Affine-invariant Riemannian geodesic between SPD matrices.

Kernels

kernel(X[, Y, Cref, metric, reg])

Kernel matrix between SPD matrices according to a specified metric.

kernel_euclid(X[, Y, reg])

Euclidean kernel between two sets of SPD matrices.

kernel_logeuclid(X[, Y, reg])

Log-Euclidean kernel between two sets of SPD matrices.

kernel_riemann(X[, Y, Cref, reg])

Affine-invariant Riemannian kernel between two sets of SPD matrices.

Tangent Space

exp_map_euclid(X, Cref)

Project matrices back to SPD manifold by Euclidean exponential map.

exp_map_logeuclid(X, Cref)

Project matrices back to SPD manifold by Log-Euclidean exponential map.

exp_map_riemann(X, Cref[, Cm12])

Project matrices back to SPD manifold by Riemannian exponential map.

log_map_euclid(X, Cref)

Project SPD matrices in tangent space by Euclidean logarithmic map.

log_map_logeuclid(X, Cref)

Project SPD matrices in tangent space by Log-Euclidean logarithmic map.

log_map_riemann(X, Cref[, C12])

Project SPD matrices in tangent space by Riemannian logarithmic map.

upper(X)

Return the weighted upper triangular part of symmetric matrices.

unupper(T)

Inverse upper function.

tangent_space(X, Cref, *[, metric])

Transform SPD matrices into tangent vectors.

untangent_space(T, Cref, *[, metric])

Transform tangent vectors back to SPD matrices.

Base

sqrtm(C)

Square root of SPD matrices.

invsqrtm(C)

Inverse square root of SPD matrices.

expm(C)

Exponential of SPD matrices.

logm(C)

Logarithm of SPD matrices.

powm(C, alpha)

Power of SPD matrices.

nearest_sym_pos_def(X[, reg])

Find the nearest SPD matrices.

Aproximate Joint Diagonalization

ajd_pham(X, *[, init, eps, n_iter_max, ...])

Approximate joint diagonalization based on Pham's algorithm.

rjd(X, *[, init, eps, n_iter_max])

Approximate joint diagonalization based on Jacobi angles.

uwedge(X, *[, init, eps, n_iter_max])

Approximate joint diagonalization based on UWEDGE.

Matrix Tests

is_square(X)

Check if matrices are square.

is_sym(X)

Check if all matrices are symmetric.

is_skew_sym(X)

Check if all matrices are skew-symmetric.

is_real(X)

Check if all complex matrices are strictly real.

is_hermitian(X)

Check if all matrices are Hermitian.

is_pos_def(X[, fast_mode])

Check if all matrices are positive definite.

is_pos_semi_def(X)

Check if all matrices are positive semi-definite.

is_sym_pos_def(X)

Check if all matrices are symmetric positive-definite.

is_sym_pos_semi_def(X)

Check if all matrices are symmetric positive semi-definite.

Visualization

plot_confusion_matrix(*args, **kwargs)

Warning

DEPRECATED: plot_confusion_matrix is deprecated and will be remove in 0.4.0; please use sklearn confusion_matrix and ConfusionMatrixDisplay; see examples/ERP/plot_classify_EEG_tangentspace.py

plot_embedding(X[, y, metric, title, ...])

Plot 2D embedding of SPD matrices.

plot_cospectra(cosp, freqs, *[, ylabels, title])

Plot cospectral matrices.

plot_waveforms(X, display, *[, times, ...])

Display repetitions of a multichannel waveform.