braintools.analysis.population.pca#
- braintools.analysis.population.pca(x, n_components=None)#
Principal component analysis by mean-centred SVD.
The data matrix is centred per feature and decomposed as \(X_c = U S V^\top\) [1]. The rows of \(V^\top\) are the principal axes; the variance along axis \(i\) is \(s_i^2 / (T - 1)\). Signs are made deterministic as in sklearn’s
svd_flipwithu_based_decision=False: the largest-magnitude entry of every component is positive.- Parameters:
- Returns:
Named tuple
(components (k, D), explained_variance (k,), explained_variance_ratio (k,), mean (D,), projection (T, k)).explained_variancecarriesunit**2andmean/projectioncarryunitwhenxis a Quantity. The ratio is relative to the total variance over allmin(T, D)components, as in sklearn; it isnanfor constant data (zero total variance).- Return type:
- Raises:
ValueError – If
xis not 1-D/2-D, has fewer than two samples, orn_componentsis out of range.
See also
participation_ratioEffective dimensionality from the same spectrum.
ccaAlignment between two populations.
Notes
Output shapes depend only on
x.shapeand the staticn_components, so the function is jittable and vmappable (e.g. over trials). It is differentiable throughjnp.linalg.svdwhen the non-zero singular values are distinct; repeated singular values make the gradient of the components undefined. Matchessklearn.decomposition.PCA(n_components=k)(withwhiten=False):components_,explained_variance_,explained_variance_ratio_,mean_andtransform(x).References
Examples
>>> import jax.numpy as jnp >>> from braintools.analysis import population >>> x = jnp.array([[1., 2.], [3., 4.], [5., 7.], [7., 9.]]) >>> res = population.pca(x) >>> res.components.shape, res.projection.shape ((2, 2), (4, 2)) >>> [round(float(v), 3) for v in res.explained_variance_ratio] [0.998, 0.002] >>> >>> # Quantities keep their units. >>> import brainunit as u >>> res = population.pca(x * u.mV, n_components=1) >>> res.explained_variance.unit Unit("mV^2")