Vector magnitude and cosine similarity
Vector magnitude and cosine similarity
The dot product in the previous chapter simultaneously contained information about length and direction.
This chapter separates them: magnitude measures size alone, and cosine similarity measures directional consistency alone.
Magnitude: How long is the vector?
Magnitude is the "straight-line distance" from the origin to the endpoint of the vector—an extension of the Pythagorean theorem to high-dimensional space.
L1 Norm
( |\mathbf{v}|_1 = \sum |v_i| )
Manhattan distance: walking along streets
L1 of (3,4) = 7
** L2 norm (default)
( $|\mathbf{v}|_2 = \sqrt{\sum v_i^2}$ )
Euclidean distance: flying in the air
L2 of (3,4) = 5
Unless otherwise specified, "magnitude" or ( $|\mathbf{v}|$ ) defaults to the L2 norm.
Unit vector: discarding length, keeping only direction
Any non-zero vector divided by its magnitude yields a unit vector with a length of 1:
[ \hat{\mathbf{v}} = \frac{\mathbf{v}}{|\mathbf{v}|} ]
The direction of the normalized vector remains unchanged, but its magnitude becomes 1.
Cosine similarity: only considers direction, not magnitude
Cosine similarity = performing a dot product after normalizing both vectors to unit vectors:
[ \text{cosine_sim}(\mathbf{a}, \mathbf{b}) = \frac{\mathbf{a}\cdot\mathbf{b}}{|\mathbf{a}||\mathbf{b}|} = \cos\theta ]
Directions are consistent
cos=1
Direction is perpendicular
cos=0
Opposite directions
cos=-1
Cosine similarity only cares about direction, not length.
v = (3,4) and w = (6,8) (w = 2v), the lengths differ by a factor of two, but cosine similarity = 1—because they have the exact same direction.
Real-life example
**Modulus: Measurement of distance
The straight-line distance from your home to school is 5 kilometers (L2 = 5), but walking along the streets takes 7 kilometers (L1 = 7).
Both measurement methods have their uses; L2 is mainly used in AI.
**Cosine Similarity: Matching music tastes
Zhang San listened to 100 songs, and Li Si listened to 10 songs. Using dot product, Zhang San's score is naturally higher.
However, using cosine similarity, we only look at whether the taste direction is consistent—Zhang San (active user) and Li Si (new user) can be fairly compared.
Mathematical definition
Deconstruct the core formula
[ \mathbf{a} \cdot \mathbf{b} = |\mathbf{a}| |\mathbf{b}| \cos\theta ]
Dot product = product of lengths $\times$ direction consistency. Conversely, you can calculate:
[ \cos\theta = \frac{\mathbf{a} \cdot \mathbf{b}}{|\mathbf{a}| |\mathbf{b}|} ]
Python hands-on practice
Example
import
numpy
as
np
v_runoob
=
np.
array
(
[
3
,
4
,
0
]
)
w_runoob
=
np.
array
(
[
6
,
8
,
0
]
)
2 times v
modulus length
norm_v
=
np.
linalg
.
norm
(
v_runoob
)
L2 default
norm_w
=
np.
linalg
.
norm
(
w_runoob
)
(
f
"||v|| = {norm_v:.1f}, ||w|| = {norm_w:.1f}"
)
5, 10
Normalization
unit_v
=
v_runoob / norm_v
unit_w
=
w_runoob / norm_w
(
"v normalization:"
,
unit_v
)
[0.6, 0.8, 0.]
(
"w normalization:"
,
unit_w
)
[0.6, 0.8, 0.] Exactly the same!
Cosine similarity
cos_sim
=
np.
dot
(
v_runoob
,
w_runoob
)
/
(
norm_v * norm_w
)
(
f
"Cosine similarity = {cos_sim:.4f}"
)
1.0
Batch calculate cosine similarity matrix
embeddings
=
np.
array
(
[
[
0.2
,
0.5
,
0.1
,
0.8
,
0.3
]
,
[
0.3
,
0.6
,
0.2
,
0.7
,
0.4
]
,
[
0.9
,
0.1
,
0.8
,
0.1
,
0.9
]
,
]
)
norms
=
np.
linalg
.
norm
(
embeddings
,
axis
=
1
,
keepdims
=
True
)
normalized
=
embeddings / norms
sim_matrix
=
normalized
@
normalized.
T
(
"\nCosine similarity matrix:"
)
(
np.
round
(
sim_matrix
,
3
)
)
Original prompt (Chinese, left untranslated)
||v|| = 5.0, ||w|| = 10.0
v 归一化: [0.6 0.8 0. ]
w 归一化: [0.6 0.8 0. ]
余弦相似度 = 1.0000
Cosine similarity matrix:
[[1. 0.996 0.146]
[0.996 1. 0.182]
[0.146 0.182 1. ]]
Application scenarios in AI
Semantic search and recommendation systems
After encoding the query and the document into vectors, they are sorted by cosine similarity to find the most relevant document. Google's semantic search and vector retrieval in RAG (Retrieval-Augmented Generation) both rely on cosine similarity.
Compared to dot product, cosine similarity is unaffected by vector magnitude—a long article's vector magnitude might be very large, but cosine similarity allows for a fair comparison of directionality with a short query.
Face recognition: Cosine similarity > Euclidean distance
Facial recognition models like FaceNet map faces to 128-dimensional embedding vectors. Whether two faces match is determined by cosine similarity—it is insensitive to lighting conditions and photo brightness (which affects vector magnitude).
Two photos of the same person under different lighting conditions have nearly identical embedding vector directions (cos ≈ 0.95+), but their magnitudes might differ significantly.
L2 regularization prevents overfitting
Adding ( \lambda|\mathbf{w}|^2 ) (weight decay) to the loss function penalizes excessively large weight magnitudes. A large weight magnitude means the model over-trusts certain features and has poor generalization ability. L2 regularization pulls it towards the origin.
Normalization in Batch Normalization
BN normalizes the activation values for each layer: subtracting the mean and dividing by the standard deviation to make the data have a norm-stable distribution. This uses the concept of the L2 norm to control the scale of the output of each layer.