【问题标题】:Encoding problem while training my own Glove model训练我自己的 Glove 模型时出现编码问题
【发布时间】:2019-09-05 16:18:50
【问题描述】:

我正在用我自己的语料库训练一个 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

知道如何使用自己的 GloVe 模型吗?

【问题讨论】:

    标签: python encoding nlp word-embedding glove


    【解决方案1】:

    我刚刚找到了一种以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("\n")
    

    然后你就可以阅读它了。

    【讨论】:

    • 谢谢你的回答,你能告诉我vector_size是什么吗?
    • @PriyankPanchal 几乎晚了一年,但对于遇到此问题并想知道的其他人来说,我认为 vector_size 从字面上看是指每个词向量的大小。您在 Glove(no_components = vector_size, learning_rate = x) 进行初始训练时定义了它
    猜你喜欢
    • 2021-05-05
    • 2018-08-04
    • 1970-01-01
    • 2021-01-31
    • 2020-06-09
    • 2021-04-26
    • 1970-01-01
    • 2022-10-22
    • 1970-01-01
    相关资源
    最近更新 更多