gpt4 book ai didi

python - 在Python中读取大型预训练的fastext词嵌入文件

转载 作者:行者123 更新时间:2023-11-30 22:00:38 26 4
gpt4 key购买 nike

我正在做情感分析,我想使用预先训练的快速文本嵌入,但是文件非常大(6.7 GB),并且程序需要很长时间才能编译。

fasttext_dir = '/Fasttext'
embeddings_index = {}
f = open(os.path.join(fasttext_dir, 'wiki.en.vec'), 'r', encoding='utf-8')
for line in tqdm(f):
values = line.rstrip().rsplit(' ')
word = values[0]
coefs = np.asarray(values[1:], dtype='float32')
embeddings_index[word] = coefs
f.close()

print('found %s word vectors' % len(embeddings_index))

embedding_dim = 300

embedding_matrix = np.zeros((max_words, embedding_dim))
for word, i in word_index.items():
if i < max_words:
embedding_vector = embeddings_index.get(word)
if embedding_vector is not None:
embedding_matrix[i] = embedding_vector

有什么办法可以加快这个过程吗?

最佳答案

您可以使用 gensim 加载预训练的嵌入。至少对我来说这要快得多。首先,您需要 pip install gensim,然后您可以使用以下代码行加载模型:

from gensim.models import FastText

model = FastText.load_fasttext_format('cc.en.300.bin')

(我不确定您是否需要 .bin 文件,也许 .vec 文件也可以。)

要使用此模型嵌入单词,只需使用 model[word]

关于python - 在Python中读取大型预训练的fastext词嵌入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54268879/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com