Tensor and numerical foundations · Easy

Normalize Retrieval Embeddings

Problem 2 of 50 · Python and NumPy

Problem

Normalize each retrieval embedding to unit L2 length. Preserve zero vectors as zero vectors. Return a matrix with the original shape.

Compute norms per row, not across the whole collection; no epsilon is added to nonzero norms.

def normalize_embeddings(embeddings):

Constraints

  • embeddings is a nonempty N × D matrix with 1 ≤ N,D ≤ 32.
  • Finite entries have magnitude at most 1000.
  • Inputs satisfy these constraints; invalid-input handling is not graded. Use only Python standard library and NumPy.

Examples

Example 1

Arguments: [
  [
    [
      3,
      4
    ]
  ]
]
Expected result: [
  [
    0.6,
    0.8
  ]
]

The length of [3,4] is 5, giving [0.6,0.8].

Example 2

Arguments: [
  [
    [
      0,
      0
    ],
    [
      0,
      -2
    ]
  ]
]
Expected result: [
  [
    0,
    0
  ],
  [
    0,
    -1
  ]
]

The zero row stays zero; [0,-2] becomes [0,-1].

Sign in to solve this problem

Browse all coding problems · Learn the foundations