Learn Before
Code
get_analogy Function Implementation
The word analogy completion task can be implemented programmatically by defining a function, such as get_analogy, that takes the first three text tokens (, , and ) along with a pretrained embedding object. It extracts the numerical vectors for the three words, evaluates the expression , and uses a nearest neighbors function (knn) to find the most similar vector in the embedding matrix, returning its corresponding word.
def get_analogy(token_a, token_b, token_c, embed): vecs = embed[[token_a, token_b, token_c]] x = vecs[1] - vecs[0] + vecs[2] topk, cos = knn(embed.idx_to_vec, x, 1) return embed.idx_to_token[int(topk[0])] # Remove unknown words
0
1
Updated 2026-05-25
Tags
D2L
Dive into Deep Learning @ D2L