Optimisation — finding the input that makes a function smallest (or largest) — is everywhere: fitting a model, minimising cost, maximising revenue. scipy.optimize gives you robust numerical solvers so you don't hand-roll calculus.
Why optimisation?
Machine learning is optimisation under the hood — "find the parameters that minimise the error". Beyond ML, you'll optimise pricing, schedules, resource allocation. The pattern is always: define a function to minimise, hand it to a solver.
Minimising a function
from scipy import optimize# Minimise f(x) = (x - 3)^2 + 1 → minimum at x = 3def f(x):return (x - 3)**2 + 1result = optimize.minimize(f, x0=0) # x0 = starting guessprint(result.x) # ≈ [3.0] the minimising inputprint(result.fun) # ≈ 1.0 the minimum value
Curve fitting
curve_fit finds the parameters of a model that best match your data — the numerical heart of regression. You supply the model shape; SciPy finds the coefficients:
import numpy as npdef model(x, a, b): # a line: y = a·x + breturn a * x + bx = np.array([1, 2, 3, 4, 5])y = np.array([2.1, 4.0, 6.2, 7.9, 10.1])params, _ = optimize.curve_fit(model, x, y)a, b = params # best-fit slope & interceptprint(a, b) # ≈ 2.0, 0.0
Root finding
A root is where a function equals zero. root_scalar (or brentq) solves equations that have no neat algebraic answer:
# Where does x^2 - 2 = 0? (√2)sol = optimize.root_scalar(lambda x: x**2 - 2, bracket=[0, 2])print(sol.root) # ≈ 1.4142
Practice
Minimise a simple quadratic with minimize. Then generate noisy points along a line, recover the slope and intercept with curve_fit, and compare to the true values. Finally, find a root of cos(x) - x.
Key takeaways
- 01Optimisation finds the input that minimises (or maximises) a function — the basis of ML.
- 02optimize.minimize(f, x0) finds a minimum from a starting guess.
- 03curve_fit recovers the best-fit parameters of a model — numerical regression.
- 04root_scalar / brentq solve f(x) = 0 when there's no algebraic answer.
- 05Numerical solvers need a good starting point or bracket, or they miss/diverge.
