如何从拥抱脸的特征提取流水线中获得整个句子的嵌入?
我理解如何获得每个标记的特性(下面),但是如何获得整个句子的整体功能呢?
feature_extraction = pipeline('feature-extraction', model="distilroberta-base", tokenizer="distilroberta-base")
features = feature_extraction("i am sentence")发布于 2020-11-06 11:57:17
为了更多地解释我在stackoverflowuser2010 user2010的答案下发表的评论,我将使用"barebone“模型,但是pipeline组件的行为是相同的。
BERT和派生模型(包括DistilRoberta,它是您在管道中使用的模型)通常是对整个序列进行预测/生成嵌入的最简单的方法,它将指示具有特殊标记(主要表示为第一个令牌的[CLS] )的句子的开始和结尾。但是,社区中有关于哪种方法更优越的讨论(请参见stackoverflowuser2010 这里提供的更详细的答案),但是,如果您只是想要一个“快速”解决方案,那么使用[CLS]令牌无疑是一种有效的策略。
现在,虽然文档的FeatureExtractionPipeline不是很清楚,但在您的示例中,我们可以通过直接的模型调用轻松地比较输出,特别是它们的长度:
from transformers import pipeline, AutoTokenizer
# direct encoding of the sample sentence
tokenizer = AutoTokenizer.from_pretrained('distilroberta-base')
encoded_seq = tokenizer.encode("i am sentence")
# your approach
feature_extraction = pipeline('feature-extraction', model="distilroberta-base", tokenizer="distilroberta-base")
features = feature_extraction("i am sentence")
# Compare lengths of outputs
print(len(encoded_seq)) # 5
# Note that the output has a weird list output that requires to index with 0.
print(len(features[0])) # 5在检查encoded_seq的内容时,您会注意到第一个令牌是用0索引的,它表示序列开始令牌(在本例中是嵌入令牌)。由于输出长度相同,所以只需执行以下操作即可访问嵌入的初步句子
sentence_embedding = features[0][0]
发布于 2022-01-22 11:59:25
如果你想要有意义的嵌入整个句子,请使用SentenceTransformers。池在它中得到了很好的实现,它还提供了各种用于微调模型的APIs,以便在句子/文本块级别产生特性/嵌入。
pip install sentence-transformers一旦安装了语句转换器,下面的代码就可以用于生成句子嵌入。
from sentence_transformers import SentenceTransformer
model_st = SentenceTransformer('distilroberta-base')
embeddings = model_st.encode("I am a sentence')
print(embeddings)访问官方的站点获得更多关于句子转换的信息。
发布于 2020-11-06 04:03:08
如果您有每个令牌的嵌入,则可以通过对其进行池(总结)来创建一个完整的句子嵌入。请注意,如果您有D维令牌嵌入,您应该通过以下方法之一获得一个D维句子嵌入:
https://stackoverflow.com/questions/64685243
复制相似问题