You cut diagonally across a field: 3 kilometres east and 4 kilometres north. The town you're heading for is straight east along the main road. How much of your walk actually got you closer to town? Only the eastward part: 3 km. The northward 4 km took you sideways. Splitting a movement into "the part along a direction" and "the part sideways to it" is called projection.
At noon, the sun casts a pole's shadow straight down onto the ground: the shadow is the pole's projection onto the ground. Vector projection is the same idea for arrows, and it answers questions machine learning keeps asking: how far is this point from the boundary? Which direction does the data spread out along? This lesson builds projection from the walk and the shadow, derives the distance from a point to a line, and ends with the formula for the margin of a support vector machine.
What you need first: the dot product explained and L1 and L2 norms explained.
Key terms
- Unit vector: a vector of length 1. It describes a pure direction, such as "east" or "north-east".
- Scalar projection: how far one vector goes along a direction. It's a single number, negative if it goes backwards.
- Vector projection: the arrow along that direction with that length: the "shadow" of the vector.
- Perpendicular component: what's left over, at right angles to the direction.
- Margin: in an SVM, the width of the empty street between the two classes.
How far along a direction?
Along an axis: easy
Your walk is a = (3, 4). The road east is the direction (1, 0). The part of the walk along the road is just the first number, 3, and the dot product gives it too: (3, 4) · (1, 0) = 3.
Along any direction: use a unit vector
Now suppose the road runs north-east. A direction of length 1 pointing north-east is u = (1, 1) ÷ √2 ≈ (0.707, 0.707). Take the dot product again:
import numpy as np
import matplotlib.pyplot as plt
walk = np.array([3.0, 4.0])
east = np.array([1.0, 0.0])
north_east = np.array([1.0, 1.0]) / np.sqrt(2)
print(f"length of north_east: {np.linalg.norm(north_east):.3f}")
print(f"progress along the east road: {walk @ east:.3f} km")
print(f"progress along the north-east road: {walk @ north_east:.3f} km")
length of north_east: 1.000
progress along the east road: 3.000 km
progress along the north-east road: 4.950 km
Along the east road, 3 km, as expected. Along a north-east road, 4.95 km: more than either 3 or 4, because your walk was mostly north-east already. The dot product with a unit vector gives the distance travelled along it.
Why does dotting with a unit vector give the distance along it? From the dot product lesson, a · u = ‖a‖ × ‖u‖ × cos θ, and ‖u‖ = 1, so a · u = ‖a‖ cos θ. And ‖a‖ cos θ is exactly the length of the shadow: the side next to the angle in a right-angled triangle whose long side is ‖a‖.
When the direction isn't length 1
Directions often come as any vector w, such as the weights of a model. Divide by its length first to turn it into a unit vector:
scalar projection of a onto w = (a · w) ÷ ‖w‖
Read it as "the dot product of a and w, divided by the length of w". Check that the length of w doesn't matter, only its direction:
for w in [np.array([1.0, 1.0]), np.array([5.0, 5.0]), np.array([0.2, 0.2])]:
print(f"w = {w}: (a · w) / ‖w‖ = {walk @ w / np.linalg.norm(w):.3f}")
w = [1. 1.]: (a · w) / ‖w‖ = 4.950
w = [5. 5.]: (a · w) / ‖w‖ = 4.950
w = [0.2 0.2]: (a · w) / ‖w‖ = 4.950
All three point north-east, so they give the same answer. That's the point of dividing by ‖w‖.
The shadow and what's left over
The vector projection is the shadow as an arrow: go that distance along the unit direction.
projection of a onto w = ((a · w) ÷ ‖w‖²) × w
It's the scalar projection, (a · w) ÷ ‖w‖, times the unit direction, w ÷ ‖w‖: the two ‖w‖s multiply to ‖w‖². What's left over, a minus the projection, is the perpendicular component, and it should be at right angles to w:
w = np.array([1.0, 1.0])
shadow = (walk @ w) / (w @ w) * w
leftover = walk - shadow
print("shadow (along w): ", shadow)
print("leftover (sideways): ", leftover)
print("shadow + leftover: ", shadow + leftover)
print(f"leftover · w = {leftover @ w:.3f} (0 means at right angles)")
shadow (along w): [3.5 3.5]
leftover (sideways): [-0.5 0.5]
shadow + leftover: [3. 4.]
leftover · w = 0.000 (0 means at right angles)
fig, ax = plt.subplots(figsize=(6, 6))
arrow = dict(head_width=0.12, length_includes_head=True)
ax.arrow(0, 0, *walk, color="black", **arrow)
ax.arrow(0, 0, *shadow, color="#c2410c", width=0.04, **arrow)
ax.plot([shadow[0], walk[0]], [shadow[1], walk[1]], color="#1f5fbf", linestyle="--", linewidth=2)
ax.plot([-0.5, 5], [-0.5, 5], color="#9ca3af", linewidth=1, zorder=0)
ax.text(-0.3, 3.6, "a = your walk (3, 4)", fontsize=11)
ax.text(3.7, 2.8, "shadow along w\n(3.5, 3.5)", color="#c2410c", fontsize=11)
ax.text(3.3, 4.1, "leftover,\nat right angles", color="#1f5fbf", fontsize=11)
ax.text(3.4, 5.15, "direction of w", color="#6b7280", fontsize=10)
ax.set_xlim(-0.5, 5.5)
ax.set_ylim(-0.5, 5.5)
ax.set_aspect("equal")
ax.grid(True, color="#e5e7eb")
ax.set_axisbelow(True)
ax.set_title("Projection: split a into a part along w and a part across it")
plt.show()
The distance from a point to a line
In the dot product lesson, a classifier scored points with w · x + b, and the boundary was the line where the score is 0. The score grew as points moved away from the line, but it wasn't a distance. Projection turns it into one.
Pick any point x₀ on the line, so w · x₀ + b = 0. The distance from a point x to the line is how far the arrow from x₀ to x goes in the direction of w, because w points straight across the line:
- distance = (x − x₀) · w ÷ ‖w‖, the scalar projection.
- Multiply out the top: w · x − w · x₀.
- Since x₀ is on the line, w · x₀ = −b, so the top is w · x + b.
distance from x to the line = (w · x + b) ÷ ‖w‖
Read it as "the score divided by the length of w". The sign says which side; drop it for the plain distance. Check with the boundary from the dot product lesson, w = (1, 1) and b = −3, and compare with a brute-force answer: try 100,001 points along the line and keep the closest:
w, b = np.array([1.0, 1.0]), -3.0
t = np.linspace(-50, 50, 100001)
line_points = np.column_stack([t, 3 - t]) # every point has x₁ + x₂ = 3
for x in [np.array([3.0, 2.0]), np.array([1.0, 1.0]), np.array([4.0, 4.0])]:
formula = (w @ x + b) / np.linalg.norm(w)
brute_force = np.min(np.linalg.norm(line_points - x, axis=1))
print(f"point {tuple(x.tolist())}: score {w @ x + b:4.1f}, formula {formula:6.3f}, brute force {brute_force:.3f}")
point (3.0, 2.0): score 2.0, formula 1.414, brute force 1.414
point (1.0, 1.0): score -1.0, formula -0.707, brute force 0.707
point (4.0, 4.0): score 5.0, formula 3.536, brute force 3.536
The formula and the brute-force search agree to three decimal places for every point. The formula gives a sign as well: (1, 1) is 0.707 away on the negative side. Notice that (4, 4) has a score of 5 but is only 3.536 away: the score is the distance times ‖w‖ = √2 ≈ 1.414.
The margin of a support vector machine
Here's the catch with scores: double w and b and you get the same line, but every score doubles. So the score alone can't say how far away a point is. Only score ÷ ‖w‖ can.
for scale in [1, 2, 10]:
w_s, b_s = scale * w, scale * b
x = np.array([3.0, 2.0])
print(f"w = {w_s}, b = {b_s:5.1f}: score {w_s @ x + b_s:5.1f}, distance {(w_s @ x + b_s) / np.linalg.norm(w_s):.3f}")
w = [1. 1.], b = -3.0: score 2.0, distance 1.414
w = [2. 2.], b = -6.0: score 4.0, distance 1.414
w = [10. 10.], b = -30.0: score 20.0, distance 1.414
A support vector machine uses this freedom to set a scale: it chooses w and b so that the points closest to the boundary, the support vectors, have a score of exactly +1 or −1. Two parallel lines, w · x + b = +1 and w · x + b = −1, then mark the edges of the empty "street" between the classes. By the distance formula:
- each edge is 1 ÷ ‖w‖ from the middle line, and
- the full width of the street, the margin, is 2 ÷ ‖w‖.
That one line explains the whole SVM idea: to make the margin as wide as possible, make ‖w‖ as small as possible, while every point still has a score of at least +1 on its own side (or at most −1 on the other). The SVM lessons build on exactly this.
rng = np.random.default_rng(0)
w, b = np.array([1.0, 1.0]), -3.0 # boundary x₁ + x₂ = 3, margin 2 / √2
positive = rng.uniform(0, 5, size=(200, 2))
positive = positive[positive @ w + b >= 1][:12] # points with score at least +1
negative = rng.uniform(-2, 3, size=(200, 2))
negative = negative[negative @ w + b <= -1][:12] # points with score at most -1
xs = np.linspace(-1, 6, 50)
fig, ax = plt.subplots(figsize=(6.5, 7))
ax.fill_between(xs, 2 - xs, 4 - xs, color="#fde68a", alpha=0.6, label=f"Margin: 2 / ‖w‖ = {2 / np.linalg.norm(w):.2f}")
ax.plot(xs, 3 - xs, color="black", linewidth=2, label="w · x + b = 0")
ax.plot(xs, 4 - xs, color="black", linestyle="--", label="w · x + b = ±1")
ax.plot(xs, 2 - xs, color="black", linestyle="--")
ax.scatter(*positive.T, color="#16a34a", label="Score ≥ +1")
ax.scatter(*negative.T, color="#dc2626", label="Score ≤ −1")
ax.set_xlim(-1, 5)
ax.set_ylim(-1, 5)
ax.set_aspect("equal")
ax.set_xlabel("x₁")
ax.set_ylabel("x₂")
ax.set_title("The SVM street: its width is 2 / ‖w‖")
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.12), ncol=2, fontsize=9)
plt.tight_layout()
plt.show()
Where machine learning uses projection
- Support vector machines: the margin is 2 ÷ ‖w‖, and the distance of any point from the boundary is its score divided by ‖w‖.
- Logistic regression: its score w · x + b, scaled by ‖w‖, is a signed distance from the boundary, which the sigmoid turns into a probability.
- PCA: finds the directions along which the data spreads out most, then projects every row onto them to keep the important part and drop the rest.
- Linear regression: the least squares prediction is the projection of the target values onto the space the features can reach. The residuals are the "leftover", at right angles to every feature.
Common mistakes
- Forgetting to divide by ‖w‖. a · w is only the distance along w when w has length 1. Otherwise it's the distance times ‖w‖.
- Mixing up scalar and vector projection. The scalar projection is a number (how far); the vector projection is an arrow (the shadow).
- Dividing by ‖w‖ instead of ‖w‖² for the vector projection. One ‖w‖ makes the length right; the other turns w into a unit direction.
- Treating classifier scores as distances. A score of 4 from one model and 2 from another don't compare unless you divide each by its ‖w‖.
Practice
- Find the scalar projection of (2, 6) onto the direction (3, 4) by hand.
Show the answer
a · w = 2 × 3 + 6 × 4 = 30, and ‖w‖ = √(9 + 16) = 5, so the scalar projection is 30 ÷ 5 = 6.
a, w = np.array([2.0, 6.0]), np.array([3.0, 4.0])
print(a @ w / np.linalg.norm(w))
6.0
- What's the vector projection of (2, 6) onto (3, 4)? Check that the leftover is at right angles to (3, 4).
Show the answer
(30 ÷ 25) × (3, 4) = 1.2 × (3, 4) = (3.6, 4.8). The leftover is (2 − 3.6, 6 − 4.8) = (−1.6, 1.2), and (−1.6, 1.2) · (3, 4) = −4.8 + 4.8 = 0.
shadow = (a @ w) / (w @ w) * w
print(shadow, round(float((a - shadow) @ w), 6))
[3.6 4.8] 0.0
- A boundary is 3x₁ + 4x₂ − 10 = 0. How far is the point (4, 2) from it, and on which side?
Show the answer
Score = 3 × 4 + 4 × 2 − 10 = 10, and ‖w‖ = 5, so the distance is 10 ÷ 5 = 2, on the positive side.
- An SVM has learnt w = (0.6, 0.8). How wide is its margin? If another SVM on different data has w = (3, 4), which margin is wider?
Show the answer
‖(0.6, 0.8)‖ = 1, so its margin is 2 ÷ 1 = 2. ‖(3, 4)‖ = 5, so the other margin is 2 ÷ 5 = 0.4. The first is five times wider: smaller weights mean a wider margin.
Interview questions
How do you compute the distance from a point to a hyperplane?
For the hyperplane w · x + b = 0, the signed distance from a point x is (w · x + b) ÷ ‖w‖. It comes from projecting the vector from any point on the hyperplane to x onto the unit normal w ÷ ‖w‖. The sign shows the side.
Why does an SVM minimise ‖w‖?
With the scale fixed so that the closest points have scores of ±1, the margin between the two classes is 2 ÷ ‖w‖. Maximising the margin is therefore the same as minimising ‖w‖ (in practice ½‖w‖², which is smoother), subject to every training point being on the correct side with a score of at least 1 in size.
Key takeaways
- The scalar projection (a · w) ÷ ‖w‖ is how far a goes in the direction of w.
- The vector projection ((a · w) ÷ ‖w‖²) × w is the shadow; what's left over is at right angles to w.
- The distance from a point to the line w · x + b = 0 is (w · x + b) ÷ ‖w‖: the score divided by the length of w.
- Scaling w and b changes the scores but not the line, so only score ÷ ‖w‖ is a true distance.
- An SVM's margin is 2 ÷ ‖w‖, so a wider margin means a smaller ‖w‖.
Frequently asked questions
What is the difference between projection and the dot product?
The dot product a · w mixes together how far a goes along w and how long w is. The scalar projection divides out the length of w, leaving just the distance along the direction. When w is a unit vector, the two are the same.
Is projection used in PCA?
Yes. PCA finds unit directions, the principal components, and represents each data point by its scalar projections onto them. Keeping only the first few projections compresses the data while keeping most of its spread.
Can you project onto more than one direction at once?
Yes: you can project onto a plane or a higher-dimensional flat space. When the directions are at right angles to each other, the projection is just the sum of the projections onto each one. Least squares regression is exactly such a projection, written with matrices.
What to learn next
- Learn how SVMs maximise the margin while keeping every point on the right side in Lagrange multipliers explained, the next maths lesson.
- See margins and support vectors in practice in support vector machines explained.
- Revisit scores and boundaries in the dot product explained.