如何以vec格式保存fasttext模型?

esi*_*diz 8 python word-embedding fasttext

我使用fasttext.train_unsupervised()python 中的函数训练了我的无监督模型。我想将它保存为 vec 文件,因为我将使用此文件作为pretrainedVectors函数中的参数fasttext.train_supervised()pretrainedVectors只接受 vec 文件,但我在创建这个 vec 文件时遇到了麻烦。有人能帮我吗?

附言。我能够以 bin 格式保存它。如果您建议我一种将 bin 文件转换为 vec 文件的方法,这也会很有帮助。

Ste*_*n87 11

为了获得仅包含所有单词向量的 VEC 文件,我从bin_to_vec 官方示例中获得灵感。

from fasttext import load_model

# original BIN model loading
f = load_model(YOUR-BIN-MODEL-PATH)
    lines=[]

# get all words from model
words = f.get_words()

with open(YOUR-VEC-FILE-PATH,'w') as file_out:
    
    # the first line must contain number of total words and vector dimension
    file_out.write(str(len(words)) + " " + str(f.get_dimension()) + "\n")

    # line by line, you append vectors to VEC file
    for w in words:
        v = f.get_word_vector(w)
        vstr = ""
        for vi in v:
            vstr += " " + str(vi)
        try:
            file_out.write(w + vstr+'\n')
        except:
            pass
Run Code Online (Sandbox Code Playgroud)

获得的 VEC 文件可能很大。要减小文件大小,您可以调整矢量组件的格式。

如果只想保留 4 位十进制数字,则可以替换vstr += " " + str(vi)
vstr += " " + "{:.4f}".format(vi)