Get startedGet started for free

Dynamic category assignment

Dynamic category assignment enables a model to classify text into predefined categories, even without prior training for those categories.

Using Hugging Face’s pipeline() for the zero-shot-classification task, provide the text and predefined categories to identify the best match.

Build a classifier to predict the label for the input text, which is a news headline already loaded for you.

The pipelines from the transformers library is preloaded for your convenience.

Note: We are using a customized version of the pipeline to help you learn how to use these functions without needing to download the model.

This exercise is part of the course

Working with Hugging Face

View Course

Exercise instructions

  • Build the pipeline and save as classifier.
  • Create a list of the labels - "politics", "science", "sports" - and save as categories.
  • Predict the label of text using the classifier and predefined categories.

Hands-on interactive exercise

Have a go at this exercise by completing this sample code.

text = "AI-powered robots assist in complex brain surgeries with precision."

# Create the pipeline
____ = pipeline(____="zero-shot-classification", ____="facebook/bart-large-mnli")

# Create the categories list
categories = ["politics", "____", "____"]

# Predict the output
output = ____(____, ____)

# Print the top label and its score
print(f"Top Label: {output['labels'][0]} with score: {output['scores'][0]}")
Edit and Run Code