v9.1.1
Menu

Word Analogy Solver

mediumFREEWord EmbeddingsNLP 1: Foundations

Solve word analogies using vector arithmetic on word embeddings.

Word analogies take the form: "A is to B as C is to ?"

Using word vectors, the answer is the word whose vector is closest to: B⃗−A⃗+C⃗\vec{B} - \vec{A} + \vec{C}

Input: solve_analogy(a, b, c, embeddings)

  • a, b, c: the three query words (A, B, C), all present in the vocabulary
  • embeddings: a dict mapping each vocabulary word to its embedding vector (a list of floats)

Output: Return the word from the vocabulary (excluding A, B, C) whose vector is closest to B - A + C (using cosine similarity).

Example

Input
king queen man
5
king 1.0 0.5 0.0
queen 0.8 0.6 0.5
man 0.9 0.4 0.0
woman 0.7 0.5 0.5
child 0.2 0.3 0.8
Output
woman
Reasoning
  • Inputs: the query reads "king is to queen as man is to ?", so AA = king, BB = queen, CC = man. Each of the 5 vocabulary words maps to a 3-dimensional vector.
  • Target vector: B⃗−A⃗\vec{B} - \vec{A} captures the "male to female" offset, and adding it to C⃗\vec{C} applies that offset to man: [0.8−1.0+0.9, 0.6−0.5+0.4, 0.5−0+0]=[0.7,0.5,0.5][0.8-1.0+0.9,\ 0.6-0.5+0.4,\ 0.5-0+0] = [0.7, 0.5, 0.5], with length 0.99≈0.995\sqrt{0.99} \approx 0.995.
  • Candidates: king, queen and man are excluded, leaving woman and child.
  • woman [0.7,0.5,0.5][0.7, 0.5, 0.5]: the dot product with the target is 0.990.99, and both lengths are 0.99\sqrt{0.99}, so cos⁡θ=0.99/0.99=1.0\cos\theta = 0.99 / 0.99 = 1.0.
  • child [0.2,0.3,0.8][0.2, 0.3, 0.8]: dot product 0.14+0.15+0.40=0.690.14 + 0.15 + 0.40 = 0.69, length 0.77≈0.877\sqrt{0.77} \approx 0.877, so cos⁡θ≈0.69/(0.995×0.877)≈0.790\cos\theta \approx 0.69 / (0.995 \times 0.877) \approx 0.790.
  • Output: the largest similarity wins, giving woman. Notice that the target is not itself a vocabulary entry in general; here it happens to coincide with woman exactly, which is why its similarity is a perfect 1.0.

Constraints

  • Exclude the three query words from candidate answers
  • Use cosine similarity to find the closest word
  • All vectors have the same dimensionality
  • There will be a unique best answer

Learn this in

More from NLP 1: Foundations

solution.py

Test results

Sign in to run your code against the test cases.