Guide to AI and Data Courses · Lecture Notes
Chapter 33: Optimization
A factory makes two products; machine hours and labor are limited, and the profit differs by product. The manager's question is simple: how many of each should we make? An engineer training a neural network is asking a similar question: which values of millions of weights make the loss smallest? Optimization is the course that writes both questions in the same language, an objective function and constraints, and solves them. These notes introduce the course and work through its three core ideas with small examples you can compute by hand.
Learning outcomes
- Formulating problems
- Write a problem stated in words as variables, an objective function and constraints.
- Linear programming
- Solve a two-variable linear program graphically and show that the optimum lies at a vertex.
- Convexity and optimality
- Check whether a function is convex; solve a simple equality-constrained problem with a Lagrange multiplier.
- Gradient methods
- Carry out a few steps of gradient descent by hand, show how step size affects convergence, and tell a Newton step apart.
- Place of the course
- State what separates optimization from machine learning, evolutionary optimization, reinforcement learning and artificial intelligence.
33.1What question does the course ask?
How do we find the values that make an objective function best?
Optimization studies how to find the values that minimize or maximize an objective function while respecting constraints. Training an AI model means searching for the weights that minimize a loss function, so an optimization method runs inside every learning algorithm.
The question of optimization is: among the values I can choose, without breaking the limits I must respect, which is best? "Best" is measured by a number: cost, loss, profit, time. The formula that gives this number is the objective function. The values we may choose are the variables, and the limits we must respect are the constraints. Splitting a problem into these three parts is the first habit of the course: what am I choosing, what am I minimizing or maximizing, and what limits apply?
The same problem can often be written in several ways, and the way it is written decides whether it is easy or hard to solve. If the objective and constraints are linear, the problem is a linear program and is solved reliably even at very large scale. If the objective is a convex function, every local optimum is also the global optimum, so a method cannot "get stuck". Outside these easy classes (neural network losses, integer decisions) the guarantees weaken, and intuition, experiments and a good choice of method come into play.
33.1.1Two sides of the course
The course joins two traditions in one theory: operations research (production, transport, scheduling) and machine learning (loss functions, stochastic gradient). The first focuses on constrained, usually linear or convex problems; the second on problems with very many variables that are unconstrained but not convex. Their shared tools are the gradient, the Hessian and convexity. The Machine Learning course uses training as a given; this course opens up the mathematics behind it.
33.1.2At a glance
| Criterion | Optimization |
|---|---|
| Approach | mathematical model of objective and constraints |
| Input | objective function and constraints |
| Output | optimal or near-optimal solution |
| Success measure | objective value, convergence rate |
| Math load | the theory itself |
| Data needs | none |
33.2A short history
| Year | Milestone |
|---|---|
| 1847 | Cauchy proposes steepest descent (gradient descent) for solving systems of equations. |
| 1947 | Dantzig develops the simplex method for linear programming. |
| 1951 | Kuhn and Tucker publish optimality conditions for constrained problems (KKT). |
| 1957 | Bellman's book Dynamic Programming is published. |
| 1984 | Karmarkar introduces a polynomial-time interior point method for linear programming. |
| 2014 | Kingma and Ba propose Adam, soon widely used to train deep networks. |
33.3Core concepts
The rest of the course is built on the concepts below. The following sections work through the most important ones with examples.
| Concept | Meaning |
|---|---|
| Objective function | The cost or loss to be minimized. |
| Constraints | Equalities and inequalities a solution must satisfy. |
| Linear programming | Linear objective and constraints; the simplex method. |
| Convexity | Every local optimum is also the global optimum. |
| Gradient descent | Small steps against the slope. |
| Stochastic gradient | Using a small part of the data at each step. |
| Lagrange multipliers | Folding constraints into the objective; KKT conditions. |
| Integer programming | Integer variables; often very hard. |
33.4Objective, constraints and linear programming
A linear program maximizes or minimizes a linear objective function over a region bounded by linear inequalities. With two variables we can draw the problem in the plane: each inequality is a half-plane, and their intersection is a polygon called the feasible region. The lines of constant objective value are parallel; we slide such a line in the direction of increasing profit and look at the last point of the region it touches.
If the feasible region is bounded and not empty, the best value of a linear objective is attained at a vertex of the region. So it is enough to try the vertices; the simplex method does this systematically by moving from vertex to vertex along edges.
A workshop makes two products; x and y are the quantities. Profit is 2x + 3y (the values are illustrative). Machine time: x + y ≤ 4; labor: x + 3y ≤ 6; also x, y ≥ 0. Maximize the profit.
- Find the vertices. The axes and the two lines give four vertices: (0, 0); x + y = 4 meets y = 0 at (4, 0); x + 3y = 6 meets x = 0 at (0, 2); the two lines meet where, subtracting, 2y = 2, so y = 1 and x = 3.
- Evaluate the objective. (0,0) → 0, (4,0) → 8, (3,1) → 9, (0,2) → 6.
- Pick the best. The largest profit is 9 at the vertex (3, 1): 3 units of the first product, 1 of the second. Both constraints are fully used there.
The number of vertices grows quickly with variables and constraints, so real problems use the simplex or an interior point method instead of counting vertices.
33.4.1Shadow price: the value of a constraint
The most useful by-product of linear programming is sensitivity information. If machine time goes from 4 hours to 5, the feasible region grows. The new vertex is where x + y = 5 meets x + 3y = 6: y = 0.5, x = 4.5; profit 2·4.5 + 3·0.5 = 10.5. One extra hour of machine time raised the profit by 1.5. This number is the shadow price of the machine constraint and equals the matching variable of the dual problem: from y1 + y2 = 2 and y1 + 3y2 = 3 we get y1 = 1.5, y2 = 0.5. A shadow price holds for small changes and answers the question "what is the most worth paying for one more unit of this resource?"
Solving an integer problem as a linear one and rounding the result. In the classic knapsack example let the values be 60, 100, 120, the weights 10, 20, 30 and the capacity 50; each item can be taken once. In the linear relaxation the first two items are taken whole and two thirds of the third: value 60 + 100 + 80 = 240. But if items cannot be split, the first two give 160, the last two give 220; the best is 220. Rounding the fractional solution (dropping the third item) gives 160, far from the best.
33.5Convexity and optimality conditions
Convexity is the most important structural property in optimization. A set is convex if it contains the line segment joining any two of its points. A function is convex if the chord between any two points of its graph lies on or above the graph.
For all a, b and 0 ≤ t ≤ 1: f(ta + (1−t)b) ≤ t·f(a) + (1−t)·f(b). For a twice-differentiable function this means the second derivative (the Hessian, in several variables) is nowhere negative. In a convex problem every local minimum is also a global minimum.
Let us test two functions with the midpoint criterion (t = 1/2).
- f(x) = x2. a = 1, b = 3: the midpoint is 2, f(2) = 4; the middle of the chord is (1 + 9)/2 = 5. 4 ≤ 5 holds. Also f″ = 2 ≥ 0: convex.
- f(x) = x4 − 2x2. a = −1, b = 1: the midpoint is 0, f(0) = 0; the middle of the chord is (−1 + −1)/2 = −1. 0 ≤ −1 fails: not convex. Indeed f″(x) = 12x2 − 4 is negative near the origin.
- Consequence. The second function has two separate valleys, x = −1 and x = 1, both with f = −1. Gradient descent picks the valley according to its starting point. In a convex problem there is no such dilemma.
33.5.1A constrained problem: the Lagrange multiplier
When the constraint is an equality, at the optimum the gradient of the objective is parallel to the gradient of the constraint: the objective cannot improve any further along the constraint surface. We write this by setting the gradient of L(x, λ) = f(x) − λ·g(x) to zero; λ is the Lagrange multiplier. The generalization of the same idea to inequality constraints is the KKT conditions.
Minimize x2 + y2 subject to x + y = 2. In other words, find the point of the line closest to the origin.
- Lagrangian. L = x2 + y2 − λ(x + y − 2).
- Set derivatives to zero. ∂L/∂x = 2x − λ = 0, ∂L/∂y = 2y − λ = 0; so x = y = λ/2.
- Insert the constraint. x + y = λ = 2, hence x = y = 1, f = 2.
- Interpret the multiplier. With the constraint x + y = c we would get x = y = c/2 and f = c2/2; at c = 2, df/dc = c = 2 = λ. The multiplier is the effect on the objective of relaxing the constraint by one unit, the same idea as the shadow price in a linear program.
Assuming every point with zero gradient is a minimum. For f(x) = x3 we have f′(0) = 0 but 0 is neither a minimum nor a maximum; for f(x, y) = x2 − y2 the origin is a saddle point. A zero gradient is only a candidate; in a convex problem the candidate is certainly a minimum, in general the second derivative (the Hessian) must be checked as well.
33.6Gradient descent, step size and Newton's method
When we cannot find the solution by a formula we proceed iteratively: choose a point, decide a direction and a step size, move to the new point. Gradient descent uses the negative gradient as the direction: x ← x − η·f′(x). The step size η (the learning rate in machine learning) decides the success of the method; too small and it is slow, too large and it overshoots the minimum.
For f(x) = x2 we have f′(x) = 2x, so the update is x ← (1 − 2η)·x. Start at x = 1.
- η = 0.1: x ← 0.8x; the steps 0.8, 0.64, 0.512, … approach zero slowly.
- η = 0.5: x ← 0; the solution in one step.
- η = 1: x ← −x; 1, −1, 1, … oscillates in place.
- η = 1.1: x ← −1.2x; 1, −1.2, 1.44, … diverges.
General rule: it converges when |1 − 2η| < 1, that is 0 < η < 1. The more curved the function, the smaller the allowed step: for f(x) = 5x2 the condition is η < 0.2.
The method that takes curvature into account is Newton's method. It approximates the function at the current point by a parabola and jumps to the bottom of the parabola: x ← x − f′(x)/f″(x). In several variables the Hessian matrix replaces f″; quasi-Newton methods such as BFGS estimate the Hessian without computing it.
f(x) = ex − 2x is convex; f′(x) = ex − 2, f″(x) = ex. The minimum is at x* = ln 2 ≈ 0.6931. Both methods start at x = 0.
- Newton. x1 = 0 − (1 − 2)/1 = 1; x2 = 1 − 0.718/2.718 ≈ 0.7358; x3 ≈ 0.6940; x4 ≈ 0.69315.
- Gradient descent, η = 0.5. x1 = 0 − 0.5(1 − 2) = 0.5; x2 ≈ 0.6756; x3 ≈ 0.6930; x4 ≈ 0.69315.
- Reading. Here η = 0.5 happens to be a good choice: at the minimum f″(ln 2) = 2, so 1/f″ = 0.5 and gradient descent resembles a Newton step. Newton tunes its own step size to the curvature; in gradient descent a person does the tuning.
At every step Newton must compute the Hessian and invert it; with millions of variables this is expensive. That is why deep learning prefers methods that use only the gradient, such as stochastic gradient, momentum and Adam.
Assuming one fixed learning rate will work on every problem. In the example above η = 1.1 diverges on one function and η = 0.1 converges slowly; on a function with different curvature the same number behaves quite differently. The step size is tuned to the curvature of the problem, and the loss curve is watched.
33.7How is the course taught?
33.7.1A typical workflow
Training a neural network is an optimization problem: the variables are the weights and the objective is the average loss. The problem is not convex, so stochastic gradient descent on mini-batches or Adam is used, and the loss curve is watched on a validation set.
33.7.2Topics over the semester
- Formulating problems: variables, objective, constraints
- Linear programming and the simplex method
- Duality and sensitivity analysis
- Convex sets and convex functions
- Convex problems: QP, SOCP, SDP
- Optimality conditions: Lagrange and KKT
- Gradient descent and step size selection
- Newton and quasi-Newton methods (BFGS)
- Constrained optimization and interior point methods
- Stochastic gradient, momentum and Adam
- Integer programming and branch and bound
- Dynamic programming
This is a typical semester; the order and coverage vary between universities.
33.7.3Skills you will gain
- modeling convex problems in CVXPY
- writing linear models with PuLP
- using scipy.optimize
- proving convexity
- monitoring and tuning convergence
33.7.4Try it yourself
The Try It: Training a Price Model slide in the presentation lets you solve a typical problem of this course yourself: A model predicts house prices as “price = w·area + b”; gradient descent moves its two weights toward the lowest loss. Click the map to set the start and change the learning rate.
33.8Are you ready for this course?
33.8.1Prerequisites
| Course | Why it is needed |
|---|---|
| Linear Algebra | gradient, Hessian, convexity |
| Calculus | derivatives, partial derivatives and Taylor series: the language of gradients and Hessians |
| Algorithms | dynamic programming, greedy methods and complexity |
33.8.2Ask yourself
For every "no", the right-hand column shows where to start. If you can say "yes" to most of them, you are ready.
| Question | If not, start with |
|---|---|
| Can you compute the gradient of a function of several variables? | Partial derivatives and the chain rule from calculus |
| Can you write the Taylor expansion of a function up to the second term? | Taylor series from calculus |
| Can you multiply a matrix by a vector and solve a linear system? | Linear Algebra |
| Can you update NumPy arrays step by step inside a loop in Python? | An intro programming course, then a short NumPy tutorial |
33.9Neighboring courses
33.9.1Where it overlaps
| Relation | Course | Shared ground |
|---|---|---|
| builds on | Machine Learning builds on this course | loss minimization, regularization |
| builds on | Artificial Neural Networks builds on this course | gradient descent, learning rate |
| builds on | This course builds on Linear Algebra | gradient, Hessian, convexity |
| shares methods | Shares methods with Artificial Intelligence | state-space search, constraint satisfaction |
| shares methods | Shares methods with Reinforcement Learning | dynamic programming, policy gradient |
| shares methods | Shares methods with Evolutionary and Metaheuristic Optimization | derivative-free and global optimization |
33.9.2Where it differs
- Evolutionary and Metaheuristic Optimization: Evolutionary methods search without derivatives; this course teaches methods that exploit problem structure (derivatives, convexity).
- Artificial Intelligence: AI starts by modeling a problem as an agent and an environment; optimization solves a mathematically stated problem.
- Machine Learning: ML lowers training loss but also wants success on new data; optimization only makes the given objective as good as possible.
- Reinforcement Learning: Reinforcement learning maximizes reward by trial and error; here the objective function is written down explicitly from the start.
33.10In practice
33.10.1Applications
| Area | What is done |
|---|---|
| Model training | Finding the weights that minimize the loss. |
| SVM | The maximum-margin separator: a convex problem. |
| Hyperparameter search | Choosing learning rate and regularization. |
| Logistics | Routing, transport and warehouse location. |
| Scheduling | Shifts, production and timetables. |
| Portfolio selection | Balancing return against risk. |
33.10.2Risks and ethics
| Risk | Explanation |
|---|---|
| The wrong objective | Optimizing what is measurable can defeat the real goal: a system that maximizes clicks alone promotes clickbait. |
| A forgotten constraint | A constraint left out of the model is ignored: the cheapest route may use a banned road, the best rota may skip legal rest. |
| Fragile optima | An optimum computed from estimated parameters can degrade badly under small errors; Markowitz portfolios are notoriously sensitive. |
| Poor scaling | Variables on wildly different scales slow a solver down or can lead it to a false "infeasible" verdict. |
These issues are discussed in depth in Explainable AI and AI Ethics.
33.10.3Tools and datasets
Tools: SciPy (scipy.optimize), CVXPY, Google OR-Tools, PuLP, Gurobi, PyTorch (torch.optim).
Classic example problems: Diet problem, Transportation problem, Knapsack problem, Traveling salesman, Markowitz portfolio, Rosenbrock function.
33.11Common misconceptions
Gradient descent always finds the best solution.
On non-convex problems it can get stuck in a local optimum or at a saddle point.
The larger the learning rate, the faster.
Too large a step overshoots the minimum and the loss diverges; too small a step drags training out.
Integer problems are solved by rounding.
Rounding the linear solution can break constraints or land far from the optimum.
The lowest loss means the best model.
Driving training loss to zero can mean overfitting; in AI the goal is generalization.
33.12Summary
- Optimization searches for the values of the variables that minimize or maximize an objective function while respecting constraints; a problem is written as variables, objective and constraints.
- The optimum of a linear program lies at a vertex of the feasible region; the shadow price of a constraint tells the value of a resource. Integer problems are not solved by rounding.
- In a convex problem every local minimum is global; convexity is checked with the midpoint criterion or the second derivative.
- In an equality-constrained problem the Lagrange multiplier is an extra unknown solved together with the constraint; its value is the effect on the objective of relaxing the constraint. A zero gradient is only a candidate.
- In gradient descent the step size is decisive (too large and it diverges); Newton's method uses curvature and converges in few steps but each step is expensive.
33.13Test Yourself
Maximize x + 2y subject to x + y ≤ 3, y ≤ 2, x, y ≥ 0. Find the vertices and solve.
Answer
Vertices: (0,0), (3,0), (1,2) (y = 2 meets x + y = 3), (0,2). Objective values 0, 3, 5, 4. The best is (1, 2), value 5.
Is f(x) = x3 convex, using the points a = −2, b = 0 and the midpoint criterion?
Answer
The midpoint is −1, f(−1) = −1; the middle of the chord is (−8 + 0)/2 = −4. −1 ≤ −4 fails, so x3 is not convex (f″ = 6x takes negative values).
Minimize x2 + 2y2 subject to x + y = 3. Solve with a Lagrange multiplier.
Answer
2x = λ, 4y = λ; so x = 2y. From the constraint 3y = 3, y = 1, x = 2, f = 4 + 2 = 6, λ = 4. (With x + y = c we get f = 2c2/3, whose derivative at c = 3 is 4: it agrees with λ.)
f(x) = (x − 3)2, start at x = 0, η = 0.25. Take two gradient descent steps. How many steps does Newton's method need?
Answer
f′(x) = 2(x − 3). x1 = 0 − 0.25·(−6) = 1.5; f′(1.5) = −3, x2 = 1.5 + 0.75 = 2.25. Newton: f″ = 2, x1 = 0 − (−6)/2 = 3; for a quadratic function, the exact solution in one step.
Gradient descent on f(x) = 5x2 with η = 0.25 starts at x = 1. Does it converge?
Answer
f′ = 10x, the update is x ← (1 − 10η)x = −1.5x. The iterates 1, −1.5, 2.25, … grow in size: it diverges. Convergence needs |1 − 10η| < 1, that is η < 0.2.
A logistics company finds 7.6 trucks in the solution of a linear program, but the number of trucks must be an integer. Is rounding to 8 enough? Think of the knapsack example (values 60, 100, 120; weights 10, 20, 30; capacity 50).
Answer
Not always. In the knapsack the linear solution has value 240 while the best integer solution is 220; and rounding can even fall to 160 (60 below the best). Rounding can break constraints or stay far from the optimum, which is why integer programming and methods such as branch and bound are needed.
33.14After this course
After this course, how training works in machine learning and neural networks becomes clear. From here you can move to evolutionary and metaheuristic optimization for problems without derivatives, reinforcement learning for sequential decisions, and operations research for allocating resources.
Courses that build on or extend this one: Machine Learning, Artificial Neural Networks.
Related careers: Operations researcher, Machine learning engineer, Logistics and planning analyst, Quantitative analyst.
33.15Further reading
- S. Boyd and L. Vandenberghe, Convex Optimization (2004), Chapters 2–4: convex sets, functions and problems, in far more depth and with more examples than these notes; the book is free to download from the authors' page.
- D. Bertsimas and J. Tsitsiklis, Introduction to Linear Optimization (1997): teaches the simplex method, duality and sensitivity analysis step by step.
- J. Nocedal and S. Wright, Numerical Optimization (2nd ed., 2006): gives gradient, Newton and quasi-Newton methods, step size selection and convergence analysis.
33.16References
- Boyd and Vandenberghe, Convex Optimization, Cambridge University Press, 2004.
- Nocedal and Wright, Numerical Optimization, 2nd ed., Springer, 2006.
- Bertsimas and Tsitsiklis, Introduction to Linear Optimization, Athena Scientific, 1997.
- Bottou, Curtis and Nocedal, "Optimization Methods for Large-Scale Machine Learning", SIAM Review 60(2), 2018.
Related pages: Slides · Slides (PDF) · Course page