polars_online.corr.spectral¶
- polars_online.corr.spectral(r: Any, k: int) tuple[Any, Any][source]¶
Compute the top
keigenpairs of a matrix, largest first.Use it to read a correlation matrix’s leading factors, or to keep them and rebuild the matrix with
from_spectral(). For the share of the variance they explain, useabsorption().Parameters
rAn
n x nsymmetric matrix, or a Gram or a closed group’s row, read aspolars_online.gram.correlation()reads it, without the intercept (the module’s docstring says why).kHow many eigenpairs to keep, a whole number of at least 1. A
kabovenkeeps alln.
Returns
(values, vectors): theklargest eigenvalues in decreasing order, and their eigenvectors as the rows of ak x narray, each signed so that its entry of largest magnitude is positive.Raises
ValueErrorris an array that is not square, a Gram column other than the intercept has no variance, orkis below 1.WrongTypeErrorkis not a whole number, such as2.5. It is both aTypeErrorand aValueError.numpy.linalg.LinAlgErrorris an array holdingnanentries, where numpy’s eigensolver does not converge.
Examples
r = np.array([[1.0, 0.8, 0.7], [0.8, 1.0, 0.75], [0.7, 0.75, 1.0]]) values, vectors = po.corr.spectral(r, 1) print(values.round(3), vectors.round(3))
[2.501] [[0.578 0.59 0.564]]
See also
from_spectral(), the matrix rebuilt from the pairs.absorption(), the share of the variance the topkexplain.
Notes
The sign rule is the one
ew_cov’spcauses on its first refresh. Later refreshes keep each vector’s sign continuous with the refresh before, andpcareads the covariance, not the correlation, so its vectors differ from these, beyond the sign, unless every variance is equal.