im not getting this output, can you also include a neutral class and rewrite a fully…
- User
im not getting this output, can you also include a neutral class and rewrite a fully working model, maybe use BERT for sentiment analysis this time?
- Assistant
im not getting this output, can you also include a neutral class and rewrite a fully working model, maybe use BERT for sentiment analysis this time?
Certainly! Let's create a fully working sentiment analysis model using BERT that classifies text into Positive, Negative, and Neutral classes. We'll use the Hugging Face Transformers library along with PyTorch to accomplish this.
First, ensure you have the necessary libraries installed. You can install them using pip:
pip install transformers
pip install torch
pip install scikit-learn
pip install pandas
pip install tqdm
For demonstration purposes, let's assume you have a CSV file (sentiment_data.csv) with two columns: text and label, where label can be positive, negative, or neutral.
Example of sentiment_data.csv:
| text | label |
|---|---|
| I love this product! | positive |
| This is the worst experience ever. | negative |
| The movie was okay, not great but not bad. | neutral |
| ... | ... |
We'll preprocess the data by tokenizing the text using BERT's tokenizer and encoding the labels.
import pandas as pd
import torch
from torch.utils.data import Dataset, DataLoader
from transformers import BertTokenizer
# Define the device
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# Load the dataset
df = pd.read_csv('sentiment_data.csv')
# Encode labels
label_dict = {'negative': 0, 'neutral': 1, 'positive': 2}
df['label'] = df['label'].map(label_dict)
# Split into training and validation sets
from sklearn.model_selection import train_test_split
train_texts, val_texts, train_labels, val_labels = train_test_split(
df['text'].values,
df['label'].values,
test_size=0.2,
random_state=42
)
# Initialize the BERT tokenizer
tokenizer = BertTokenizer.from_pretrained('bert-base-uncased')
# Define a custom dataset class
class SentimentDataset(Dataset):
def __init__(self, texts, labels, tokenizer, max_len=128):
self.texts = texts
self.labels = labels
self.tokenizer = tokenizer
self.max_len = max_len
def __len__(self):
return len(self.texts)
def __getitem__(self, idx):
text = str(self.texts[idx])
label = self.labels[idx]
encoding = self.tokenizer.encode_plus(
text,
add_special_tokens=True,
max_length=self.max_len,
return_token_type_ids=False,
padding='max_length',
truncation=True,
return_attention_mask=True,
return_tensors='pt',
)
return {
'input_ids': encoding['input_ids'].flatten(), # Shape: [max_len]
'attention_mask': encoding['attention_mask'].flatten(),
'labels': torch.tensor(label, dtype=torch.long)
}
# Create dataset and dataloader
batch_size = 16
train_dataset = SentimentDataset(train_texts, train_labels, tokenizer)
val_dataset = SentimentDataset(val_texts, val_labels, tokenizer)
train_loader = DataLoader(train_dataset, batch_size=batch_size, shuffle=True)
val_loader = DataLoader(val_dataset, batch_size=batch_size)
We'll use BertForSequenceClassification from Hugging Face, which is suitable for classification tasks.
from transformers import BertForSequenceClassification, AdamW, get_linear_schedule_with_warmup
# Initialize the model
model = BertForSequenceClassification.from_pretrained(
'bert-base-uncased',
num_labels=3, # Negative, Neutral, Positive
output_attentions=False,
output_hidden_states=False
)
model = model.to(device)
We'll define the optimizer, scheduler, and the training loop.
from tqdm import tqdm
import numpy as np
# Define optimizer and scheduler
optimizer = AdamW(model.parameters(), lr=2e-5, correct_bias=False)
total_steps = len(train_loader) * 3 # 3 epochs
scheduler = get_linear_schedule_with_warmup(
optimizer,
num_warmup_steps=0,
num_training_steps=total_steps
)
# Define loss function
from torch.nn import CrossEntropyLoss
loss_fn = CrossEntropyLoss().to(device)
# Training function
def train_epoch(
model,
data_loader,
loss_fn,
optimizer,
scheduler,
device,
n_examples
):
model.train()
losses = []
correct_predictions = 0
for batch in tqdm(data_loader, desc="Training"):
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask,
labels=labels
)
loss = outputs.loss
logits = outputs.logits
_, preds = torch.max(logits, dim=1)
correct_predictions += torch.sum(preds == labels)
losses.append(loss.item())
loss.backward()
torch.nn.utils.clip_grad_norm_(model.parameters(), max_norm=1.0)
optimizer.step()
scheduler.step()
optimizer.zero_grad()
return correct_predictions.double() / n_examples, np.mean(losses)
# Evaluation function
def eval_model(model, data_loader, loss_fn, device, n_examples):
model.eval()
losses = []
correct_predictions = 0
with torch.no_grad():
for batch in tqdm(data_loader, desc="Evaluating"):
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask,
labels=labels
)
loss = outputs.loss
logits = outputs.logits
_, preds = torch.max(logits, dim=1)
correct_predictions += torch.sum(preds == labels)
losses.append(loss.item())
return correct_predictions.double() / n_examples, np.mean(losses)
# Training loop
epochs = 3
for epoch in range(epochs):
print(f'Epoch {epoch +1}/{epochs}')
print('-' * 10)
train_acc, train_loss = train_epoch(
model,
train_loader,
loss_fn,
optimizer,
scheduler,
device,
len(train_dataset)
)
print(f'Train loss {train_loss} accuracy {train_acc}')
val_acc, val_loss = eval_model(
model,
val_loader,
loss_fn,
device,
len(val_dataset)
)
print(f'Val loss {val_loss} accuracy {val_acc}')
print()
After training, it's essential to evaluate the model using metrics like accuracy, precision, recall, and F1-score.
from sklearn.metrics import classification_report
def get_predictions(model, data_loader):
model.eval()
texts = []
predictions = []
prediction_probs = []
real_labels = []
with torch.no_grad():
for batch in tqdm(data_loader, desc="Predicting"):
input_ids = batch['input_ids'].to(device)
attention_mask = batch['attention_mask'].to(device)
labels = batch['labels'].to(device)
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask
)
logits = outputs.logits
probs = torch.softmax(logits, dim=1)
_, preds = torch.max(probs, dim=1)
predictions.extend(preds.cpu().numpy())
prediction_probs.extend(probs.cpu().numpy())
real_labels.extend(labels.cpu().numpy())
return predictions, prediction_probs, real_labels
preds, probs, true_labels = get_predictions(model, val_loader)
# Classification report
print(classification_report(true_labels, preds, target_names=label_dict.keys()))
Sample Output:
precision recall f1-score support
negative 0.85 0.80 0.82 50
neutral 0.78 0.85 0.81 50
positive 0.80 0.79 0.80 50
accuracy 0.81 150
macro avg 0.81 0.81 0.81 150
weighted avg 0.81 0.81 0.81 150
You can create a function to predict the sentiment of new sentences.
def predict_sentiment(text, model, tokenizer, device, max_len=128):
model.eval()
encoding = tokenizer.encode_plus(
text,
add_special_tokens=True,
max_length=max_len,
return_token_type_ids=False,
padding='max_length',
truncation=True,
return_attention_mask=True,
return_tensors='pt',
)
input_ids = encoding['input_ids'].to(device)
attention_mask = encoding['attention_mask'].to(device)
with torch.no_grad():
outputs = model(
input_ids=input_ids,
attention_mask=attention_mask
)
logits = outputs.logits
probs = torch.softmax(logits, dim=1)
confidence, pred = torch.max(probs, dim=1)
label_map = {0: 'negative', 1: 'neutral', 2: 'positive'}
return label_map[pred.item()], confidence.item()
# Example usage
text = "I'm feeling great today!"
sentiment, confidence = predict_sentiment(text, model, tokenizer, device)
print(f"Sentiment: {sentiment}, Confidence: {confidence:.2f}")
Sample Output:
Sentiment: positive, Confidence: 0.95
# Save the model
model.save_pretrained('sentiment-model')
tokenizer.save_pretrained('sentiment-model')
from transformers import BertForSequenceClassification, BertTokenizer
model = BertForSequenceClassification.from_pretrained('sentiment-model')
tokenizer = BertTokenizer.from_pretrained('sentiment-model')
model = model.to(device)
CUDA Out of Memory:
batch_size.max_len.Poor Performance:
Inconsistent Results:
import random
import numpy as np
import torch
def set_seed(seed=42):
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
set_seed()
This guide provides a comprehensive approach to building a BERT-based sentiment analysis model with three classes: Negative, Neutral, and Positive. By following these steps, you can train, evaluate, and deploy a robust sentiment classifier tailored to your specific needs.
If you encounter any specific errors or issues while implementing this model, feel free to share the error messages or problematic code snippets, and I'll be happy to help you debug!
Not yet included in a published release.