如何从拥抱脸的特征提取管道中获得整个句子的嵌入?
我了解如何获取每个标记的特征(如下),但是如何获取整个句子的整体特征?
feature_extraction = pipeline('feature-extraction', model="distilroberta-base", tokenizer="distilroberta-base")
features = feature_extraction("i am sentence")
最佳答案
为了详细解释我在 stackoverflowuser2010 的回答下的评论,我将使用“准系统”模型,但行为与 pipeline
组件相同。
BERT 和派生模型(包括 DistilRoberta,这是您在管道中使用的模型)通常使用特殊标记(通常表示为 [CLS]
第一个标记),这通常是在整个序列上进行预测/生成嵌入的最简单方法。社区中有关于哪种方法更好的讨论(另请参见 stackoverflowuser2010 here 的更详细答案),但是,如果您只是想要一个“快速”的解决方案,那么采用 [CLS]
token 当然是一种有效的策略。
现在,documentation 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
进行索引,表示序列开始标记(在我们的例子中,嵌入 token )。由于输出长度相同,因此您可以通过执行类似的操作来简单地访问初步的句子嵌入
sentence_embedding = features[0][0]
关于machine-learning - 从拥抱脸特征提取管道中获取句子嵌入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64685243/