Skip to content

numpy/matmul-diagonal

Pack Severity Fix Versions
NumPy warning unsafe, with xpd check --fix --unsafe-fixes All versions

Computing a whole matrix product to read its diagonal or trace was 34 times slower than needed. Use np.einsum to compute only the diagonal.

leverage = np.diag(X @ cov @ X.T)
leverage = np.einsum("ij,ij->i", X @ cov, X)

The rule reports np.diag(a @ b), np.diag(np.dot(a, b)), np.diagonal(a @ b), np.diag(a @ b.T), np.trace(a @ b) and np.trace(np.dot(a, b)).

xpd check --fix --unsafe-fixes applies the fixes of this rule. Check the result, because an unsafe fix can change what the code does.

The unsafe fix writes np.einsum("ij,ji->i", a, b), np.einsum("ij,ij->i", a, b), np.einsum("ij,ji->", a, b).

The order of operations can change the last bits. The contraction expects compatible two-dimensional operands and can raise where np.diag would build a matrix from a one-dimensional product.

This computes the whole product to read its diagonal, which ran 34 times slower on 1,000 by 1,000 matrices. Write $NP.einsum("ij,ji->i", $A, $B).

See all rules in the NumPy pack.