Dot products and norms
Quick answer
For two real vectors of equal length, the dot product is the sum of pairwise products: a · b = a₁b₁ + … + aₙbₙ. In a linear predictor, this combines features with weights. A norm measures vector size; the L1 norm is the sum of absolute values and the L2 norm is the square root of the sum of squared values. The Euclidean distance between two vectors is the L2 norm of their difference. A dot product is not itself a distance. Feature units and scales influence all these calculations.
Compute a weighted prediction
A parcel takes 3 minutes per kilometer and 2 minutes per kilogram, plus a fixed 4-minute overhead. Pair distance and weight with the corresponding coefficients. zip pairs elements; validate lengths before pairing because ordinary zip silently stops at the shorter input.
def dot(a, b): if len(a) != len(b): raise ValueError("length mismatch") return sum(x * y for x, y in zip(a, b))
print(dot([5, 2], [3, 2]) + 4)print(dot([1, -2], [4, 3]))Expected output:
23-2The predicted duration is 5 × 3 + 2 × 2 + 4 = 23 minutes. Negative dot products are possible.
Compare norms and distance
Use NumPy locally, with real vectors only. The L2 norm of [3, -4] is 5; its L1 norm is 7. Subtract two points before measuring their separation. Componentwise addition and scalar multiplication preserve the vector length.
import numpy as npa = np.array([3, -4])b = np.array([0, 0])print(float(np.linalg.norm(a, ord=1)))print(float(np.linalg.norm(a, ord=2)))print(float(np.linalg.norm(a-b)))print((a + np.array([1, 2])).tolist())print((2*a).tolist())Expected output:
7.05.05.0[4, -2][6, -8]The L2 distance here is 5 because b is the origin. A point displaced equally along two different units should not be compared without deciding how those units are scaled.
Common mistakes
A large dot product can reflect large vector magnitudes rather than similar directions. A zero vector has zero norm, so dividing by its norm to normalize it is invalid. Squared L2 distance avoids a square root but is not the L2 norm itself.
Practice and next steps
Calculate the dot product of [2, 4] and [5, -1], then the L1 norm of their difference. Explain why the quantities answer different questions. Next, apply the same weights to many rows.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Dot products and norms — knowledge check
Apply linear algebra to small numerical fixtures.
What is [2,-1] · [3,4]?
What is the L1 norm of [-3,4]?
What is the L2 norm of [6,8]?
What is the squared Euclidean distance between [1,2] and [4,6]?
Why must you check vector lengths before using ordinary zip for a dot product?