minimize() takes a function fun that returns a single scalar value, and an initial guess x0, then searches for the input that makes fun's output as small as possible, returning a result object with .x, the optimal input found, and .fun, the minimum value achieved there. Like root(), it can get stuck in a local minimum rather than finding the true global minimum for functions with multiple valleys, and different method choices, like Nelder-Mead, BFGS, or L-BFGS-B, trade off speed, robustness, and whether they require the function's derivative.
1Understanding optimize.minimize()
minimize() takes a function fun that returns a single scalar value, and an initial guess x0, then searches for the input that makes fun's output as small as possible, returning a result object with .x, the optimal input found, and .fun, the minimum value achieved there. Like root(), it can get stuck in a local minimum rather than finding the true global minimum for functions with multiple valleys, and different method choices, like Nelder-Mead, BFGS, or L-BFGS-B, trade off speed, robustness, and whether they require the function's derivative.
minimize() only guarantees finding a local minimum near the starting guess, not necessarily the global minimum across the entire function — for functions with multiple local minima, try several different starting points, or use a global-optimization-specific method, if finding the true overall minimum matters.
from scipy import optimize
def f(x):
return (x - 3) ** 2 + 5
result = optimize.minimize(f, x0=0)
print(result.x, result.fun)2Practical Example
Here is a real-world application of optimize.minimize() showing how it is used in production SciPy code.
from scipy import optimize
def f(x):
return x[0]**2 + x[1]**2
result = optimize.minimize(f, x0=[3, 4])
print(result.x)3Best Practices
Follow these guidelines when working with optimize.minimize():
1. Try multiple different starting points for functions that might have several local minima, since minimize() can get stuck in whichever one is nearest the initial guess
2. Provide the function's gradient, via the jac parameter, when available, since many methods converge faster and more reliably with it than by estimating it numerically
3. Check result.success and inspect result.message when a minimization doesn't produce the expected result, rather than assuming it always converges correctly
Tip: minimize() only guarantees finding a local minimum near the starting guess, not necessarily the global minimum across the entire function — for functions with multiple local minima, try several different starting points, or use a global-optimization-specific method, if finding the true overall minimum matters.
from scipy import optimize
def f(x):
return (x - 3) ** 2 + 5
result = optimize.minimize(f, x0=0)
print(result.x, result.fun)