Module 5 of 9 · Real Datasets & Pre-trained Models · Beginner

Using HuggingFace Pipelines

Duration: 5 min

The pipeline function is the fastest way to use a pre-trained model. One line of code downloads the model and runs inference. No training required.

Sentiment analysis in 3 lines

from transformers import pipeline

classifier = pipeline('sentiment-analysis')
result = classifier('The California housing market is incredibly competitive.')
print(result)
# [{'label': 'NEGATIVE', 'score': 0.987}]

Try it in Google Colab: Open in Colab

Other ready-to-use pipelines

from transformers import pipeline

# Text summarisation
summariser = pipeline('summarization', model='facebook/bart-large-cnn')
text = """California's housing market has long been one of the most expensive
in the United States. Driven by tech industry growth, limited land supply,
and restrictive zoning laws, median home prices in the San Francisco Bay Area
exceed $1 million. The 1990 census data captured a snapshot of this market
before the dot-com boom dramatically accelerated prices."""
print(summariser(text, max_length=60, min_length=20))

# Zero-shot classification (no training needed)
classifier = pipeline('zero-shot-classification')
result = classifier(
    'This house has 3 bedrooms and a large garden',
    candidate_labels=['real estate', 'food', 'technology', 'sports']
)
print(result['labels'][0])  # real estate

# Named entity recognition
ner = pipeline('ner', grouped_entities=True)
print(ner('Elon Musk founded SpaceX in Hawthorne, California.'))

Specifying a model

from transformers import pipeline

# Use a specific model from the Hub
classifier = pipeline(
    'text-classification',
    model='distilbert-base-uncased-finetuned-sst-2-english'
)
reviews = [
    'Great location, terrible neighbours.',
    'Best investment I ever made.',
    'Overpriced for what you get.'
]
for review, result in zip(reviews, classifier(reviews)):
    print(f'{result["label"]:8} ({result["score"]:.2f}) — {review}')

💡 Tip: The first time you run a pipeline, it downloads the model weights (~250MB for DistilBERT). They're cached locally so subsequent runs are instant.

❓ What does the HuggingFace pipeline() function do?

← Previous Continue interactively → Next →

Related Courses