Optimisation basics
Choose the best design or setting systematically: define an objective function, search it by brute force, descend its slope with gradient descent, and beware of local minima.
Lesson 6 of 6 · 35 min · Self-paced · Free
Why optimise?
Engineering is full of choices with a "best" answer somewhere among many possibilities. Which calibration factor makes a sensor agree most closely with a ruler? Which controller gain gives the fastest response without overshoot? Which arm length lets a gripper reach every shelf while staying light? Guessing and checking by hand works for one or two options. Optimisation is the systematic version: describe what "best" means as a number, then let an algorithm search for the setting that makes that number as small (or as large) as possible.
The ingredients
Every optimisation problem has three parts:
- Decision variables: the things you are allowed to choose, such as a gain k.
- An objective function: a single number that measures how good a choice is. By convention we usually minimise it, so it is often called a cost or error.
- Constraints: limits on the choices, such as "the arm must weigh less than 400 g" or "the gain must be positive".
The hardest and most important step is usually the second: writing down, as a number, what you actually want.
A worked example: calibrating a sensor
A distance sensor reports raw values that should be proportional to distance. We place a target at five carefully measured distances and record the raw values (made-up data). We want the scale factor k such that distance ≈ k × reading.
A natural objective is the sum of squared errors: for each measurement, take the difference between the predicted and true distance, square it so that positive and negative errors both count, and add them up. A perfect k would score zero.
reference_mm = [100, 200, 300, 400, 500] # true distances, measured with a ruler
reading = [52, 98, 151, 203, 248] # raw sensor values (made-up)
def error(k):
"""Sum of squared differences between k × reading and the true distance, in mm²."""
return sum((k * r - d) ** 2 for r, d in zip(reading, reference_mm))
for k in [1.5, 2.0, 2.5]:
print(f"k = {k}: error = {error(k):9.1f} mm²")Output:
k = 1.5: error = 34199.5 mm²
k = 2.0: error = 88.0 mm²
k = 2.5: error = 34887.5 mm²(sum(... for ...) adds up the values produced by a loop, like a list comprehension without building the list.) The error is huge on either side and small near k = 2. The objective function turns a vague question — "which k fits best?" — into a precise one: "which k makes error(k) smallest?"
Brute force: grid search
The most reliable method is to try many values and keep the best. Here we try k from 1.50 to 2.50 in steps of 0.01:
reference_mm = [100, 200, 300, 400, 500]
reading = [52, 98, 151, 203, 248]
def error(k):
return sum((k * r - d) ** 2 for r, d in zip(reading, reference_mm))
best_k = 1.5
for i in range(150, 251):
k = i / 100
if error(k) < error(best_k):
best_k = k
print(f"Grid search: k = {best_k:.2f}, error = {error(best_k):.1f} mm²")Output:
Grid search: k = 2.00, error = 88.0 mm²Grid search is simple and hard to fool, but it has two weaknesses. Its answer is only as fine as the grid. And its cost explodes with the number of variables: 101 values for one variable is cheap, but 101 values for each of 5 variables is 101⁵, about ten billion evaluations. That is exponential growth again, from the lesson on complexity.
Gradient descent: walking downhill
Imagine standing on a hillside in thick fog, wanting to reach the valley floor. You cannot see the valley, but you can feel which way the ground slopes under your feet. So you take a step downhill, feel again, and repeat. That is gradient descent.
The slope of the objective at k is its derivative. For our error function it is
slope(k) = Σ 2 × r × (k × r − d)(you can check it numerically with a central difference, from the lesson on numerical differentiation). If the slope is positive, the error increases as k increases, so we should decrease k, and vice versa. Each step moves k against the slope, scaled by a step size (often called the learning rate):
k_new = k − rate × slope(k)reference_mm = [100, 200, 300, 400, 500]
reading = [52, 98, 151, 203, 248]
def slope(k):
return sum(2 * r * (k * r - d) for r, d in zip(reading, reference_mm))
def gradient_descent(k, rate, steps):
for _ in range(steps):
k = k - rate * slope(k)
return k
for rate in [1e-7, 1e-6, 3e-6, 1e-5]:
k = gradient_descent(1.0, rate, 20)
print(f"rate {rate:.0e}: k after 20 steps = {k:.4f}")
exact = sum(r * d for r, d in zip(reading, reference_mm)) / sum(r * r for r in reading)
print(f"Exact least-squares answer: k = {exact:.4f}")Output:
rate 1e-07: k after 20 steps = 1.4272
rate 1e-06: k after 20 steps = 1.9959
rate 3e-06: k after 20 steps = 1.9975
rate 1e-05: k after 20 steps = -77905.8195
Exact least-squares answer: k = 1.9975The step size matters enormously:
- Too small (10⁻⁷): every step is tiny, and after 20 steps k has crept only from 1.0 to about 1.43.
- About right (3 × 10⁻⁶): k reaches the exact answer, 1.9975, to four decimal places.
- Too large (10⁻⁵): each step overshoots the valley so far that it lands higher up the other side, the next step overshoots even more, and k flies off to nonsense. The method has diverged.
For this simple problem there is an exact formula (this is the method of least squares, which the Data Analysis module covers), and that is exactly why it is a good test: we can check that gradient descent finds the right answer before trusting it on problems with no formula. Notice too that grid search gave 2.00, the nearest grid point to 1.9975.
Local minima
Our error function has a single valley. Many real objectives have several. Consider this function, chosen as an illustration:
f(x) = x⁴ − 3x² + xIt has two valleys: a deep one near x = −1.30 and a shallower one near x = 1.13. Gradient descent only ever walks downhill, so which valley it ends in depends on where it starts:
def f(x):
return x**4 - 3 * x**2 + x
def dfdx(x):
return 4 * x**3 - 6 * x + 1
for start in [2.0, -2.0, 0.0]:
x = start
for _ in range(200):
x = x - 0.01 * dfdx(x)
print(f"start {start:+.1f} -> x = {x:+.4f}, f(x) = {f(x):+.4f}")Output:
start +2.0 -> x = +1.1309, f(x) = -1.0702
start -2.0 -> x = -1.3008, f(x) = -3.5139
start +0.0 -> x = -1.3008, f(x) = -3.5139Starting at +2, the method settles at x ≈ 1.13, a local minimum: lower than everything nearby, but not the lowest point overall. The global minimum, f ≈ −3.51 at x ≈ −1.30, is found only from the other starts. Gradient descent has no way to know that a deeper valley exists over the hill.
Common defences:
- Multiple starts: run from several starting points and keep the best result.
- A coarse grid search first, then gradient descent from the best grid point.
- Understand the problem: plotting or tabulating the objective often reveals how many valleys there are.
What you optimise is what you get
An optimiser will find the best answer to the question you wrote down, not the one you meant. Minimise only an arm's mass and it will become too weak to lift anything; minimise only a robot's travel time and it may drive dangerously fast. Real objectives combine goals and respect constraints — for example "minimise travel time, subject to speed below 0.5 m/s near people". Always check an optimised result against common sense and against the requirements it must meet.
Recap
- An optimisation problem has decision variables, an objective function and constraints.
- The sum of squared errors is a common objective for fitting a model to measurements.
- Grid search is simple and robust but becomes very expensive with many variables.
- Gradient descent steps against the slope: k_new = k − rate × slope(k). Too small a rate is slow; too large diverges.
- Gradient descent can stop in a local minimum; multiple starts or a coarse search first help.
- Test an optimiser on a problem with a known answer, and check that its result makes engineering sense.
Knowledge check
Check your understanding
Project
Programming project: tune it yourself
Use optimisation to choose two parameters.
- Extend the calibration model to distance ≈ k × reading + c, where c is an offset. Make up six measurements (label them as made-up) and write an error function of both k and c.
- Find the best k and c by grid search over a sensible range. Count the number of error evaluations.
- Implement gradient descent for both variables at once: compute the slope with respect to k and with respect to c (you can estimate each with a central difference), and update both at every step. Try at least three step sizes and record what happens.
- For f(x) = x⁴ − 3x² + x, run gradient descent from 21 starting points between −3 and 3. Count how many end in each valley.
- Write a paragraph on which method you would trust more, and why, for a problem with 10 variables.
No hardware is required.
Deliverables
- A Python 3 program with grid search and gradient descent for the two-parameter calibration
- A table of results for different step sizes
- The count of starts ending in each valley, and your paragraph
Go further
- Gradient descent — Wikipedia ↗
The method, the role of the step size and its behaviour on different kinds of function.
- Mathematical optimization — Wikipedia ↗
An overview of objective functions, constraints, local and global optima and the main families of methods.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.