如何将numpy阵列加载到Gensim keyEdVector格式



训练单词嵌入后,我将其保存为NPZ格式。当我试图将其加载为键值向量格式时,它会出现错误。如何将numpy阵列作为gensim.keyedvectors格式加载?我真的需要它,因为我需要使用诸如mostrongimilar()的函数,而不仅仅是向量值。

在tensorflow中,

self.verb_embeddings = tf.Variable(np.load(cfg.pretrained_target)["embeddings"],
                                               name="verb_embeddings",
                                               dtype=tf.float32,
                                               trainable=cfg.tune_emb)

保存

target_emb = sess.run(model.verb_embeddings)
np.savez_compressed("trained_target_emb.npz", embeddings=target_emb)

在main.py

 model = KeyedVectors.load('trained_target_emb.npz')

我有

_pickle.UnpicklingError: A load persistent id instruction was encountered, but no persistent_load function was specified.

也尝试了

 model = KeyedVectors.load_word2vec_format('trained_target_emb.npz')

但是有

 UnicodeDecodeError: 'utf-8' codec can't decode byte 0xde in position 14: invalid continuation byte

gensim KeyedVectors实例无法从单纯的原始数组中加载:没有关于表示哪些单词的信息,哪些索引包含哪个单词。

Gensim中的普通.load()期望使用Gensim自己的.save()方法从Gensim保存的对象。

可以从与原始Google/Mikolov word2vec.c工具使用的文件相同的文件中加载字向量。因此,也许您的TensorFlow代码可以这样保存?

然后,您将使用.load_word2vec_format()

最新更新