Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Data Science
  • Data Science Projects
  • Data Analysis
  • Data Visualization
  • Machine Learning
  • ML Projects
  • Deep Learning
  • NLP
  • Computer Vision
  • Artificial Intelligence
Open In App
Next Article:
Text Classification using HuggingFace Model
Next article icon

Text Classification using HuggingFace Model

Last Updated : 20 Jun, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Text classification is a pivotal task in natural language processing (NLP) that categorizes text into predefined categories. It is widely used in sentiment analysis, spam detection, topic labeling, and more. The development of transformer-based models, such as those provided by Hugging Face, has significantly enhanced the accuracy and efficiency of these tasks.

This article explores how to implement text classification using a Hugging Face transformer model, specifically leveraging a user-friendly Gradio interface to interact with the model.

Table of Content

  • Overview of Hugging Face Transformers
  • Choosing a Model
  • Implementing Text Classification Model with Gradio
  • Conclusion

Overview of Hugging Face Transformers

Hugging Face is at the forefront of modern NLP, providing a vast array of pre-trained models that are easily accessible through their transformers library. These models are trained on diverse datasets and are highly capable of understanding and generating human-like text. For text classification, models like BERT, DistilBERT, and RoBERTa are commonly used due to their robustness and versatility in handling various NLP tasks.

Choosing a Model

For our demonstration, we selected distilbert-base-uncased-finetuned-sst-2-english, a distilled version of the BERT model fine-tuned on the Stanford Sentiment Treebank (SST-2) dataset for sentiment analysis. This model offers a good balance between performance and computational efficiency, making it suitable for real-time applications.

Implementing Text Classification Model with Gradio

The goal is to create a web-based interface using Gradio that allows users to input text and receive sentiment classification results. Gradio is an open-source library that makes it easy to create customizable UI components for machine learning models.

Step 1: Load the Model

We use the pipeline API from Hugging Face's transformers library, which provides a high-level abstraction to apply pre-trained models directly to data.

from transformers import pipeline

def load_model():
return pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")

Step 2: Define Text Classification Function

This function receives text from the user and uses the loaded model to perform sentiment analysis.

def classify_text(model, text):
return model(text)

Step 3: Set Up Gradio Interface

We create a simple interface with a textbox for input and configure it to display the model's output in JSON format.

import gradio as gr

def main():
model = load_model()
interface = gr.Interface(
fn=lambda text: classify_text(model, text),
inputs=gr.Textbox(lines=2, placeholder="Enter Text Here..."),
outputs="json",
title="Text Classification with HuggingFace",
description="This interface uses a HuggingFace model to classify text sentiments. Enter a sentence to see its classification."
)
interface.launch()

Complete Code and Output for Text Classification using Hugging Face Model

Python
import gradio as gr from transformers import pipeline  def load_model():     # Load a pre-trained HuggingFace pipeline for sentiment analysis     model_pipeline = pipeline("sentiment-analysis", model="distilbert-base-uncased-finetuned-sst-2-english")     return model_pipeline  def classify_text(model, text):     # Use the loaded model to classify text     result = model(text)     return result  def main():     # Load the model     model = load_model()      # Define the Gradio interface     interface = gr.Interface(         fn=lambda text: classify_text(model, text),         inputs=gr.Textbox(lines=2, placeholder="Enter Text Here..."),         outputs="json",         title="Text Classification with HuggingFace",         description="This interface uses a HuggingFace model to classify text sentiments. Enter a sentence to see its classification."     )      # Launch the Gradio app     interface.launch()  if __name__ == "__main__":     main() 

Output:

Capture


Conclusion

Integrating Hugging Face transformers with Gradio offers a powerful and efficient way to deploy NLP models with interactive web interfaces. This setup not only aids in rapid prototyping but also enhances accessibility, allowing end-users with no technical background to leverage state-of-the-art NLP technologies. By following this guide, developers can extend the application to various other NLP tasks, customizing the interface and model choice as per their specific needs.


Next Article
Text Classification using HuggingFace Model

S

sai_teja_anantha
Improve
Article Tags :
  • Blogathon
  • NLP
  • AI-ML-DS
  • AI-ML-DS With Python
  • Data Science Blogathon 2024

Similar Reads

    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
    4 min read
    Text Feature Extraction using HuggingFace Model
    Text feature extraction converts text data into a numerical format that machine learning algorithms can understand. This preprocessing step is important for efficient, accurate, and interpretable models in natural language processing (NLP). We will discuss more about text feature extraction in this
    4 min read
    Text2Text Generations using HuggingFace Model
    Text2Text generation is a versatile and powerful approach in Natural Language Processing (NLP) that involves transforming one piece of text into another. This can include tasks such as translation, summarization, question answering, and more. HuggingFace, a leading provider of NLP tools, offers a ro
    5 min read
    Text-to-Image using Stable Diffusion HuggingFace Model
    Models available through HuggingFace utilize advanced machine-learning techniques for a variety of applications, from natural language processing to computer vision. Recently, they have expanded to include the ability to generate images directly from text descriptions, prominently featuring models l
    3 min read
    Text Summarizations using HuggingFace Model
    Text summarization is a crucial task in natural language processing (NLP) that involves generating concise and coherent summaries from longer text documents. This task has numerous applications, such as creating summaries for news articles, research papers, and long-form content, making it easier fo
    5 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences