|

AI Project: Zero-Shot Classification with Hugging Face

3D isometric illustration of a robot instantly categorizing unknown objects into new buckets, representing Zero-Shot classification.

This is one of the most powerful and “magical” tasks in modern AI.

What if you want to classify a news article into “Politics,” “Business,” or “Sports” without training a new model? That’s Zero-Shot Classification.

Step 1: Install

pip install transformers torch

Step 2: The Code

You just give the pipeline a list of “candidate labels” that you want it to choose from.

from transformers import pipeline

# 1. Load the pipeline
# This will download a model trained on NLI (Natural Language Inference)
classifier = pipeline("zero-shot-classification")

# 2. Define your text and your custom labels
text = "The government announced a new tax policy today that will affect small businesses."
my_labels = ["Sports", "Technology", "Politics", "Business"]

# 3. Classify!
result = classifier(text, candidate_labels=my_labels)
print(result)

Step 3: The Result

The model will return a list of your labels, sorted by how relevant they are to the text.

{
  'sequence': 'The government announced a new tax policy today that will affect small businesses.',
  'labels': ['Politics', 'Business', 'Technology', 'Sports'],
  'scores': [0.95, 0.88, 0.02, 0.01]
}

The model correctly identified the text is about “Politics” and “Business,” even though it was never specifically trained on those words! You can change the my_labels list to anything (e.g., ["Happy", "Angry", "Urgent"]) and it will work.

Key Takeaways

  • Sentiment Analysis and Multi-Label Classification are popular tasks in AI, trained on specific sentiments or categories.
  • Zero-Shot Classification allows you to classify text into categories like ‘Politics’, ‘Business’, or ‘Sports’ without training a new model.
  • To use Zero-Shot Classification, install the necessary tools and provide a list of candidate labels for the model to choose from.
  • The model returns labels sorted by relevance, demonstrating its ability to generalise to unseen categories.

Similar Posts

Leave a Reply