# Create an instance of the zero-shot classification pipeline
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
# Perform zero-shot classification
result = classifier(text, categories)
# Prepare the classification results as a dictionary
output = {}
for category, score in zip(result["labels"], result["scores"]):
output[category] = score
return output
Assistant
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.
Here's a finetuned version of your code with improvements in readability, documentation, error handling, and overall best practices:
python
from transformers import pipeline
def classify_business(text: str, categories: list = None) -> dict:
"""
Classify a business based on a given text using zero-shot classification.
Args:
- text (str): The input text to classify.
- categories (list, optional): Refined classification categories. Defaults to a predefined list.
Returns:
- dict: A dictionary with categories as keys and their corresponding scores as values.
"""
# Define the default refined classification categories
default_categories = [
"web development company",
"mobile app development company",
"enterprise software company",
"hardware company",
"fintech",
"management consultancy",
"marketing consultancy",
"IT consultancy",
"recruitment agency",
"e-commerce",
"retail",
"banking",
"insurance",
]
# Use provided categories if available, otherwise default categories
categories = categories if categories is not None else default_categories
# Input Validation
if not isinstance(text, str) or not text.strip():
raise ValueError("Input text must be a non-empty string.")
if not all(isinstance(category, str) for category in categories):
raise ValueError("All categories must be strings.")
try:
# Create an instance of the zero-shot classification pipeline
# Model: facebook/bart-large-mnli (you may experiment with other models for better results)
classifier = pipeline("zero-shot-classification", model="facebook/bart-large-mnli")
# Perform zero-shot classification
result = classifier(text, categories)
# Prepare the classification results as a dictionary
output = dict(zip(result["labels"], result["scores"]))
return output
except Exception as e:
# Catch and re-raise with more context, or handle as per your application's requirements
raise RuntimeError(f"Failed to classify business: {str(e)}") from e
# Example Usage
if __name__ == "__main__":
example_text = "We specialize in building scalable web applications for enterprises."
classification_result = classify_business(example_text)
print("Classification Result:")
for category, score in classification_result.items():
print(f"{category}: {score:.4f}")
Key Improvements and Additions:
Type Hints: Added for function parameters and return type to enhance readability and enable better auto-completion in IDEs.
Documentation String: Included to provide a clear description of the function, its parameters, and its return value.
Default Categories: Made optional by allowing users to pass their own list of categories.
Input Validation:
Ensures the input text is a non-empty string.
Verifies all categories are strings.
Error Handling:
Wraps the pipeline creation and usage in a try-except block to catch any unexpected errors.
Provides a more informative error message while preserving the original exception.
Simplified Dictionary Creation: Used the dict() constructor with zip() for a more concise creation of the output dictionary.
Example Usage: Added under a if __name__ == "__main__": block to demonstrate how to use the classify_business function without running when the script is imported as a module elsewhere.
Model Selection: The code uses the facebook/bart-large-mnli model, which is a popular choice for zero-shot classification tasks. However, you can experiment with other models like facebook/bart-large-snli or valhalla/bart-large-snli-mnli-scitail to see if they perform better for your specific use case.