Bird
Raised Fist0
NlpHow-ToBeginner · 3 min read

How to Use Hugging Face Pipeline in NLP: Simple Guide

Use the pipeline function from the transformers library to quickly load pre-trained NLP models for tasks like sentiment analysis or text generation. Simply specify the task name and input text, and the pipeline handles tokenization, model inference, and output formatting automatically.
📐

Syntax

The basic syntax to use Hugging Face pipeline is:

  • pipeline(task, model=None, tokenizer=None): Creates a pipeline for the specified NLP task.
  • task: A string like "sentiment-analysis", "text-generation", or "ner".
  • model and tokenizer: Optional, specify custom model or tokenizer names.
  • Call the pipeline object with input text to get predictions.
python
from transformers import pipeline

# Create a sentiment analysis pipeline
nlp = pipeline('sentiment-analysis')

# Use the pipeline on text
result = nlp('I love using Hugging Face!')
💻

Example

This example shows how to use the Hugging Face pipeline for sentiment analysis. It loads a pre-trained model and predicts the sentiment of a given sentence.

python
from transformers import pipeline

# Load sentiment-analysis pipeline
sentiment_pipeline = pipeline('sentiment-analysis')

# Input text
text = 'Hugging Face makes NLP easy and fun!'

# Get prediction
result = sentiment_pipeline(text)

print(result)
Output
[{'label': 'POSITIVE', 'score': 0.9998}]
⚠️

Common Pitfalls

Common mistakes when using Hugging Face pipeline include:

  • Not installing the transformers library or missing dependencies.
  • Using incorrect task names (e.g., "sentiment" instead of "sentiment-analysis").
  • Passing input types other than strings or lists of strings.
  • Ignoring internet connection when loading models for the first time.

Always check the official task names and ensure your input is a string or list of strings.

python
from transformers import pipeline

# Wrong task name (will raise error)
# nlp = pipeline('sentiment')  # Incorrect

# Correct task name
nlp = pipeline('sentiment-analysis')
📊

Quick Reference

ParameterDescriptionExample
taskNLP task to perform"sentiment-analysis", "ner", "text-generation"
modelCustom model name or path"distilbert-base-uncased-finetuned-sst-2-english"
tokenizerCustom tokenizer name or path"distilbert-base-uncased"
inputText or list of texts to analyze"I love NLP!" or ["Hello", "World"]
✅

Key Takeaways

Use the pipeline function with the correct task name to load pre-trained NLP models easily.
Pass strings or lists of strings as input to get predictions from the pipeline.
Common tasks include sentiment-analysis, named-entity-recognition (ner), and text-generation.
Ensure transformers library is installed and internet is available for first-time model downloads.
Check official Hugging Face docs for valid task names and supported models.