📘
Word Analogy Solver
MediumWord Embeddings
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
Input format:
- Line 1: Three words (A B C) — the analogy query
- Line 2: Number of words in vocabulary N
- Lines 3 to N+2: word followed by its embedding vector (space-separated floats)
Output: 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:
Step 1: Compute target vector target = queen - king + man = [0.8, 0.6, 0.5] - [1.0, 0.5, 0.0] + [0.9, 0.4, 0.0] = [0.7, 0.5, 0.5]
Step 2: Compute cosine similarity with each candidate Candidates (excluding king, queen, man): woman, child
- woman [0.7, 0.5, 0.5]: cos_sim with [0.7, 0.5, 0.5] = 1.0
- child [0.2, 0.3, 0.8]: cos_sim is lower
Answer: woman (highest similarity)
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
Editor
Python 3.13.1
Test Results
0/0Run code to see test results.