Boost Python Linear Algebra Performance with SciPy.linalg
This article explains how SciPy’s linalg module, built on optimized BLAS/LAPACK libraries, extends NumPy’s linear algebra with faster routines and advanced algorithms, and demonstrates fitting a quadratic polynomial using least‑squares via a practical code example.
Linear Algebra (scipy.linalg)
Built on ATLAS LAPACK and BLAS libraries, SciPy provides very fast linear algebra capabilities.
All linear algebra routines accept two‑dimensional arrays as input and output.
scipy.linalg and numpy.linalg
scipy.linalg= numpy.linalg + more advanced algorithms. scipy.linalg is compiled with BLAS/LAPACK, making it faster. numpy.matrix and 2‑D numpy.ndarray are matrix types; numpy.matrix offers a more convenient interface for matrix operations, supports MATLAB‑like syntax such as the * operator for matrix multiplication, and provides I and T members for inverse and transpose.
Example
We fit a quadratic polynomial y = a + b·x² by forming a design matrix with a constant column and a column of x² values, then solving the least‑squares problem M·p = y.
from scipy.linalg import lstsq
import matplotlib.pyplot as plt
x = np.array([1, 2.5, 3.5, 4, 5, 7, 8.5])
y = np.array([0.3, 1.1, 1.5, 2.0, 3.2, 6.6, 8.6])
M = x[:, np.newaxis]**[0, 2]
p, res, rnk, s = lstsq(M, y)
p _= plt.plot(x, y, 'o', label='data')
xx = np.linspace(0, 9, 101)
yy = p[0] + p[1]*xx**2
_= plt.plot(xx, yy, label='least squares fit, $y = a + bx^2$')
_= plt.xlabel('x')
_= plt.ylabel('y')
_= plt.legend(framealpha=1, shadow=True)
_= plt.grid(alpha=0.25)
_= plt.show()Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Model Perspective
Insights, knowledge, and enjoyment from a mathematical modeling researcher and educator. Hosted by Haihua Wang, a modeling instructor and author of "Clever Use of Chat for Mathematical Modeling", "Modeling: The Mathematics of Thinking", "Mathematical Modeling Practice: A Hands‑On Guide to Competitions", and co‑author of "Mathematical Modeling: Teaching Design and Cases".
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
