PIXELBANKv8.2.1
Menu

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^=vv2,v2=ivi2\hat{v} = \frac{v}{\lVert v \rVert_2}, \qquad \lVert v \rVert_2 = \sqrt{\sum_i v_i^2}

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

Test Results

0/0
Run code to see test results.
L2-Normalize an Embedding - Easy | PixelBank