使用Torchtext进行最近的邻居搜索惹恼

问题描述 投票:0回答:1

我将Torchtext用于某些NLP任务,特别是使用内置嵌入。

我希望能够进行逆向矢量搜索:生成一个有噪声的矢量,找到最接近它的矢量,然后取回与该有噪声矢量最接近的单词。

torchtext docs开始,这是将嵌入内容附加到内置数据集的方法:

from torchtext.vocab import GloVe
from torchtext import data

embedding = GloVe(name='6B', dim=100)

# Set up fields
TEXT = data.Field(lower=True, include_lengths=True, batch_first=True)
LABEL = data.Field(sequential=False, is_target=True)

# make splits for data
train, test = datasets.IMDB.splits(TEXT, LABEL)

# build the vocabulary
TEXT.build_vocab(train, vectors=embedding, max_size=100000)
LABEL.build_vocab(train)

# Get an example vector
embedding.get_vecs_by_tokens("germany")

然后我们可以构建恼人的索引:

from annoy import AnnoyIndex

num_trees = 50

ann_index = AnnoyIndex(embedding_dims, 'angular')

# Iterate through each vector in the embedding and add it to the index
for vector_num, vector in enumerate(TEXT.vocab.vectors):
    ann_index.add_item(vector_num, vector) # Here's the catch: will vector_num correspond to torchtext.vocab.Vocab.itos?

ann_index.build(num_trees)

然后说我想使用嘈杂的向量检索单词:

# Get an existing vector
original_vec = embedding.get_vecs_by_tokens("germany")
# Add some noise to it
noise = generate_noise_vector(ndims=100)
noisy_vector = original_vec + noise
# Get the vector closest to the noisy vector
closest_item_idx = ann_index.get_nns_by_vector(noisy_vector, 1)[0]
# Get word from noisy item
noisy_word = TEXT.vocab.itos[closest_item_idx]

我的问题出现在上面的最后两行:ann_index是使用enumerateembedding对象上创建的,该对象是Torch张量。

[vocab][2]对象具有其自己的itos列表,给定索引将返回一个单词。

我的问题是:我可以确定单词在itos列表中出现的顺序与TEXT.vocab.vectors中的顺序相同吗?如何将一个索引映射到另一个索引?

nlp pytorch nearest-neighbor torchtext annoy
1个回答
0
投票

我可以确定单词在itos列表中出现的顺序与TEXT.vocab.vectors中的顺序相同吗?

Field类将始终实例化一个Vocab对象(source),并且由于您将经过预训练的向量传递给TEXT.build_vocab,因此Vocab构造函数将call该函数load_vectors

if vectors is not None:
    self.load_vectors(vectors, unk_init=unk_init, cache=vectors_cache)

load_vectors中,通过列举vectors中的单词,filleditos

for i, token in enumerate(self.itos):
    start_dim = 0
    for v in vectors:
        end_dim = start_dim + v.dim
        self.vectors[i][start_dim:end_dim] = v[token.strip()]
        start_dim = end_dim
    assert(start_dim == tot_dim)

因此,可以确定itosvectors将具有相同的顺序。

© www.soinside.com 2019 - 2024. All rights reserved.