训练我自己的手套模型时出现编码问题

人气:873 发布:2022-10-16 标签: python encoding nlp word-embedding glove

问题描述

我正在使用自己的语料库训练手套模型,但在以utf-8格式保存/加载它时遇到问题。

以下是我尝试的内容:

from glove import Corpus, Glove

#data
lines = [['woman', 'umbrella', 'silhouetted'], ['person', 'black', 'umbrella']]

#GloVe training
corpus = Corpus() 
corpus.fit(lines, window=4)
glove = Glove(no_components=4, learning_rate=0.1)
glove.fit(corpus.matrix, epochs=10, no_threads=8, verbose=True)
glove.add_dictionary(corpus.dictionary)
glove.save('glove.model.txt')

保存的文件glove.model.txt不可读,我无法使用utf-8编码保存它。

当我尝试阅读时,例如将其转换为word2vec格式:

from gensim.models.keyedvectors import KeyedVectors
from gensim.scripts.glove2word2vec import glove2word2vec
glove2word2vec(glove_input_file="glove.model.txt", 
word2vec_output_file="gensim_glove_vectors.txt")    

model = KeyedVectors.load_word2vec_format("gensim_glove_vectors.txt", binary=False)

我有以下错误:

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

关于如何使用我自己的手套模型有什么想法吗?

推荐答案

我刚刚找到了一种以utf-8格式保存数据的方法,我在这里分享它,以防有人遇到同样的问题

不要使用手套保存方法glove.save('glove.model.txt')尝试自己模拟手套记录:

with open("results_glove.txt", "w") as f:
    for word in glove.dictionary:
        f.write(word)
        f.write(" ")
        for i in range(0, vector_size):
            f.write(str(glove.word_vectors[glove.dictionary[word]][i]))
            f.write(" ")
        f.write("
")

然后您就可以阅读它了。

191