Skip to content

numpy/matmul-diagonal

Rule matmul-diagonal
Pack NumPy
Severity warning
Fix unsafe, with xpd check --fix --unsafe-fixes
Library versions every version

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).

xpd prints this message with the issue. A name that starts with $ stands for code from your file.

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).

Browse the other rules of the NumPy pack.