



Essential preprocessing technique that scales embedding vectors to unit length using L2 norm, ensuring consistent magnitude and making cosine similarity equivalent to dot product for faster computation.
Loading more......
On this page
Vector Normalization (L2 Normalization)
L2 normalization scales embedding vectors to a consistent magnitude by converting them to unit length. This ensures all vectors lie on the surface of a unit sphere, making similarity measures focus purely on direction rather than magnitude.
The standard approach adjusts each vector so its Euclidean length (L2 norm) becomes 1. This is done by dividing each component of the vector by the vector's original L2 norm.
||v|| = √(v₁² + v₂² + ... + vₙ²)
v_normalized = v / ||v||
Original vector: [3, 4]
For normalized vectors A and B:
cosine_similarity(A, B) = dot_product(A, B)
This enables:
import numpy as np
def normalize_l2(vector):
norm = np.linalg.norm(vector, ord=2)
# Add epsilon to avoid division by zero
epsilon = 1e-12
return vector / (norm + epsilon)
# Batch normalization
def normalize_batch(vectors):
norms = np.linalg.norm(vectors, axis=1, keepdims=True)
return vectors / (norms + 1e-12)
import torch
import torch.nn.functional as F
# Single vector
normalized = F.normalize(vector, p=2, dim=0)
# Batch of vectors
normalized_batch = F.normalize(vectors, p=2, dim=1)
import tensorflow as tf
normalized = tf.math.l2_normalize(vector, axis=-1)
from sklearn.preprocessing import normalize
normalized = normalize(vectors, norm='l2')
Problem: Division by zero if norm is 0 (all-zeros embedding)
Solution: Add epsilon (tiny value like 1e-12) to denominator
normalized = vector / (norm + 1e-12)
Problem: Very small norms can cause numerical instability
Solution:
Problem: Floating-point errors in high dimensions
Solution:
Action: Apply L2 normalization before similarity computation
Action: Normalization may be redundant (verify documentation)
No additional storage required (same dimensions)
# WRONG: Using cosine similarity without normalization
similarity = np.dot(embedding1, embedding2) # Not equivalent to cosine!
# RIGHT: Normalize first
emb1_norm = normalize_l2(embedding1)
emb2_norm = normalize_l2(embedding2)
similarity = np.dot(emb1_norm, emb2_norm) # Now equivalent to cosine
# WRONG: Double normalization
embedding = model.encode(text) # Already normalized
embedding = normalize_l2(embedding) # Redundant!
# RIGHT: Check documentation first
Normalization is a mathematical operation, free to implement.
Explore more items related to this one