📘
L2-Normalize an Embedding
Problem Statement
Contrastive training compares embeddings by cosine similarity, which requires them to live on the unit sphere. Implement the L2 normalization applied to every image and text embedding before the dot product.
Background
For a vector v, the L2-normalized version is
v^=∥v∥2v,∥v∥2=∑ivi2
After this, a dot product between two normalized vectors is their cosine similarity. Guard the zero vector: if the norm is 0, return the vector unchanged (all zeros) rather than dividing by zero.
Your Task
Implement:
def l2_normalize(v):
Return the normalized vector as a list rounded to 4 decimals.
Input Format
- v: list of numbers.
Output Format
- A list of floats rounded to 4 decimals.
Sample
print(l2_normalize([3.0, 4.0]))
Output:
[0.6, 0.8]
Example:
Input:
print(l2_normalize([3.0, 4.0]))
Output:
[0.6, 0.8]
Reasoning:
Norm = sqrt(9+16) = 5; 3/5 = 0.6, 4/5 = 0.8.
Constraints:
1 <= len(v) <= 4096.- The norm is the Euclidean (L2) norm.
- A zero vector is returned unchanged (no division by zero).
- Round every entry to 4 decimals; avoid
-0.0.
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.