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 @ ybeta = np.linalg.solve(X.T @ X, X.T @ y)What the rule reports
Section titled “What the rule reports”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.
How to fix it
Section titled “How to fix it”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.
Diagnostic message
Section titled “Diagnostic message”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.