Python Tutorial
SciPy Optimizers
Find roots and minima, and fit a curve to data with scipy.optimize.
Root of an Equation
from scipy.optimize import root
def eqn(x):
return x + 3 * 2.71828**x
print(root(eqn, 0).x)Minimize
from scipy.optimize import minimize
def fn(x):
return (x[0] - 3) ** 2 + (x[1] + 1) ** 2
res = minimize(fn, [0, 0])
print(res.x, res.fun)Curve Fit
import numpy as np
from scipy.optimize import curve_fit
def model(x, a, b):
return a * x + b
x = np.array([0, 1, 2, 3, 4], dtype=float)
y = np.array([1, 3, 5, 7, 9], dtype=float)
params, _ = curve_fit(model, x, y)
print(params) # slope, intercept📘 Real-World Deep Dive
Knowing <strong>SciPy Optimizers (SciPy)</strong> well is what turns SciPy from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of SciPy Optimizers that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
from scipy.optimize import minimize
import numpy as np
res = minimize(lambda x: (x[0]-1)**2 + (x[1]+2)**2, x0=[0, 0])
print("x*:", res.x, "f(x*):", res.fun)Expected Output
(see source)Common mistakes
- Many SciPy functions take
methodstrings with subtle spelling differences ("trust-constr"vs."trust-constr") — readscipy.optimize.least_squaresdocs. - Sparse matrices need explicit conversion to dense (
toarray()) before being fed to functions that don't acceptscipy.sparse. scipy.signalfunctions often return arrays whose length differs from input — always inspectlen(out)defensively.- Treating SciPy Optimizers as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Use vectorised
scipy.statsdistributions instead of looping per-sample for large parametric studies. scipy.sparse.csr_matrixis the right format for arithmetic;csc_matrixis right for slicing columns.- Prefer Cython/Numba (or NumPy ufuncs) over Python loops inside SciPy callbacks (e.g.
odeint). - When working with SciPy, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.