Find the Minimum of a Function with scipy.optimize.minimize
Search for the input that makes a function smallest, choose a method, and keep the answer inside bounds.
- minimize with a starting point x0
- Reading .x, .fun and .success
- Methods and bounds
- (3, -1)
- value 2
- (1, 1)
- BFGS
- (2, -0.5)
- value 3.25
Search for the lowest point
The problem
Optimisation problems are everywhere: the cheapest design, the shortest time, the best parameters for a model. When the function is too complicated to differentiate and solve by hand, a numerical optimiser searches for the minimum.
Think of it like this
minimize is like a hiker in fog looking for the bottom of a valley. The hiker feels which way the ground slopes and keeps walking downhill until every direction goes up. Bounds are fences the hiker may not cross.
f(p)⛰️ The height of the groundx0=[0, 0]🚩 Where the hiker startsminimize(f, x0)🥾 Walk downhill until it stops going downbounds=[(0, 2), (-0.5, 0.5)]🚧 Fences the hiker cannot crossscipy.optimize.minimize(fun, x0) searches for the point where fun is smallest, starting from x0. It returns a result object with the point .x, the value .fun and whether it succeeded.
Key points
- The function takes one array of parameters and returns one number.
result.xis the best point andresult.funthe value there.method="BFGS"picks the algorithm; the default depends on bounds and constraints.- With
bounds, the minimum of f moves to the edge, (2, -0.5), with value 3.25.
When should you use it?
- Fitting model parameters by minimising an error.
- Engineering design: least material, lowest cost.
- Maximising profit or area by minimising its negative.
When not to use it
- Fitting a model to data points:
curve_fitwraps this for you. - Functions with many separate valleys: a local method may stop in the wrong one; try
scipy.optimize.differential_evolution.
Example code
import numpy as np
from scipy.optimize import minimize
# A bowl-shaped function with its minimum at (3, -1)
def f(p):
x, y = p
return (x - 3)**2 + (y + 1)**2 + 2
result = minimize(f, x0=[0, 0])
print("Minimum at:", result.x.round(4).tolist())
print(f"Minimum value: {result.fun:.4f}")
print("Success:", result.success)
# The Rosenbrock function: a curved valley, minimum at (1, 1)
def rosen(p):
x, y = p
return (1 - x)**2 + 100 * (y - x**2)**2
result = minimize(rosen, x0=[-1.2, 1], method="BFGS")
print("Rosenbrock minimum:", result.x.round(4).tolist())
# Bounds: keep x between 0 and 2, y between -0.5 and 0.5
result = minimize(f, x0=[1, 0], bounds=[(0, 2), (-0.5, 0.5)])
print("With bounds:", result.x.round(4).tolist(), f"value {result.fun:.4f}")
Result of running the code
Minimum at: [3.0, -1.0]
Minimum value: 2.0000
Success: True
Rosenbrock minimum: [1.0, 1.0]
With bounds: [2.0, -0.5] value 3.2500
Code explanation
f has its lowest point at (3, -1) with the value 2, and minimize finds it from the start x0=[0, 0]. The result has .x for the point, .fun for the function value and .success. The Rosenbrock function has a narrow curved valley that is hard for simple methods; BFGS still reaches its minimum at (1, 1). With bounds, x may only go up to 2 and y down to -0.5, so the best allowed point is (2, -0.5) with the value 3.25.
Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.
Practice exercises
Modify the runnable example with the exercises below to build understanding beyond copying the result.
- Change the function or the data and predict the result before running.
- Compare the numerical answer with the exact one from SymPy or a hand calculation.
- Plot the result with Matplotlib to see what the numbers mean.
Common mistakes
Writing the function with separate arguments
minimize passes one array, not several numbers.
def f(x, y):
def f(p):
x, y = p
Using minimize to find a maximum
To maximise, minimise the negative of the function.
minimize(profit, x0)
minimize(lambda p: -profit(p), x0)
Finished this lesson?
Mark it as learned to track your progress.
Practice with a challenge
Use what this lesson covers to solve a real problem. Each challenge runs in your browser with instant tests and an AI review.
- Mini-Batch Gradient Descent Train a linear model by updating the weights after every small batch of samples instead of the whole dataset. Medium
- Gradient Descent with Momentum Apply momentum updates, which keep part of the previous step so training speeds up along consistent directions. Easy
- Adam Optimizer Implement Adam, the default optimizer for deep learning, with moving averages and bias correction. Medium
Tools for this lesson
- Graph Plotter Online: Plot Points and FunctionsPlot points, a pasted table or functions like sin(x) online and download the graph as a PNG. Free graph maker that also gives you the Python Matplotlib code.
- How to Plot a Graph in Python Online (Matplotlib Examples)Plot a graph in Python online with Matplotlib: lines, functions like sin(x), data from a CSV, bar and pie charts. Run each example in your browser.
- NumPy Online: Run NumPy Code in Your BrowserA NumPy playground with no install: arrays, statistics, linear algebra, random numbers and broadcasting. NumPy 2, pandas and SciPy ready to import.