将Python字典转换为Word2Vec对象

4

我在Python中获得了一个将单词映射到它们的向量的字典,我正在尝试绘制最相似的n个单词的散点图。因为对于大量的单词进行TSNE处理需要很长时间,所以最好的选择是将该字典转换为w2v对象来处理。


你到目前为止尝试了什么? - patrick
词向量从哪里获得?(通常,任何提供词向量的文件或计算词向量的库都会将它们以便于使用的形式呈现。)你指的“Word2Vec对象”具体是指什么? - gojomo
我使用自己的神经网络计算了单词向量。 我正在尝试像这个链接中的那个一样将它们可视化: https://www.kaggle.com/jeffd23/visualizing-word-vectors-with-t-sne - Ammar Rashed
2个回答

6

我曾遇到相同问题,最终找到了解决办法。

因此,我认为你的字典与我的类似。

d = {}
d['1'] = np.random.randn(300)
d['2'] = np.random.randn(300)

基本上,这些键是用户的ID,每个用户都有一个形状为(300,)的向量。

因此,现在为了将其用作word2vec,我首先需要将其保存为二进制文件,然后使用gensim库加载它。

from numpy import zeros, dtype, float32 as REAL, ascontiguousarray, fromstring
from gensim import utils

m = gensim.models.keyedvectors.Word2VecKeyedVectors(vector_size=300)
m.vocab = d
m.vectors = np.array(list(d.values()))
my_save_word2vec_format(binary=True, fname='train.bin', total_vec=len(d), vocab=m.vocab, vectors=m.vectors)

我的 my_save_word2vec_format 函数在哪里:

def my_save_word2vec_format(fname, vocab, vectors, binary=True, total_vec=2):
"""Store the input-hidden weight matrix in the same format used by the original
C word2vec-tool, for compatibility.

Parameters
----------
fname : str
    The file path used to save the vectors in.
vocab : dict
    The vocabulary of words.
vectors : numpy.array
    The vectors to be stored.
binary : bool, optional
    If True, the data wil be saved in binary word2vec format, else it will be saved in plain text.
total_vec : int, optional
    Explicitly specify total number of vectors
    (in case word vectors are appended with document vectors afterwards).

"""
if not (vocab or vectors):
    raise RuntimeError("no input")
if total_vec is None:
    total_vec = len(vocab)
vector_size = vectors.shape[1]
assert (len(vocab), vector_size) == vectors.shape
with utils.smart_open(fname, 'wb') as fout:
    print(total_vec, vector_size)
    fout.write(utils.to_utf8("%s %s\n" % (total_vec, vector_size)))
    # store in sorted order: most frequent words at the top
    for word, row in vocab.items():
        if binary:
            row = row.astype(REAL)
            fout.write(utils.to_utf8(word) + b" " + row.tostring())
        else:
            fout.write(utils.to_utf8("%s %s\n" % (word, ' '.join(repr(val) for val in row))))

然后使用。
m2 = gensim.models.keyedvectors.Word2VecKeyedVectors.load_word2vec_format('train.bin', binary=True)

加载模型作为word2vec。

1
谢谢。我希望gensim将来能够实现一种转换方法(例如from_dict),而不是在研究中处理这些问题。 - Ammar Rashed
3
对于gensim > 3.4,请使用utils.open而不是utils.smart_open。 - Avi Avidan

0
如果您已经使用自己的代码计算了单词向量,您可能希望将它们写入与Google原始word2vec.c或gensim兼容的格式文件中。您可以查看KeyedVectors.save_word2vec_format()中的gensim代码,以了解其向量是如何编写的 - 这不到20行代码 - 并对您的向量进行类似的操作。请参见:

https://github.com/RaRe-Technologies/gensim/blob/3d2227d58b10d0493006a3d7e63b98d64e991e60/gensim/models/keyedvectors.py#L130

然后,您可以重新加载由您的代码生成的向量,并将它们与Jeff Delaney提到的示例几乎直接使用。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接