Implementing Zero-Shot Classification
Step 1: Install HuggingFace Transformers
First, ensure that you have the HuggingFace Transformers library installed:
pip install transformers
Step 2: Initialize the Zero-Shot Classification Pipeline
Next, we initialize the zero-shot classification pipeline using the facebook/bart-large-mnli
model:
from transformers import pipeline
# Initialize the zero-shot classification pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
Step 3: Perform Classification
We can now classify a sample text into predefined labels. Here’s an example:
text = "The company's quarterly earnings increased by 20%, exceeding market expectations."
candidate_labels = ["finance", "sports", "politics", "technology"]
result = classifier(text, candidate_labels)
print(result)
Code of Zero-Shot Classification
from transformers import pipeline
# Initialize the zero-shot classification pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
text = "The company's quarterly earnings increased by 20%, exceeding market expectations."
candidate_labels = ["finance", "sports", "politics", "technology"]
result = classifier(text, candidate_labels)
print(result)
Output:
{'sequence': "The company's quarterly earnings increased by 20%, exceeding market expectations.", 'labels': ['finance', 'technology', 'sports', 'politics'], 'scores': [0.6282334327697754, 0.22457945346832275, 0.08779555559158325, 0.05939162150025368]}
Zero-Shot Text Classification using HuggingFace Model
Zero-shot text classification is a groundbreaking technique that allows for categorizing text into predefined labels without any prior training on those specific labels. This method is particularly useful when labeled data is scarce or unavailable. Leveraging the HuggingFace Transformers library, we can easily implement zero-shot classification using pre-trained models. In this article, we’ll explore how to use the HuggingFace pipeline
for zero-shot classification and create an interactive web interface using Gradio.