Views
No views yet
bert-base-uncased for multi-label emotion classification.bert-base-uncasedangerfeardisgustsadnesssurprisejoyanticipationtrust1import torch
2from transformers import BertTokenizer, BertForSequenceClassification
3
4# Set device
5device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
6
7# Load model and tokenizer
8model_path = "sajeewa/emotion-classification-bert"
9emotion_labels = ["anger", "fear", "disgust", "sadness", "surprise", "joy", "anticipation", "trust"]
10
11tokenizer = BertTokenizer.from_pretrained(model_path)
12model = BertForSequenceClassification.from_pretrained(model_path, num_labels=len(emotion_labels)).to(device)
13
14# Emotion prediction function
15def predict_emotions(text: str):
16 model.eval()
17 inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=50).to(device)
18 inputs.pop("token_type_ids", None)
19
20 with torch.no_grad():
21 logits = model(**inputs).logits
22
23 probs = torch.sigmoid(logits).cpu().numpy()[0]
24 return {label: round(float(score), 4) for label, score in zip(emotion_labels, probs)}
25
26# Example usage
27example_text = "I'm feeling lonely today."
28predictions = predict_emotions(example_text)
29dominant_emotion = max(predictions, key=predictions.get)
30print({dominant_emotion: predictions[dominant_emotion]})