将 Python 字典转换为 Word2Vec 对象

Convert Python dictionary to Word2Vec object

我已经在 python 中获得了一个将单词映射到它们的向量的字典,并且我正在尝试散点图 n 个最相似的单词,因为 TSNE 对大量单词的处理需要永远。最好的办法是把字典转成w2v对象来处理。

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

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

然后您可以重新加载源自您的代码的向量,并几乎直接将它们用于 one from Jeff Delaney you mention 等示例。

我遇到了同样的问题,我终于找到了解决方案

所以,我假设你的字典看起来像我的

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