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 (aa, bb, and cc) along with a pretrained embedding object. It extracts the numerical vectors for the three words, evaluates the expression vec(c)+vec(b)vec(a)\textrm{vec}(c) + \textrm{vec}(b) - \textrm{vec}(a), 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

Contributors are:

Who are from:

Tags

D2L

Dive into Deep Learning @ D2L