我在Python中获得了一个将单词映射到它们的向量的字典,我正在尝试绘制最相似的n个单词的散点图。因为对于大量的单词进行TSNE处理需要很长时间,所以最好的选择是将该字典转换为w2v对象来处理。
我在Python中获得了一个将单词映射到它们的向量的字典,我正在尝试绘制最相似的n个单词的散点图。因为对于大量的单词进行TSNE处理需要很长时间,所以最好的选择是将该字典转换为w2v对象来处理。
我曾遇到相同问题,最终找到了解决办法。
因此,我认为你的字典与我的类似。
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)
KeyedVectors.save_word2vec_format()
中的gensim代码,以了解其向量是如何编写的 - 这不到20行代码 - 并对您的向量进行类似的操作。请参见:
然后,您可以重新加载由您的代码生成的向量,并将它们与Jeff Delaney提到的示例几乎直接使用。