Zero-Shot Text Classification using HuggingFace Model
Last Updated :
23 Jul, 2025
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.
Understanding Zero-Shot Classification
Zero-shot classification relies on pre-trained language models that understand language context deeply. These models can be prompted with new tasks, such as classification, by providing text and candidate labels. The model evaluates the text against the labels and assigns probabilities to each label based on its understanding.
HuggingFace Transformers
The HuggingFace Transformers library provides an easy-to-use interface for various natural language processing tasks, including zero-shot classification. One of the most popular models for this task is facebook/bart-large-mnli
, which is based on the BART model and fine-tuned on the Multi-Genre Natural Language Inference (MNLI) dataset.
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
Python
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]}
Evaluating Zero-Shot Classification
To evaluate the performance, you can compare the predicted labels with true labels using metrics like precision, recall, and F1-score. Here’s an example using a small dataset:
Python
from sklearn.metrics import classification_report
texts = ["The stock market is up today.", "The new movie is a great thriller.", "The football match was exciting."]
true_labels = ["finance", "entertainment", "sports"]
predicted_labels = []
for text in texts:
result = classifier(text, candidate_labels=["finance", "entertainment", "sports"])
predicted_labels.append(result['labels'][0])
print(classification_report(true_labels, predicted_labels))
Output:
precision recall f1-score support
entertainment 0.50 1.00 0.67 1
finance 1.00 1.00 1.00 1
sports 0.00 0.00 0.00 1
accuracy 0.67 3
macro avg 0.50 0.67 0.56 3
weighted avg 0.50 0.67 0.56 3
Creating an Interactive Interface with Gradio
Gradio provides an easy way to create web interfaces for machine learning models. We can use Gradio to build an interactive interface for zero-shot classification.
Step 1: Install Gradio
First, install Gradio:
pip install gradio
Step 2: Define the Classification Function
Create a function that takes text and labels as inputs and returns the classification results:
import gradio as gr
from transformers import pipeline
# Initialize the zero-shot classification pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
# Define the classification function
def classify_text(text, labels):
labels = labels.split(",")
result = classifier(text, candidate_labels=labels)
return {label: score for label, score in zip(result["labels"], result["scores"])}
Step 3: Create the Gradio Interface
Set up the Gradio interface with text inputs for the sentence and labels, and a label output:
# Create the Gradio interface
interface = gr.Interface(
fn=classify_text,
inputs=[
gr.inputs.Textbox(lines=2, placeholder="Enter text here..."),
gr.inputs.Textbox(lines=1, placeholder="Enter comma-separated labels here...")
],
outputs=gr.outputs.Label(num_top_classes=3),
title="Zero-Shot Text Classification",
description="Classify text into labels without training data.",
)
# Launch the interface
interface.launch()
Complete Code for Creating an Interactive Interface with Gradio
Python
import gradio as gr
from transformers import pipeline
# Initialize the zero-shot classification pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
# Define the classification function
def classify_text(text, labels):
labels = labels.split(",")
result = classifier(text, candidate_labels=labels)
return {label: score for label, score in zip(result["labels"], result["scores"])}
# Create the Gradio interface
interface = gr.Interface(
fn=classify_text,
inputs=[
gr.Textbox(lines=2, placeholder="Enter text here..."),
gr.Textbox(lines=1, placeholder="Enter comma-separated labels here...")
],
outputs=gr.Label(num_top_classes=3),
title="Zero-Shot Text Classification",
description="Classify text into labels without training data.",
)
# Launch the interface
interface.launch()
Output:
Gradio Interface for Interactive Zero Shot Classification Conclusion
Zero-shot text classification using the HuggingFace Transformers library offers a flexible and powerful way to categorize text without the need for labeled training data. By leveraging models like facebook/bart-large-mnli, we can achieve high accuracy in various classification tasks. Additionally, integrating this functionality with Gradio allows for easy deployment of interactive web interfaces, making it accessible to a wider audience. This approach opens up numerous possibilities for real-world applications where labeled data is not readily available.
Similar Reads
Natural Language Processing (NLP) Tutorial Natural Language Processing (NLP) is a branch of Artificial Intelligence (AI) that helps machines to understand and process human languages either in text or audio form. It is used across a variety of applications from speech recognition to language translation and text summarization.Natural Languag
5 min read
Introduction to NLP
Natural Language Processing (NLP) - OverviewNatural Language Processing (NLP) is a field that combines computer science, artificial intelligence and language studies. It helps computers understand, process and create human language in a way that makes sense and is useful. With the growing amount of text data from social media, websites and ot
9 min read
NLP vs NLU vs NLGNatural Language Processing(NLP) is a subset of Artificial intelligence which involves communication between a human and a machine using a natural language than a coded or byte language. It provides the ability to give instructions to machines in a more easy and efficient manner. Natural Language Un
3 min read
Applications of NLPAmong the thousands and thousands of species in this world, solely homo sapiens are successful in spoken language. From cave drawings to internet communication, we have come a lengthy way! As we are progressing in the direction of Artificial Intelligence, it only appears logical to impart the bots t
6 min read
Why is NLP important?Natural language processing (NLP) is vital in efficiently and comprehensively analyzing text and speech data. It can navigate the variations in dialects, slang, and grammatical inconsistencies typical of everyday conversations. Table of Content Understanding Natural Language ProcessingReasons Why NL
6 min read
Phases of Natural Language Processing (NLP)Natural Language Processing (NLP) helps computers to understand, analyze and interact with human language. It involves a series of phases that work together to process language and each phase helps in understanding structure and meaning of human language. In this article, we will understand these ph
7 min read
The Future of Natural Language Processing: Trends and InnovationsThere are no reasons why today's world is thrilled to see innovations like ChatGPT and GPT/ NLP(Natural Language Processing) deployments, which is known as the defining moment of the history of technology where we can finally create a machine that can mimic human reaction. If someone would have told
7 min read
Libraries for NLP
Text Normalization in NLP
Normalizing Textual Data with PythonIn this article, we will learn How to Normalizing Textual Data with Python. Let's discuss some concepts : Textual data ask systematically collected material consisting of written, printed, or electronically published words, typically either purposefully written or transcribed from speech.Text normal
7 min read
Regex Tutorial - How to write Regular Expressions?A regular expression (regex) is a sequence of characters that define a search pattern. Here's how to write regular expressions: Start by understanding the special characters used in regex, such as ".", "*", "+", "?", and more.Choose a programming language or tool that supports regex, such as Python,
6 min read
Tokenization in NLPTokenization is a fundamental step in Natural Language Processing (NLP). It involves dividing a Textual input into smaller units known as tokens. These tokens can be in the form of words, characters, sub-words, or sentences. It helps in improving interpretability of text by different models. Let's u
8 min read
Python | Lemmatization with NLTKLemmatization is an important text pre-processing technique in Natural Language Processing (NLP) that reduces words to their base form known as a "lemma." For example, the lemma of "running" is "run" and "better" becomes "good." Unlike stemming which simply removes prefixes or suffixes, it considers
6 min read
Introduction to StemmingStemming is an important text-processing technique that reduces words to their base or root form by removing prefixes and suffixes. This process standardizes words which helps to improve the efficiency and effectiveness of various natural language processing (NLP) tasks.In NLP, stemming simplifies w
6 min read
Removing stop words with NLTK in PythonNatural language processing tasks often involve filtering out commonly occurring words that provide no or very little semantic value to text analysis. These words are known as stopwords include articles, prepositions and pronouns like "the", "and", "is" and "in." While they seem insignificant, prope
5 min read
POS(Parts-Of-Speech) Tagging in NLPParts of Speech (PoS) tagging is a core task in NLP, It gives each word a grammatical category such as nouns, verbs, adjectives and adverbs. Through better understanding of phrase structure and semantics, this technique makes it possible for machines to study human language more accurately. PoS tagg
7 min read
Text Representation and Embedding Techniques
NLP Deep Learning Techniques
NLP Projects and Practice
Sentiment Analysis with an Recurrent Neural Networks (RNN)Recurrent Neural Networks (RNNs) are used in sequence tasks such as sentiment analysis due to their ability to capture context from sequential data. In this article we will be apply RNNs to analyze the sentiment of customer reviews from Swiggy food delivery platform. The goal is to classify reviews
5 min read
Text Generation using Recurrent Long Short Term Memory NetworkLSTMs are a type of neural network that are well-suited for tasks involving sequential data such as text generation. They are particularly useful because they can remember long-term dependencies in the data which is crucial when dealing with text that often has context that spans over multiple words
4 min read
Machine Translation with Transformer in PythonMachine translation means converting text from one language into another. Tools like Google Translate use this technology. Many translation systems use transformer models which are good at understanding the meaning of sentences. In this article, we will see how to fine-tune a Transformer model from
6 min read
Building a Rule-Based Chatbot with Natural Language ProcessingA rule-based chatbot follows a set of predefined rules or patterns to match user input and generate an appropriate response. The chatbot canât understand or process input beyond these rules and relies on exact matches making it ideal for handling repetitive tasks or specific queries.Pattern Matching
4 min read
Text Classification using scikit-learn in NLPThe purpose of text classification, a key task in natural language processing (NLP), is to categorise text content into preset groups. Topic categorization, sentiment analysis, and spam detection can all benefit from this. In this article, we will use scikit-learn, a Python machine learning toolkit,
5 min read
Text Summarization using HuggingFace ModelText summarization involves reducing a document to its most essential content. The aim is to generate summaries that are concise and retain the original meaning. Summarization plays an important role in many real-world applications such as digesting long articles, summarizing legal contracts, highli
4 min read
Advanced Natural Language Processing Interview QuestionNatural Language Processing (NLP) is a rapidly evolving field at the intersection of computer science and linguistics. As companies increasingly leverage NLP technologies, the demand for skilled professionals in this area has surged. Whether preparing for a job interview or looking to brush up on yo
9 min read