machine-learning - 从拥抱脸特征提取管道中获取句子嵌入

标签 machine-learning nlp huggingface-transformers spacy-transformers

如何从拥抱脸的特征提取管道中获得整个句子的嵌入?

我了解如何获取每个标记的特征(如下),但是如何获取整个句子的整体特征?

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/

相关文章:

python - 使用 Sklearn.naive_bayes.Bernoulli 的朴素贝叶斯分类器;如何利用模型进行预测?

algorithm - 文本分类中的搭配

python - 不能从变压器导入管道

java - 在 Java 代码中使用 libsvm 在移动设备中执行预测

python - 如何快速获取使用 PyCharm 和 Pytorch 的文档

machine-learning - 当未分配时如何找到 "num_words"或 Keras 分词器的词汇量大小?

python - 使用 SpaCy 和 Python 创建基于规则的匹配以检测地址

deep-learning - 训练使用 AutoConfig 定义的拥抱面 AutoModel

nlp - 来自 HuggingFace 的 BertWordPieceTokenizer 与 BertTokenizer

python - 如何对 pandas.Series 列进行二进制分解