SciPy Optimizers
Optimization means finding the input that makes a function as small (or as large) as possible. It is everywhere: the cheapest route, the strongest beam for a given weight, the model parameters that best fit some data. The scipy.optimize module contains a family of optimizers that do this numerically.
Minimizing a function of one variable
For a function of a single number, use minimize_scalar(). It returns an OptimizeResult object, which behaves like a dictionary with attribute access:
from scipy.optimize import minimize_scalar
def cost(x):
return x ** 4 - 3 * x ** 3 + 2
res = minimize_scalar(cost)
print("x :", round(res.x, 4))
print("f(x) :", round(res.fun, 4))
print("success :", res.success)
print("evals :", res.nfev)x : 2.25
f(x) : -6.543
success : True
evals : 14
The most useful fields of the result are:
| Field | Meaning |
|---|---|
x |
The best input found |
fun |
The function value at x |
success |
True if the optimizer believes it converged |
message |
A human-readable reason for stopping |
nfev / nit |
Number of function evaluations / iterations |
If you know the answer lies in an interval, pass bounds=(a, b) together with method="bounded".
Minimizing a function of several variables
minimize() handles functions of a vector. You give it the function and a starting guess x0; the function receives a NumPy array with one entry per variable.
import numpy as np
from scipy.optimize import minimize
# A bowl-shaped surface whose lowest point is at (1, -2)
def bowl(p):
x, y = p
return (x - 1) ** 2 + 2 * (y + 2) ** 2 + 5
res = minimize(bowl, x0=[0, 0])
print("best point:", np.round(res.x, 4))
print("value :", round(res.fun, 4))
print("method :", "BFGS (the default without bounds)")best point: [ 1. -2.]
value : 5.0
method : BFGS (the default without bounds)
Choosing a method
minimize() wraps many algorithms, selected with method=:
| Method | Uses gradient? | Good for |
|---|---|---|
"BFGS" |
yes (estimated if not given) | Smooth functions without constraints — the default |
"Nelder-Mead" |
no | Noisy or non-smooth functions, few variables |
"Powell" |
no | Like Nelder-Mead; supports bounds |
"L-BFGS-B" |
yes | Many variables, simple bounds |
"SLSQP" |
yes | Equality and inequality constraints |
"trust-constr" |
yes | Large constrained problems |
A classic test is the Rosenbrock function, a curved valley whose minimum is at (1, 1). SciPy ships it as rosen, along with its exact gradient rosen_der. Let's compare how much work each method needs:
from scipy.optimize import minimize, rosen, rosen_der
start = [-1.2, 1.0]
for method in ["Nelder-Mead", "Powell", "BFGS"]:
res = minimize(rosen, start, method=method)
print(f"{method:12} x = ({res.x[0]:.4f}, {res.x[1]:.4f}) evaluations = {res.nfev}")
res = minimize(rosen, start, method="BFGS", jac=rosen_der)
print(f"{'BFGS + grad':12} x = ({res.x[0]:.4f}, {res.x[1]:.4f}) evaluations = {res.nfev}")Nelder-Mead x = (1.0000, 1.0000) evaluations = 159
Powell x = (1.0000, 1.0000) evaluations = 607
BFGS x = (1.0000, 1.0000) evaluations = 117
BFGS + grad x = (1.0000, 1.0000) evaluations = 39
Supplying the exact gradient with jac= saves many evaluations, because the optimizer no longer has to estimate slopes with extra function calls.
Local versus global minima
Most optimizers are local: they roll downhill from the starting point and stop in the first valley they reach. A wiggly function can have many valleys, so the starting point matters:
import numpy as np
from scipy.optimize import minimize, basinhopping
def wavy(x):
return np.sin(3 * x[0]) + 0.1 * x[0] ** 2
for x0 in [-3.0, 0.0, 2.0]:
res = minimize(wavy, x0=[x0])
print(f"start {x0:5.1f} -> x = {res.x[0]:7.4f}, f = {res.fun:.4f}")
best = basinhopping(wavy, x0=[2.0], niter=50, stepsize=1.5, seed=0)
print(f"basinhopping -> x = {best.x[0]:7.4f}, f = {best.fun:.4f}")start -3.0 -> x = -2.5608, f = -0.3295
start 0.0 -> x = -0.5122, f = -0.9732
start 2.0 -> x = 1.5366, f = -0.7586
basinhopping -> x = -0.5122, f = -0.9732
basinhopping repeatedly jumps to a random nearby point and runs a local search from there, keeping the best result. SciPy also offers differential_evolution, shgo and dual_annealing for global searches.
Maximizing instead of minimizing
SciPy only minimizes. To maximize f, minimize -f and flip the sign of the result. Here we find the box with the largest volume that can be folded from a 30 × 20 cm sheet by cutting squares of side h from the corners:
from scipy.optimize import minimize_scalar
def volume(h):
return (30 - 2 * h) * (20 - 2 * h) * h
res = minimize_scalar(lambda h: -volume(h), bounds=(0, 10), method="bounded")
print(f"cut squares of {res.x:.3f} cm")
print(f"max volume = {-res.fun:.1f} cm^3")cut squares of 3.924 cm
max volume = 1056.3 cm^3
Tip: Always check
res.successand look atres.messagewhen results look odd. A bad starting guess, a poorly scaled problem or a discontinuous function are the usual culprits.
Test yourself
Which attribute of an OptimizeResult holds the best input found?
- res.fun
- res.x
- res.best
- res.min
How do you maximize a function f with SciPy?
- minimize(f, maximize=True)
- Minimize -f and negate the resulting value
- Use optimize.maximum(f)
- It isn't possible
Why might minimize() return different answers for different starting points?
- It uses random numbers internally
- It is a local method that stops in the nearest valley
- It has a bug
- Because x0 is ignored