Views
No views yet
zero-shot-classification pipeline like so:1from transformers import pipeline
2classifier = pipeline("zero-shot-classification",
3 model="joeddav/xlm-roberta-large-xnli")1# we will classify the Russian translation of, "Who are you voting for in 2020?"
2sequence_to_classify = "За кого вы голосуете в 2020 году?"
3# we can specify candidate labels in Russian or any other language above:
4candidate_labels = ["Europe", "public health", "politics"]
5classifier(sequence_to_classify, candidate_labels)
6# {'labels': ['politics', 'Europe', 'public health'],
7# 'scores': [0.9048484563827515, 0.05722189322113991, 0.03792969882488251],
8# 'sequence': 'За кого вы голосуете в 2020 году?'}This text is {}. If you are working strictly within one language, it
may be worthwhile to translate this to the language you are working with:1sequence_to_classify = "¿A quién vas a votar en 2020?"
2candidate_labels = ["Europa", "salud pública", "política"]
3hypothesis_template = "Este ejemplo es {}."
4classifier(sequence_to_classify, candidate_labels, hypothesis_template=hypothesis_template)
5# {'labels': ['política', 'Europa', 'salud pública'],
6# 'scores': [0.9109585881233215, 0.05954807624220848, 0.029493311420083046],
7# 'sequence': '¿A quién vas a votar en 2020?'}1# pose sequence as a NLI premise and label as a hypothesis
2from transformers import AutoModelForSequenceClassification, AutoTokenizer
3nli_model = AutoModelForSequenceClassification.from_pretrained('joeddav/xlm-roberta-large-xnli')
4tokenizer = AutoTokenizer.from_pretrained('joeddav/xlm-roberta-large-xnli')
5
6premise = sequence
7hypothesis = f'This example is {label}.'
8
9# run through model pre-trained on MNLI
10x = tokenizer.encode(premise, hypothesis, return_tensors='pt',
11 truncation_strategy='only_first')
12logits = nli_model(x.to(device))[0]
13
14# we throw away "neutral" (dim 1) and take the probability of
15# "entailment" (2) as the probability of the label being true
16entail_contradiction_logits = logits[:,[0,2]]
17probs = entail_contradiction_logits.softmax(dim=1)
18prob_label_is_true = probs[:,1]