Module 4 · Intermediate · Many variables

Functions of several variables

Functions with two or more inputs, pictured as a landscape, a contour map and slices, using a model's loss over its two weights. The setting for gradients.

By theprogrammers team · · 11 min read

So far, every function in this course had one input: profit depended on price, height on time. Real things depend on several inputs at once. A house's price depends on its size, age and location. The height of the ground on a trek depends on how far east and how far north you are. And a machine learning model's error depends on every one of its weights at the same time, sometimes millions of them.

A function of several variables takes several numbers in and gives one number out. That's a small change in notation, but a big change in what you can picture. Here you'll learn three ways to see a function of two variables (a landscape, a contour map, and slices), using the loss of a real model as the example. These pictures are what make partial derivatives and the gradient, the next two lessons, easy to understand.

What you need first: maxima and minima with derivatives and what is a function?

Key terms

  • Function of several variables: a rule that takes two or more inputs and gives one output, such as f(x, y) = x² + y².
  • Surface: the 3D picture of a two-input function: inputs along the floor, output as height.
  • Contour line (or level curve): a line joining all inputs that give the same output, like the height lines on a trekking map.
  • Contour plot: a flat map of a function drawn with contour lines.
  • Slice: the one-input function you get by holding all but one input fixed.

One input, then two

Recall the students from covariance explained: study hours and marks. A simple model predicts marks from hours with a straight line:

predicted marks = w × hours + b

The model has two numbers to choose: the slope w and the intercept b. How good is a particular choice? Measure the mean squared error (MSE): the average of (actual − predicted)². The MSE depends on both w and b, so it's a function of two variables:

L(w, b) = average of (marks − (w × hours + b))²

import numpy as np
import matplotlib.pyplot as plt

hours = np.array([2, 3, 5, 6, 8, 9, 11, 12])
marks = np.array([45, 52, 50, 60, 68, 75, 74, 84])

def loss(w, b):
    return np.mean((marks - (w * hours + b)) ** 2)

for w, b in [(0, 60), (3, 40), (4, 35), (3.7, 37.5)]:
    print(f"w = {w:>3}, b = {b:>4}: loss = {loss(w, b):7.2f}")
w =   0, b =   60: loss =  181.25
w =   3, b =   40: loss =   23.00
w =   4, b =   35: loss =   12.25
w = 3.7, b = 37.5: loss =   11.02

Two inputs in, one number out. Different (w, b) pairs give different losses, and training the model means finding the pair with the lowest one. But with two inputs, there's no single curve to draw. How do you see the whole function?

Picture 1: a landscape

Treat (w, b) as a position on the floor and the loss as the height above it. The function becomes a surface, like a landscape:

W, B = np.meshgrid(np.linspace(1, 6.5, 120), np.linspace(20, 55, 120))
L = np.vectorize(loss)(W, B)

fig = plt.figure(figsize=(12, 4.8))
ax3d = fig.add_subplot(1, 2, 1, projection="3d")
ax3d.plot_surface(W, B, L, cmap="viridis", alpha=0.9)
ax3d.set_xlabel("w (slope)")
ax3d.set_ylabel("b (intercept)")
ax3d.set_zlabel("loss")
ax3d.set_title("The loss as a landscape")

ax2d = fig.add_subplot(1, 2, 2)
levels = [20, 40, 80, 160, 320]
cs = ax2d.contour(W, B, L, levels=levels, cmap="viridis")
ax2d.clabel(cs, fontsize=9)
ax2d.plot(3.7, 37.5, "*", color="#c2410c", markersize=16)
ax2d.set_xlabel("w (slope)")
ax2d.set_ylabel("b (intercept)")
ax2d.set_title("The same loss as a contour map")
plt.tight_layout()
plt.show()
Two views of the model's loss over slope w from 1 to 6.5 and intercept b from 20 to 55. On the left, a 3D surface shaped like a long, narrow valley running diagonally, with the lowest part in the middle. On the right, the same function as a contour map: nested, long, thin ellipses tilted diagonally, labelled with loss values from 20 near the centre to 320 at the outside, with an orange star at the centre, near w = 3.7, b = 37.5.
  • np.meshgrid makes a grid of (w, b) pairs covering the floor: W holds the w of every grid point and B the b.
  • np.vectorize(loss) runs loss on every grid point, giving the height L at each.
  • plot_surface draws the landscape in 3D; contour draws the contour map, and clabel writes the loss on each line.

The landscape is a valley. Somewhere at the bottom is the best (w, b). Training a model is walking down into that valley.

Picture 2: a contour map

A 3D surface looks good but is hard to read: parts hide behind others. The right-hand chart is the same function as a contour map, like the ones trekkers use. Each line joins all the (w, b) pairs with the same loss. Reading one is like reading a hill-station map:

  • Nested closed loops surround a valley floor (or a peak). The star marks the bottom.
  • Lines close together mean the loss changes fast: steep ground.
  • Lines far apart mean gentle ground.

The contours here are long, thin, tilted ellipses. That says something real about the model: you can trade a bigger slope for a smaller intercept and stay at almost the same loss (moving along the valley), but moving across the valley raises the loss quickly. That tilt comes from the inputs: hours are all positive, so raising w raises every prediction, which a lower b can largely cancel out. Long, thin valleys like this are exactly what makes gradient descent slow, and why feature scaling helps.

Experiment: the tilt comes from hours all being positive. What if you measure hours from the class average instead (hours − 7), so some are negative and some positive? Predict: will the valley still be tilted? Then run it:

centred = hours - hours.mean()        # hours from the average: -5, -4, ..., +5

def loss_centred(w, b):
    return np.mean((marks - (w * centred + b)) ** 2)

Wc, Bc = np.meshgrid(np.linspace(1, 6.5, 120), np.linspace(46, 81, 120))
Lc = np.vectorize(loss_centred)(Wc, Bc)
fig, ax = plt.subplots(figsize=(6, 4.5))
cs = ax.contour(Wc, Bc, Lc, levels=levels, cmap="viridis")
ax.clabel(cs, fontsize=9)
ax.set_xlabel("w (slope)")
ax.set_ylabel("b (marks at the average hours)")
ax.set_title("Centred hours: the valley is no longer tilted")
plt.show()
A contour map of the loss for the model using centred hours, over w from 1 to 6.5 and b from 46 to 81. The contours are ellipses with no tilt: their long axis runs exactly horizontally, along the w direction, and they're centred near w = 3.7 and b = 63.5.

The ellipses now line up with the axes: the best w no longer depends on b. Centring took away the trade-off between slope and intercept, so each can be found on its own. The intercept now means "predicted marks at the average study time", which is 63.5, the average mark. This is one reason standardising features (centring, then dividing by the spread) makes training easier.

Picture 3: slices

Hold one input fixed and vary the other, and you're back to a function of one variable, which you already know how to handle. Fix b = 37.5 and vary w; then fix w = 3.7 and vary b:

ws = np.linspace(1, 6.5, 200)
bs = np.linspace(20, 55, 200)
fig, axes = plt.subplots(1, 2, figsize=(11, 3.6))
axes[0].plot(ws, [loss(w, 37.5) for w in ws], color="#c2410c", linewidth=2.5)
axes[0].set_xlabel("w (with b fixed at 37.5)")
axes[0].set_title("Slice along w")
axes[1].plot(bs, [loss(3.7, b) for b in bs], color="#0f766e", linewidth=2.5)
axes[1].set_xlabel("b (with w fixed at 3.7)")
axes[1].set_title("Slice along b")
for ax in axes:
    ax.set_ylabel("loss")
plt.tight_layout()
plt.show()
Two U-shaped curves. On the left, the loss as w varies from 1 to 6.5 with b fixed at 37.5: a steep U with its bottom near w = 3.7. On the right, the loss as b varies from 20 to 55 with w fixed at 3.7: a much wider, gentler U with its bottom near b = 37.5.

Each slice is an ordinary U-shaped curve, with a slope you can measure. The slice along w is much steeper than the slice along b: a small change in slope moves every prediction, and moves the far-right students most, while a change in intercept moves all predictions by the same small amount. The slope of a slice is a partial derivative, the subject of partial derivatives explained.

More than two variables

With three inputs, the "landscape" would need four dimensions to draw; with a million, there's no picture at all. But everything still works:

  • The function still gives one number for every combination of inputs.
  • You can still slice it: hold every input fixed except one, and you get an ordinary curve.
  • The lowest point is still where no single direction goes downhill.

That's the beauty of the slice idea. It lets you handle a million-variable function one variable at a time, which is exactly how the gradient works.

Where machine learning uses this

  • Every loss is a function of all the weights. Linear regression with 10 features has 11 weights; a large language model has billions.
  • The loss landscape: researchers talk about valleys, plateaus and saddle points of the loss when explaining how training behaves.
  • Contour plots of the loss over two weights show why unscaled features make training slow: the valley becomes long and thin.
  • Regularisation adds a second landscape (a penalty on large weights) to the loss, reshaping the valley, as regularisation explained shows.

Common mistakes

  • Reading a contour map's lines as paths. They join points of equal height; you move across them to go uphill or downhill.
  • Ignoring spacing. Close lines mean steep; far apart means gentle.
  • Assuming the inputs act separately. In the loss, changing w changes which b is best: the valley is tilted.
  • Expecting a picture for many variables. Use slices and numbers instead.

Practice

  1. For f(x, y) = x² + y², what's f(3, 4)? Describe its contour lines.
Show the answer

f(3, 4) = 9 + 16 = 25. Each contour, such as f = 25, is a circle around the origin (radius 5 for f = 25), so the contour map is a set of circles, with a minimum at (0, 0).

  1. Predict, then check: which change raises the loss more from the best point, w up by 0.5 or b up by 5?
Show the answer
best = loss(3.7, 37.5)
print(round(loss(4.2, 37.5) - best, 2), round(loss(3.7, 42.5) - best, 2))
14.35 24.0

Raising b by 5 hurts more here: the loss rises by about 24, against about 14 for w. Raising w by 0.5 shifts the predictions by between 1 and 6 marks (0.5 × hours), while raising b by 5 shifts every prediction by a full 5. Per unit, though, w is far more sensitive: 0.5 of w did more than half the damage of 5 units of b.

  1. On a trekking map, contour lines are bunched together on the east side of a hill and spread out on the west. Which side is easier to climb?
Show the answer

The west: widely spaced lines mean the height changes slowly, so the slope is gentle.

  1. Write the loss for a model with three weights, predicting a flat's price from its size and age: price ≈ w₁ × size + w₂ × age + b. How many variables is the loss a function of?
Show the answer

L(w₁, w₂, b) = average of (price − (w₁ × size + w₂ × age + b))². Three variables: the data are fixed, and the weights are the inputs.

  1. Why is the loss thought of as a function of the weights, not of the data?
Show the answer

During training the data are fixed: they're the examples you have. What you can change, and are searching over, are the weights. So the loss is a landscape over weight values, and training looks for its lowest point.

Interview questions

What does a loss landscape represent?

The loss as a function of the model's parameters: each point in parameter space has a height equal to the loss on the training data. Training is a search for low points. Its shape (valleys, plateaus, saddle points, conditioning) determines how easily optimisers like gradient descent can find good parameters.

What does a contour plot of a two-parameter loss tell you?

Contours connect parameter pairs with equal loss. Concentric loops mark minima, line spacing shows steepness, and elongated ellipses indicate poor conditioning (very different curvature in different directions), which slows gradient descent and is often improved by feature scaling.

Key takeaways

  • A function of several variables takes several inputs and gives one output; a model's loss is a function of all its weights.
  • Picture two-input functions as a landscape (surface) or a contour map (lines of equal output).
  • On a contour map, nested loops mark minima and close lines mean steep ground.
  • A slice holds all but one input fixed, giving an ordinary one-variable curve.
  • Slices let you handle any number of variables one at a time, which leads to partial derivatives and the gradient.

Frequently asked questions

Can a function of several variables give several outputs?

Yes: a function can map several inputs to several outputs, like a neural network layer. This course treats one output at a time; a function with many outputs is handled as several one-output functions, which is what the Jacobian matrix collects.

What's the notation f: ℝ² → ℝ?

It means f takes two real numbers in (ℝ² is the plane of pairs) and gives one real number out. A loss with n weights is f: ℝⁿ → ℝ.

Do I need to draw 3D plots in practice?

Rarely. Contour plots and slices are usually clearer. 3D surfaces are mostly for building intuition, as here.

What to learn next

  1. Measure the slope in each direction in partial derivatives explained.
  2. Combine the slopes into one arrow in the gradient explained visually.
  3. Revisit one-variable minimisation in maxima and minima with derivatives.