Text Classification using HuggingFace Model (original) (raw)

Last Updated : 14 Apr, 2026

Text classification using models from Hugging Face enables developers to automatically categorise text into predefined labels such as sentiment, topic, or intent. With pre-trained Hugging Face Transformers models, it becomes easy to build powerful NLP applications without training models from scratch.

Implementing Text Classification

Step 1: Set Up the Environment

pip install transformers

Step 2: Import Required Libraries

Import the pipeline from Transformers, as it provides a high level interface that automatically manages tokenization, model loading, inference and output formatting in a single streamlined workflow.

Python `

from transformers import pipeline

`

Step 3: Initialise Text Classification Model

This sets the task to text classification and loads a DistilBERT model, fine tuned for sentiment analysis. On first use, the model downloads automatically and the pipeline handles tokenization and prediction internally

Python `

classifier = pipeline( "text-classification", model="distilbert-base-uncased-finetuned-sst-2-english" )

`

**Output:

hugging_face_3

Loading pretrained model

Step 4: Provide Input Text

Python `

text1 = "This product is absolutely amazing!" text2 = "The service was terrible and disappointing."

`

Step 5: Run Classification

Python `

result1 = classifier(text1)

print("Sentiment:", result1[0]["label"]) print("Confidence:", result1[0]["score"])

result2 = classifier(text2)

print("Sentiment:", result2[0]["label"]) print("Confidence:", result2[0]["score"])

`

**Output:

As we can see our model is working fine.

You can download the full code from here