Zero-shot classification is a technique that allows us to classify text without having pre-labeled training data. This is particularly useful in real-world scenarios where labeling data can be time-consuming and expensive.
The Hugging Face Transformer Library provides an easy-to-use pipeline for zero-shot classification. Let's explore this with a few examples:
Example 1: Basic Classification
from transformers import pipeline
classifier = pipeline("zero-shot-classification")
result = classifier(
"Do you think Trump will win this election?",
candidate_labels=["education", "politics", "business"],
)
print(result)
# Output:
# {'sequence': 'Do you think Trump will win this election?',
# 'labels': ['politics', 'business', 'education'],
# 'scores': [0.9876543879508972, 0.008765432238578796, 0.003580179810523987]}
Example 2: Multi-label Classification
from transformers import pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli", revision="c626438")
result = classifier(
"The new AI policy will impact both the tech industry and academic research.",
candidate_labels=["technology", "politics", "education", "economics"],
multi_label=True
)
print(result)
# Output:
# {'sequence': 'The new AI policy will impact both the tech industry and academic research.',
# 'labels': ['technology', 'politics', 'education', 'economics'],
# 'scores': [0.9253, 0.8764, 0.7865, 0.6543]}
Example 3: Classifying with Custom Labels
result = classifier(
"The spacecraft successfully landed on Mars, marking a new era in space exploration.",
candidate_labels=["astronomy", "technology", "history", "geology"],
multi_label=True
)
print(result)
# Output:
# {'sequence': 'The spacecraft successfully landed on Mars, marking a new era in space exploration.',
# 'labels': ['astronomy', 'technology', 'history', 'geology'],
# 'scores': [0.9253, 0.8764, 0.7865, 0.6543]}
These examples demonstrate the flexibility and power of zero-shot classification using the Hugging Face Transformer Library. It allows us to classify text into any set of categories we define, without the need for specific training data for those categories.
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!
Provide Feedback For This Article
We take your feedback seriously and use it to improve our content. Thank you for helping us serve you better!
Thanks for your feedback! If you have time, please provide details by selecting options below.
😊 Thanks for your time, your feedback has been registered!
Comments & Discussion
Facing issues? Have questions? Post them here! We're happy to help!