Functions of Several Variables
Most real quantities depend on more than one input. The temperature on a metal plate depends on and , a loan payment depends on rate, term and amount, and a neural network's loss depends on millions of weights. This lesson covers how to picture such functions with level curves, and how limits and continuity work when there is more than one direction to approach from.
Inputs, outputs, domain
A function of two variables, , takes a point of the plane and returns a number. Its domain is the set of points where the formula makes sense:
| Function | Domain | Why |
|---|---|---|
| all of | polynomials are defined everywhere | |
| (a disc) | square root needs a non-negative input | |
| (a half-plane) | log needs a positive input | |
| everything except | no division by zero |
With three inputs, assigns a number to each point of space, like the air temperature in a room. With inputs we write or with a vector .
Graphs and level curves
The graph of is the surface from Surfaces in 3D. A flat picture is often more useful: the level curves (contours) for several values of . This is how a hiking map shows a mountain: closely spaced contours mean steep ground, widely spaced ones mean gentle slopes.
| Level curves | |
|---|---|
| circles centred at the origin | |
| parallel straight lines | |
| hyperbolas (and two crossing lines at ) | |
| ellipses, squashed in |
For the analogous objects are level surfaces, for example the spheres .
A loss surface
In machine learning, a model's loss is a function of its parameters. For a straight-line model fitted to data, the mean squared error is a function of two variables, . Its contour plot shows a valley whose lowest point is the best fit.
import numpy as np
import matplotlib.pyplot as plt
x = np.array([0.0, 1.0, 2.0, 3.0, 4.0])
y = np.array([1.1, 2.9, 5.2, 7.1, 8.8])
def loss(w, b):
pred = w * x[:, None, None] + b # broadcast over a grid of (w, b)
return np.mean((pred - y[:, None, None]) ** 2, axis=0)
W, B = np.meshgrid(np.linspace(0, 4, 121), np.linspace(-2, 4, 121))
L = loss(W, B)
i = np.unravel_index(np.argmin(L), L.shape)
print(f"grid minimum near w = {W[i]:.2f}, b = {B[i]:.2f}, loss = {L[i]:.4f}")
print("least squares:", np.round(np.polyfit(x, y, 1), 4))
plt.figure(figsize=(6, 4))
cs = plt.contour(W, B, L, levels=[0.05, 0.3, 1, 3, 8, 20], cmap="viridis")
plt.clabel(cs, fontsize=8)
plt.plot(W[i], B[i], "r*", markersize=12)
plt.xlabel("w (slope)"); plt.ylabel("b (intercept)"); plt.title("Level curves of the loss L(w, b)")grid minimum near w = 1.97, b = 1.10, loss = 0.0187
least squares: [1.96 1.1 ]
The contours are long thin ellipses: the loss changes slowly along one diagonal direction and quickly across it. That shape is what makes plain gradient descent zig-zag, and it is a good reason to scale features.
Limits in several variables
In one variable, can approach only from the left or the right. In the plane, can approach along infinitely many paths: straight lines, parabolas, spirals. The limit
exists only if gets close to whatever the path. So a quick way to show that a limit does not exist is to find two paths that give different values.
Take near the origin. Along the line :
The value depends on the slope : 0 along the x-axis (), 1 along , −1 along . So the limit at does not exist, even though every straight-line path gives a limit.
import numpy as np
f = lambda x, y: 2 * x * y / (x**2 + y**2)
g = lambda x, y: x**2 * y / (x**2 + y**2)
for name, path in [("y = 0 ", lambda t: (t, 0 * t)),
("y = x ", lambda t: (t, t)),
("y = -x", lambda t: (t, -t)),
("y = x²", lambda t: (t, t**2))]:
vals_f = [round(float(f(*path(t))), 4) for t in [0.1, 0.01, 0.001]]
vals_g = [round(float(g(*path(t))), 4) for t in [0.1, 0.01, 0.001]]
print(f"{name}: f -> {vals_f}, g -> {vals_g}")y = 0 : f -> [0.0, 0.0, 0.0], g -> [0.0, 0.0, 0.0]
y = x : f -> [1.0, 1.0, 1.0], g -> [0.05, 0.005, 0.0005]
y = -x: f -> [-1.0, -1.0, -1.0], g -> [-0.05, -0.005, -0.0005]
y = x²: f -> [0.198, 0.02, 0.002], g -> [0.0099, 0.0001, 0.0]
For every path heads to 0. Numbers can only suggest that; a proof needs a bound valid for all paths. Here , so , which goes to 0. The limit of is 0.
Continuity
is continuous at if is defined and equals the limit there. Sums, products and compositions of continuous functions are continuous, and so is a quotient where the denominator is non-zero, exactly as in one variable. The function above cannot be made continuous at the origin, whatever value you assign there.
In software
- Machine learning. Training is the search for a low point of a function of many variables (the loss). Level curves and 2D slices are how people visualise it.
- Graphics. A fragment shader is a function of (and time) returning a colour. Signed distance fields are functions of .
- Finance and engineering. A spreadsheet model with several input cells is a function of several variables; a "data table" in Excel scans it over a grid like the one above.
Exercises
Exercise 1: Domains
Describe the domain of (a) and (b) .
Answer
(a) , the region on and above the parabola. (b) every point except the line .
Solution
(a) The square root needs , so . (b) The denominator must be non-zero: , so remove the line .
Exercise 2: Level curves
Describe the level curves of for , 0 and 2.
Answer
Parabolas : the same upward parabola shifted to vertex , and .
Solution
means , so . Each level curve is the parabola moved up by .
Exercise 3: A limit that fails
Show that the limit of at does not exist.
Answer
Along the x-axis , along the y-axis , so there is no single limit.
Solution
Two paths give different values, so the limit does not exist.
Exercise 4: Locate the minimum on a grid (code)
Evaluate on a grid over with step 0.01 and report where the smallest value occurs.
Answer
Near , with .
Solution
Exact solution, for reference: setting the partial derivatives to zero (next lessons) gives and , whose solution is , , with minimum value .
import numpy as np
g = np.round(np.arange(-3, 3.0001, 0.01), 2)
X, Y = np.meshgrid(g, g)
F = (X - 1)**2 + 2 * (Y + 0.5)**2 + 0.5 * X * Y
i = np.unravel_index(np.argmin(F), F.shape)
print(X[i], Y[i], round(float(F[i]), 4))1.16 -0.65 -0.3064
Test yourself
What are the level curves of ?
- Parallel lines
- Circles centred at the origin
- Parabolas
- Hyperbolas
To prove that a limit at does NOT exist, it is enough to…
- find one path where the function has no limit or two paths that give different limits
- check the x-axis only
- show that is undefined
- show that the function is a fraction
On a contour map, closely spaced level curves mean…
- the function is constant there
- the function changes rapidly there
- a minimum
- a discontinuity