许可证: mit
缩略图: https://huggingface.co/front/thumbnails/facebook.png
管道标签: 零样本分类
数据集:
BART大型MNLI模型
这是facebook/bart-large模型在MultiNLI(MNLI)数据集上训练后的检查点。
关于该模型的更多信息:
基于NLI的零样本文本分类
Yin等人提出了一种方法,将预训练的NLI模型用作现成的零样本序列分类器。该方法通过将待分类序列作为NLI前提,并从每个候选标签构建假设来实现。例如,如果我们想评估一个序列是否属于“政治”类别,我们可以构建一个假设这段文本是关于政治的。
。然后,蕴含和矛盾的概率被转换为标签概率。
这种方法在许多情况下出奇地有效,特别是与BART和Roberta等大型预训练模型一起使用时。有关此方法及其他零样本方法的更详细介绍,请参阅此博客文章。下面的代码片段展示了如何使用此模型进行零样本分类,包括使用Hugging Face内置的管道和原生Transformers/PyTorch代码。
使用零样本分类管道
可以通过以下方式加载zero-shot-classification
管道:
from transformers import pipeline
classifier = pipeline("zero-shot-classification",
model="facebook/bart-large-mnli")
然后,您可以使用此管道将序列分类为您指定的任何类别名称。
sequence_to_classify = "总有一天我会去看看这个世界"
candidate_labels = ['旅行', '烹饪', '舞蹈']
classifier(sequence_to_classify, candidate_labels)
如果多个候选标签可能正确,传递multi_label=True
以独立计算每个类别:
candidate_labels = ['旅行', '烹饪', '舞蹈', '探索']
classifier(sequence_to_classify, candidate_labels, multi_label=True)
手动使用PyTorch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
nli_model = AutoModelForSequenceClassification.from_pretrained('facebook/bart-large-mnli')
tokenizer = AutoTokenizer.from_pretrained('facebook/bart-large-mnli')
premise = sequence
hypothesis = f'这个例子是关于{label}的。'
x = tokenizer.encode(premise, hypothesis, return_tensors='pt',
truncation_strategy='only_first')
logits = nli_model(x.to(device))[0]
entail_contradiction_logits = logits[:,[0,2]]
probs = entail_contradiction_logits.softmax(dim=1)
prob_label_is_true = probs[:,1]