Skip to content

numpy/inv-then-multiply

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

Multiplying by an inverse loses more digits than solving, and was 3.8 times slower. Call np.linalg.solve(a, b).

beta = np.linalg.inv(X.T @ X) @ X.T @ y
beta = np.linalg.solve(X.T @ X, X.T @ y)

The rule reports np.linalg.inv(a) @ b, np.linalg.inv(a).dot(b), np.dot(np.linalg.inv(a), b) and np.linalg.inv(a) @ b @ c, as in the normal equations.

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.linalg.solve(a, b), np.linalg.solve(a, b @ c).

Solving can change the last bits. With a stack of matrices, check how the right-hand side is broadcast, since solve and matrix multiplication can interpret a two-dimensional operand differently.

Multiplying by the inverse loses more digits than solving, and solve ran 3.8 times faster for a vector on a 1,000 by 1,000 matrix. Write $NP.linalg.solve($A, $B).

See all rules in the NumPy pack.