Creating a Python classification script
It seems the user wants a Python script for classifying text using a pre-trained Transformer model, likely from Hugging Face Transformers. I'll need to make the script concise yet functional, possibly focusing on sentiment classification. I'll show how to load a pre-trained model like "distilbert-base-uncased-finetuned-sst-2-english" and classify input text using either the "pipeline" API or a more manual approach with "AutoTokenizer" and "AutoModelForSequenceClassification." I think I’ll stick with sentiment classification as a clear example.Implementing a text classification script
The user needs a Python script that parses command-line arguments, using the Transformers library. Since they want a functional script, I'll include installation instructions but keep them brief. I'll start the script with the necessary imports and a main function structure.
I plan to provide a simple example that uses the pipeline API for sentiment analysis with "distilbert-base-uncased-finetuned-sst-2-english." The script will accept text either as a command-line argument or via user input, keeping it user-friendly and efficient!Implementing a classification script with flexibility
I think it’s essential to mention that the user can change the model name in the script. I’ll include a short installation command for pip, noting they need to install both "transformers" and "torch" since Torch can be quite heavy.
The script will implement the full classification process without using the pipeline to show the underlying mechanics. However, given the request for brevity, I might ultimately opt for the pipeline, as it hides complexity while still being effective. I need to ensure that users understand label mapping as well!Creating a robust text classification script
To implement the classification script using Transformers, I’ll start with the pipeline for text classification. I can make it so that it uses a custom model name or defaults if none is provided. While the user didn't specify command-line input, it's a good idea to allow text inputs as a list.
I think using argparse for handling user input makes the script more robust. So, I’ll outline this functionality and include a brief description to kick off the script!Finalizing the text classification script
The usage instructions are straightforward; I’ll show how to run the script with example text inputs. I'll define the required arguments to facilitate user input through argparse and utilize the Transformers pipeline.
While the pipeline automatically determines the device, I'll simplify by avoiding requiring the user to specify a GPU, as the default is CPU. I should include a quick installation note for the necessary libraries as well. With this prepared, I’ll provide the full script along with a brief explanation for clarity! Below is a minimal, self-contained Python script that uses a pre-trained Transformer model (from Hugging Face) to classify text (sentiment analysis by default).
1. Install dependencies
pip install transformers torch --upgrade
2. text_classifier.py
#!/usr/bin/env python3
"""
text_classifier.py
Classify text with a pre-trained Transformer model (default: sentiment analysis).
Usage:
python text_classifier.py "I love using Transformer models!"
python text_classifier.py "This is terrible." "This is amazing!"
python text_classifier.py -m distilbert-base-uncased-finetuned-sst-2-english "Custom model text"
"""
import argparse
from transformers import pipeline
def parse_args():
parser = argparse.ArgumentParser(
description="Classify text with a pre-trained Transformer model."
)
parser.add_argument(
"texts",
nargs="+",
help="One or more texts to classify.",
)
parser.add_argument(
"-m", "--model",
default="distilbert-base-uncased-finetuned-sst-2-english",
help=(
"Hugging Face model name or path. "
"Default: distilbert-base-uncased-finetuned-sst-2-english (sentiment analysis)."
),
)
return parser.parse_args()
def main():
args = parse_args()
# Create a text-classification pipeline with the chosen model
classifier = pipeline(
task="text-classification",
model=args.model,
# set return_all_scores=False for a single label; True to see all labels/scores
return_all_scores=False,
)
results = classifier(args.texts)
for text, result in zip(args.texts, results):
label = result["label"]
score = result["score"]
print("Text: ", text)
print(f"Predicted label: {label} (score={score:.4f})")
print("-" * 60)
if __name__ == "__main__":
main()
3. Running examples
python text_classifier.py "I absolutely love this!" "This is the worst."
Output (example):
Text: I absolutely love this!
Predicted label: POSITIVE (score=0.9991)
------------------------------------------------------------
Text: This is the worst.
Predicted label: NEGATIVE (score=0.9983)
------------------------------------------------------------
To use another pre-trained sequence classification model (e.g., a topic classifier), just change -m to the desired model name from the Hugging Face Hub.