polars_online.corr.spectral

polars_online.corr.spectral(r: Any, k: int) → tuple[Any, Any][source]

Compute the top k eigenpairs 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, use absorption().

Parameters

r

An n x n symmetric matrix, or a Gram or a closed group’s row, read as polars_online.gram.correlation() reads it, without the intercept (the module’s docstring says why).

k

How many eigenpairs to keep, a whole number of at least 1. A k above n keeps all n.

Returns

(values, vectors): the k largest eigenvalues in decreasing order, and their eigenvectors as the rows of a k x n array, each signed so that its entry of largest magnitude is positive.

Raises

ValueError

r is an array that is not square, a Gram column other than the intercept has no variance, or k is below 1.

WrongTypeError

k is not a whole number, such as 2.5. It is both a TypeError and a ValueError.

numpy.linalg.LinAlgError

r is an array holding nan entries, 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

Notes

The sign rule is the one ew_cov’s pca uses on its first refresh. Later refreshes keep each vector’s sign continuous with the refresh before, and pca reads the covariance, not the correlation, so its vectors differ from these, beyond the sign, unless every variance is equal.