如何将自定义嵌入矩阵保存为.txt文件格式?

问题描述 投票:0回答:1

我做了一本字典,其中包含以下格式的单词及其对应的单词向量。

{'word1': array([ 4.530e-02, -1.170e-02, -1.201e-01,  2.439e-01,  4.670e-02d], type=float32),
'word2': array([ 4.530e-02, -1.170e-02, -1.201e-01,  2.439e-01,  4.670e-02d], type=float32)}

我想把这本字典以如下格式保存到custom_embeddings.txt文件中。

你的custom_embeddings.txt文件的格式需要是token后面跟着嵌入的每一个维度的值,所有的维度都用一个空格隔开,例如,这里有两个5维嵌入的token。

word1 4.530e-02 -1.170e-02 -1.201e-01  2.439e-01  4.670e-02d
word2 4.530e-02 -1.170e-02 -1.201e-01  2.439e-01  4.670e-02d

如果你能告诉我如何实现这个结果,那将会很有帮助?

先谢谢你

python nlp pytorch
1个回答
1
投票

蟒蛇的 .items() 调用是一种优雅的方式来循环处理字典中的所有单词。这将把输出保存为文本文件的行。

txt_filename = 'output.txt'

with open(txt_filename, 'w') as f:
    for word, vec in my_wordvec_dict.items():
        f.write('{} {}\n'.format(word, ' '.join(['{:e}'.format(item) for item in vec])))
© www.soinside.com 2019 - 2024. All rights reserved.