Fundamentals 3 min read

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.

Model Perspective
Model Perspective
Model Perspective
Boost Python Linear Algebra Performance with SciPy.linalg

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.

<code>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
</code>
<code>_= 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()
</code>
PythonNumPylinear algebraSciPydata fittingleast squares
Model Perspective
Written by

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

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.