AI Wiki中文/EN

Inner products and angles

内积与角度

Turn vectors into a matching score, derive cosine and orthogonality, and separate geometric choices from semantic claims.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

How does an item receive a score?

Imagine describing an item with two coordinates: benefit and cost, both converted to agreed scales. Preference weights w=(2,−1)w=(2,-1) and item features x=(3,4)x=(3,4) produce the score 2×3−1×4=22\times3-1\times4=2. More benefit increases the score; more cost lowers it. This invented example shows how an operation between vectors can compress several measurements into one number.

The familiar operation is a dot product: multiply matching coordinates and add the results. It can represent a weighted score or, in Euclidean space, agreement between directions. A large dot product can also arise because a vector is long. Comparing directions alone requires normalization.

From algebra to geometry

For real coordinate vectors, the Euclidean inner product is the dot product:

⟨x,y⟩=x⊤y=∑i=1dxiyi,∥x∥2=x⊤x.\langle x,y\rangle=x^\top y=\sum_{i=1}^{d}x_i y_i,\qquad \|x\|_2=\sqrt{x^\top x}.

The second expression defines Euclidean length. An inner product is more general than this particular dot product. On a real vector space it is symmetric, linear in each argument, and satisfies ⟨x,x⟩>0\langle x,x\rangle>0 when x≠0x\ne0. For example, ∑iwixiyi\sum_iw_i x_i y_i is an inner product when all wi>0w_i>0, changing the coordinate scales of the geometry. Negative weights need not preserve positive definiteness. MML, Section 3.2

Why does dividing a dot product by the two lengths produce a number between -1 and 1? For any real tt:

0≤∥x−ty∥22=∥x∥22−2tx⊤y+t2∥y∥22.0\leq\|x-ty\|_2^2=\|x\|_2^2-2t x^\top y+t^2\|y\|_2^2.

For y≠0y\ne0, substitute t=(x⊤y)/∥y∥22t=(x^\top y)/\|y\|_2^2 and rearrange to obtain the Cauchy–Schwarz inequality:

∣x⊤y∣≤∥x∥2∥y∥2,cos⁡θ=x⊤y∥x∥2∥y∥2(x,y≠0).|x^\top y|\leq\|x\|_2\|y\|_2,\qquad \cos\theta=\frac{x^\top y}{\|x\|_2\|y\|_2}\quad(x,y\ne0).

Cosine compares directions. Two nonzero vectors with a zero inner product are orthogonal under that inner product. Cosine 1 indicates the same direction, and -1 the opposite direction. A zero vector has no defined direction, so the cosine formula cannot be applied to it directly. Deep Learning, Sections 2.5–2.6

Orthogonality depends on the chosen geometry. The ordinary dot product of x=(1,2)x=(1,2) and y=(2,−1)y=(2,-1) is zero. Giving the first coordinate weight 4 and the second weight 1 changes the weighted inner product to 6. The vectors are perpendicular in one geometry but not the other.

Compare dot product and cosine

This complete Python program uses teaching inputs of moderate numerical magnitude. fsum improves summation and hypot calculates Euclidean length; this is still not a numerical library covering every extreme floating-point value.

import math

def dot(x, y):
    if len(x) != len(y):
        raise ValueError("dimension mismatch")
    return math.fsum(a * b for a, b in zip(x, y))

def cosine(x, y):
    score = dot(x, y)
    nx, ny = math.hypot(*x), math.hypot(*y)
    if nx == 0 or ny == 0:
        raise ValueError("zero vector has no direction")
    return max(-1.0, min(1.0, score / (nx * ny)))

x, y = [1, 2], [2, -1]
assert dot(x, y) == 0
assert abs(cosine(x, [10, 20]) - 1) < 1e-12
assert dot(x, [10, 20]) == 50
assert dot(x, [4 * y[0], y[1]]) == 6
try:
    cosine(x, [0, 0])
    raise AssertionError("zero vector was accepted")
except ValueError:
    pass

Both operations scan dd entries in O(d)O(d) time. Apart from iterators and scalar accumulators, no result vector of length dd is required. Clipping to [−1,1][-1,1] prevents small rounding errors from disrupting a later inverse-cosine calculation; it does not repair invalid input data.

Similar cosine does not establish similar meaning

Suppose one document vector is exactly ten times another. Its dot product with a query scales accordingly, while cosine is unchanged. The appropriate choice depends on the task. Length might carry useful intensity information or merely reflect document length. Normalizing is not an unconditional improvement.

Orthogonality is a geometric relation under an inner product, not automatically statistical independence. An embedding cosine score is not a probability either: 0.8 does not mean an 80% chance of synonymy. Task labels, retrieval evaluations, or other external evidence establish whether the score is useful.

Complex inner products require complex conjugation; copying this real-valued dot product is insufficient. Before transferring an implementation to a new mathematical setting, check its domain and conventions.

Change length and track the invariants

  1. Multiply a nonzero vector yy by positive 10. What happens to dot product and cosine? Answer: the dot product increases tenfold; cosine is unchanged.
  2. Multiply by -1 instead. Answer: both change sign, reflecting the reversed direction.
  3. Do weights 0 and 1 define an inner product on the two-dimensional space? Answer: no. The nonzero vector (1,0)(1,0) has zero self-product, violating positive definiteness.
  4. Construct candidates with equal cosine and different dot products. Example: for query (1,2)(1,2), candidates (1,2)(1,2) and (10,20)(10,20) both have cosine 1, but dot products 5 and 50.

Where models use inner products

Linear predictors, kernel methods, and attention all convert pairs of objects into numerical scores. Attention additionally scales dot products and uses Softmax to turn a collection of scores into weights; each step changes the numbers and their interpretation. Orthogonal projection uses inner products to find a closest linear approximation. Following these connections links matching scores in retrieval to the geometry of least squares.

Make a prediction, then check

Multiply a candidate vector by positive 5 while keeping the query fixed. What happens to cosine similarity?

Choose one answer

Learning objectives

  • Derive the cosine range from a nonnegative squared length.
  • Distinguish dot product, cosine, orthogonality, and statistical independence.

Prerequisites & connections

Explore related knowledge →

References

  1. Mathematics for Machine Learning — mathematical foundations (2024-01-15 draft)
    Marc Peter Deisenroth; A. Aldo Faisal; Cheng Soon Ong · 2020
  2. Deep Learning — Chapter 2: Linear Algebra
    Ian Goodfellow; Yoshua Bengio; Aaron Courville · 2016

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-05 · Codex technical check: cited-source comparison, re-derivation and recalculation, bilingual argument comparison, and executed Python assertions; no independent human peer review.

  • Rederived Cauchy–Schwarz from a nonnegative square; checked nonzero-vector and real-domain conditions.
  • Recomputed ordinary product 0, weighted product 6, and cosine 1 for aligned vectors; code rejects zero vectors.
  • Compared the main arguments, numerical examples, exercises, and answers across languages; structural checks additionally compare display equations, source lists, and code.
  • Reviewed the answer-label rendering fix: only Markdown emphasis markers changed to strong tags; normalized text and all code are identical.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.