v9.1.1
Menu

Embedding Lookup

easyFREEWord EmbeddingsNLP 1: Foundations

Given a simple embedding table (word-to-vector mapping) and a list of words, look up each word's embedding vector and return the average embedding.

Implement embedding_lookup(table, words):

  • table: a dict mapping each word to its embedding vector (a list of floats; all vectors have the same length)
  • words: a list of words to look up

In the example, the table is displayed as its entry count followed by one entry per line (word, then comma-separated floats, e.g. "cat 0.1,0.2,0.3"), and the last line lists the lookup words.

If a word is not in the table, skip it. Return the average as a list of floats, rounding each dimension to 4 decimal places.

Example

Input
3
cat 1.0,0.0
dog 0.0,1.0
fish 0.5,0.5
cat dog
Output
[0.5, 0.5]
Reasoning
  • Inputs: table maps three words to 2-dimensional vectors: cat →(1.0,0.0)\to (1.0, 0.0), dog →(0.0,1.0)\to (0.0, 1.0), fish →(0.5,0.5)\to (0.5, 0.5). words is the query: cat and dog.
  • Lookup: both query words are in the table, so k=2k = 2 vectors take part. Fish is in the table but not in the query, so it plays no role.
  • Average: each dimension is averaged on its own, eˉd=1k∑j=1kej,d\bar{e}_d = \frac{1}{k}\sum_{j=1}^{k} e_{j,d}:
    • dimension 1: 1.0+0.02=0.5\frac{1.0 + 0.0}{2} = 0.5
    • dimension 2: 0.0+1.02=0.5\frac{0.0 + 1.0}{2} = 0.5
  • Output: [0.5, 0.5], a list with one float per embedding dimension (here 2), each rounded to 4 decimal places.
  • Notice: a missing word is skipped entirely, so it changes the divisor kk rather than adding a zero vector. Querying cat and bird would give (1.0,0.0)(1.0, 0.0), cat's own vector, not (0.5,0.0)(0.5, 0.0).

Constraints

  • 1 ≤ n ≤ 20
  • Embedding dimensions are consistent
  • At least one lookup word will be in the table
  • Output: List of floats rounded to 4 decimal places

Learn this in

More from NLP 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.