プリンキピア

第15章自然言語処理:事前学習

15.4.3. Applying Word Embeddings15.4.3 単語埋め込みを応用する

After training the word2vec model, we can use the cosine similarity of word vectors from the trained model to find words from the dictionary that are most semantically similar to an input word.
英語のヒント
word2vecのモデルを訓練した後、訓練したモデルから得た単語ベクトルのコサイン類似度を使って、入力した単語に意味が最も似ている単語を辞書から見つけられる。
def get_similar_tokens(query_token, k, embed):
    W = embed.weight.data
    x = W[vocab[query_token]]
    # Compute the cosine similarity. Add 1e-9 for numerical stability
    cos = torch.mv(W, x) / torch.sqrt(torch.sum(W * W, dim=1) *
                                      torch.sum(x * x) + 1e-9)
    topk = torch.topk(cos, k=k+1)[1].cpu().numpy().astype('int32')
    for i in topk[1:]:  # Remove the input words
        print(f'cosine sim={float(cos[i]):.3f}: {vocab.to_tokens(i)}')

get_similar_tokens('chip', 3, net[0])
cosine sim=0.702: microprocessor
cosine sim=0.649: mips
cosine sim=0.643: intel