TExcelTAD
Home › SciPy › SciPy Optimizers

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:

python · try it yourself
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.

python · try it yourself
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:

python · try it yourself
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:

python · try it yourself
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:

python · try it yourself
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.success and look at res.message when 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?

  1. res.fun
  2. res.x
  3. res.best
  4. res.min

How do you maximize a function f with SciPy?

  1. minimize(f, maximize=True)
  2. Minimize -f and negate the resulting value
  3. Use optimize.maximum(f)
  4. It isn't possible

Why might minimize() return different answers for different starting points?

  1. It uses random numbers internally
  2. It is a local method that stops in the nearest valley
  3. It has a bug
  4. Because x0 is ignored