如何在gensim中使用word2vec2tensor?

How to use word2vec2tensor in gensim?

我正在按照以下 gensim 教程将我的 word2vec 模型转换为张量。运行 Link 到教程:https://radimrehurek.com/gensim/scripts/word2vec2tensor.html

更具体地说,我运行以下命令

python -m gensim.scripts.word2vec2tensor -i C:\Users\Emi\Desktop\word2vec\model_name -o C:\Users\Emi\Desktop\word2vec

但是,上面的命令出现以下错误。

UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0: invalid start byte

当我使用model.wv.save_word2vec_format(model_name)保存我的模型时(如下面link:https://github.com/RaRe-Technologies/gensim/issues/1847中提到的)然后使用上面的命令我得到以下错误。

ValueError: invalid vector on line 1 (is this really the text format?)

只是想知道我是否在逗号的语法上有任何错误。请让我知道如何解决这个问题。

如果需要,我很乐意提供更多详细信息。

我能够使用以下代码解决问题:

model = gensim.models.keyedvectors.KeyedVectors.load(file_name)

max_size = len(model.wv.vocab)-1
w2v = np.zeros((max_size,model.layer1_size))

if not os.path.exists('projections'):
    os.makedirs('projections')

with open("projections/metadata.tsv", 'w+') as file_metadata:

    for i, word in enumerate(model.wv.index2word[:max_size]):

        #store the embeddings of the word
        w2v[i] = model.wv[word]

        #write the word to a file 
        file_metadata.write(word + '\n')

sess = tf.InteractiveSession()
with tf.device("/cpu:0"):
    embedding = tf.Variable(w2v, trainable=False, name='embedding')
tf.global_variables_initializer().run()
saver = tf.train.Saver()
writer = tf.summary.FileWriter('projections', sess.graph)
config = projector.ProjectorConfig()
embed= config.embeddings.add()
embed.tensor_name = 'embedding'
embed.metadata_path = 'metadata.tsv'
projector.visualize_embeddings(writer, config)
saver.save(sess, 'projections/model.ckpt', global_step=max_size)

您的型号与 gensim.scripts.word2vec2tensor() 不兼容。您可能需要使用 model.wv.save_word2vec_format().

保存您的模型

我猜你使用了 model.save(),它在后台调用 pickle(参见 utils documentation). Alternatively, model.wv.save_word2vec_format() will save word vectors "in a format compatible with the original word2vec implementation" as noted in the docs。此格式与 gensim.scripts.word2vec2tensor()

一致