embedding - 如何将句子-Bert 输出向量保存到文件中?
问题描述
我正在使用 Bert 来获取多词之间的相似性。这是我用于嵌入的代码:
from sentence_transformers import SentenceTransformer
model = SentenceTransformer('bert-large-uncased-whole-word-masking')
words = [
"Artificial intelligence",
"Data mining",
"Political history",
"Literature book"]
我还有一个包含 540000 个单词的数据集。
Vocabs = [
"Winter flooding",
"Cholesterol diet", ....]
问题是当我想将 Vocabs 嵌入到向量中时,它永远需要时间。
words_embeddings = model.encode(words)
Vocabs_embeddings = model.encode(Vocabs)
有没有办法让它更快?或者我想在 for 循环中嵌入词汇并将输出向量保存在一个文件中,这样我就不必每次需要时都嵌入 540000 个词汇。有没有办法将嵌入保存到文件中并再次使用它?我将非常感谢您花时间帮助我。
解决方案
您可以像这样腌制您的语料库和嵌入,也可以腌制字典,或者以您喜欢的任何其他格式将它们写入文件。
import pickle
with open("my-embeddings.pkl", "wb") as fOut:
pickle.dump({'sentences': words, 'embeddings': word_embeddings},fOut)
或更一般地,如下所示,因此您在嵌入不存在时进行编码,但之后您需要从文件中加载它们,而不是重新编码您的语料库:
if not os.path.exists(embedding_cache_path):
# read your corpus etc
corpus_sentences = ...
print("Encoding the corpus. This might take a while")
corpus_embeddings = model.encode(corpus_sentences, show_progress_bar=True, convert_to_numpy=True)
corpus_embeddings = corpus_embeddings / np.linalg.norm(corpus_embeddings, axis=1, keepdims=True)
print("Storing file on disc")
with open(embedding_cache_path, "wb") as fOut:
pickle.dump({'sentences': corpus_sentences, 'embeddings': corpus_embeddings}, fOut)
else:
print("Loading pre-computed embeddings from disc")
with open(embedding_cache_path, "rb") as fIn:
cache_data = pickle.load(fIn)
corpus_sentences = cache_data['sentences']
corpus_embeddings = cache_data['embeddings']
推荐阅读
- javascript - 脚本适用于 Edge 但不适用于 Chrome
- python - 从熊猫数据框中的单个单元格中检索值时出错
- javascript - 当数组作为参数传递时,函数调用不显示未定义的值
- react-native - 如何在反应导航 5.x 中创建透明背景?
- c# - 为什么没有在安装项目中检测到所有依赖项?
- list - 迭代时无法修改集合。- Apex 类
- python-3.x - Python3 中的 PostgreSQL - 带有外键的创建表语句中的语法错误
- twitter-bootstrap - xs 的 bootstrap 3 响应能力
- git - 一个目录中的 2 个 git 存储库(共享 Dockerfile)
- javascript - 使用 knex.transactionProvider() 时出现 KnexTimeoutError