numpy/inv-then-multiply
| Rule | inv-then-multiply |
|---|---|
| Pack | NumPy |
| Severity | warning |
| Fix | unsafe, with xpd check --fix --unsafe-fixes |
| Library versions | every version |
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).
Message
Section titled “Message”xpd prints this message with the issue. A name that starts with $ stands for code from your file.
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).Browse the other rules of the NumPy pack.