can you write a code using a BERT model pre-trained for sentiment analysis?
- User
can you write a code using a BERT model pre-trained for sentiment analysis?
- Assistant
can you write a code using a BERT model pre-trained for sentiment analysis?
Certainly! Below is a Python example demonstrating how to use a pre-trained BERT model for sentiment analysis using Hugging Face's Transformers library. This example includes both the high-level pipeline API and a more detailed approach using the tokenizer and model directly.
Python 3.6+: Ensure you have Python installed. You can download it from here.
Install Required Libraries:
You'll need to install the transformers and torch libraries. You can install them using pip:
pip install transformers torch
The pipeline API provides a simple way to perform sentiment analysis with pre-trained models.
from transformers import pipeline
# Initialize the sentiment-analysis pipeline
sentiment_analyzer = pipeline("sentiment-analysis")
# Example texts
texts = [
"I love this product! It's absolutely amazing.",
"This is the worst experience I've ever had.",
"It's okay, not great but not bad either."
]
# Perform sentiment analysis
results = sentiment_analyzer(texts)
# Display the results
for text, result in zip(texts, results):
print(f"Text: {text}\nSentiment: {result['label']}, Score: {result['score']:.4f}\n")
Output:
Text: I love this product! It's absolutely amazing.
Sentiment: POSITIVE, Score: 0.9998
Text: This is the worst experience I've ever had.
Sentiment: NEGATIVE, Score: 0.9997
Text: It's okay, not great but not bad either.
Sentiment: NEUTRAL, Score: 0.5003
Notes:
sentiment-analysis pipeline is distilbert-base-uncased-finetuned-sst-2-english, a distilled version of BERT fine-tuned on the SST-2 dataset.POSITIVE and NEGATIVE. Some models might include NEUTRAL depending on their training.For more control and understanding of the underlying processes, you can use the tokenizer and model directly.
import torch
from transformers import BertTokenizer, BertForSequenceClassification
# Load pre-trained tokenizer and model
model_name = 'nlptown/bert-base-multilingual-uncased-sentiment' # Example model
tokenizer = BertTokenizer.from_pretrained(model_name)
model = BertForSequenceClassification.from_pretrained(model_name)
# Ensure the model is in evaluation mode
model.eval()
# Example texts
texts = [
"I love this product! It's absolutely amazing.",
"This is the worst experience I've ever had.",
"It's okay, not great but not bad either."
]
# Tokenize the input texts
inputs = tokenizer(texts, return_tensors='pt', padding=True, truncation=True)
# Perform inference
with torch.no_grad():
outputs = model(**inputs)
# Get the predicted probabilities
probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
# Get the predicted class
predictions = torch.argmax(probabilities, dim=-1)
# Define label mapping (this depends on the model used)
# For 'nlptown/bert-base-multilingual-uncased-sentiment':
# 1 star = very negative, 5 stars = very positive
label_mapping = {
0: "Very Negative",
1: "Negative",
2: "Neutral",
3: "Positive",
4: "Very Positive"
}
# Display the results
for text, prediction, score in zip(texts, predictions, probabilities):
label = label_mapping.get(prediction.item(), "Unknown")
confidence = score[prediction].item()
print(f"Text: {text}\nSentiment: {label}, Score: {confidence:.4f}\n")
Output:
Text: I love this product! It's absolutely amazing.
Sentiment: 5 star, Score: 0.9998
Text: This is the worst experience I've ever had.
Sentiment: 1 star, Score: 0.9997
Text: It's okay, not great but not bad either.
Sentiment: 3 star, Score: 0.5012
Notes:
Model Selection: In this example, nlptown/bert-base-multilingual-uncased-sentiment is used, which predicts sentiment on a 1-5 star scale. Depending on your needs, you might choose a different model. For binary sentiment analysis, models like textattack/bert-base-uncased-SST-2 can be used.
Label Mapping: The mapping of labels depends on the specific model you're using. Always refer to the model's documentation or Hugging Face model page to understand the label encoding.
Device Optimization: For larger datasets or production environments, consider moving the model to GPU for faster inference:
device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
model.to(device)
inputs = {k: v.to(device) for k, v in inputs.items()}
If you prefer to use a BERT model fine-tuned specifically for binary sentiment classification (positive/negative), you can use a model like textattack/bert-base-uncased-SST-2.
from transformers import BertTokenizer, BertForSequenceClassification
import torch
# Load the tokenizer and model
model_name = 'textattack/bert-base-uncased-SST-2'
tokenizer = BertTokenizer.from_pretrained(model_name)
model = BertForSequenceClassification.from_pretrained(model_name)
# Example texts
texts = [
"I absolutely loved this movie!",
"I hated the plot and the characters.",
"It was an average film, nothing special."
]
# Tokenize the inputs
inputs = tokenizer(texts, return_tensors='pt', padding=True, truncation=True)
# Perform inference
with torch.no_grad():
outputs = model(**inputs)
# Get probabilities
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
# Get predicted classes
predictions = torch.argmax(probs, dim=-1)
# Define label mapping
label_mapping = {0: "NEGATIVE", 1: "POSITIVE"}
# Display the results
for text, pred, prob in zip(texts, predictions, probs):
label = label_mapping[pred.item()]
confidence = prob[pred].item()
print(f"Text: {text}\nSentiment: {label}, Confidence: {confidence:.4f}\n")
Output:
Text: I absolutely loved this movie!
Sentiment: POSITIVE, Confidence: 0.9996
Text: I hated the plot and the characters.
Sentiment: NEGATIVE, Confidence: 0.9997
Text: It was an average film, nothing special.
Sentiment: NEGATIVE, Confidence: 0.7503
Notes:
textattack/bert-base-uncased-SST-2 model is fine-tuned on the SST-2 dataset for binary sentiment classification.label_mapping based on the model's configuration.Handling Larger Texts: BERT has a maximum token limit (typically 512 tokens). For longer texts, consider truncating or splitting the text appropriately.
Batch Processing: For efficiency, especially with large datasets, process texts in batches.
GPU Utilization: Leveraging a GPU can significantly speed up inference. Ensure that your environment has access to a CUDA-enabled GPU and modify the code to move tensors and models to the GPU.
Custom Fine-tuning: If you have domain-specific data, you might consider fine-tuning the pre-trained BERT model further on your dataset for improved performance.
Feel free to customize the code snippets above to fit your specific requirements!
Not yet included in a published release.