How to beginner · 3 min read

How to use sentiment analysis pipeline Hugging Face

Quick answer
Use Hugging Face's pipeline function with the task set to sentiment-analysis to analyze text sentiment easily. Install transformers and run the pipeline on your input text to get sentiment labels and confidence scores.

PREREQUISITES

  • Python 3.8+
  • pip install transformers>=4.0.0
  • pip install torch (or tensorflow, depending on backend)

Setup

Install the transformers library from Hugging Face and a deep learning backend like torch or tensorflow. Set up your Python environment accordingly.

bash
pip install transformers torch

Step by step

Import the pipeline from transformers, create a sentiment analysis pipeline, and pass your text to get sentiment predictions.

python
from transformers import pipeline

# Create sentiment analysis pipeline
sentiment_analyzer = pipeline('sentiment-analysis')

# Analyze sentiment of a sample text
result = sentiment_analyzer('I love using Hugging Face transformers!')
print(result)
output
[{'label': 'POSITIVE', 'score': 0.9998}]

Common variations

  • Specify a different model by passing model='distilbert-base-uncased-finetuned-sst-2-english' to pipeline.
  • Use batch inputs by passing a list of texts.
  • Run asynchronously with asyncio and custom wrappers.
python
from transformers import pipeline

# Use a specific model
sentiment_analyzer = pipeline('sentiment-analysis', model='distilbert-base-uncased-finetuned-sst-2-english')

texts = ["I love this!", "This is terrible."]
results = sentiment_analyzer(texts)
print(results)
output
[{'label': 'POSITIVE', 'score': 0.9998}, {'label': 'NEGATIVE', 'score': 0.9996}]

Troubleshooting

  • If you get an import error, ensure transformers and torch are installed.
  • For slow performance, check if a GPU is available and configured.
  • If you see model download errors, verify your internet connection or use a local cache.

Key Takeaways

  • Use Hugging Face's pipeline with task sentiment-analysis for quick sentiment detection.
  • You can specify different pretrained models to customize accuracy and speed.
  • Batch processing multiple texts improves throughput and efficiency.
Verified 2026-04 · distilbert-base-uncased-finetuned-sst-2-english
Verify ↗