Views
No views yet
1from transformers import AutoTokenizer, AutoModelForSequenceClassification
2import torch
3
4# Load model and tokenizer
5tokenizer = AutoTokenizer.from_pretrained("Khoa/vietnamese-sentiment-analysis-with-entity")
6model = AutoModelForSequenceClassification.from_pretrained("Khoa/vietnamese-sentiment-analysis-with-entity")
7
8# Function to predict sentiment
9def predict_sentiment(text, entity, model, tokenizer):
10 combined_text = f"Đối với {entity}, {text}"
11 inputs = tokenizer(combined_text, return_tensors="pt", truncation=True, padding=True)
12
13 with torch.no_grad():
14 outputs = model(**inputs)
15 predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
16 predicted_class = torch.argmax(predictions, dim=-1).item()
17
18 sentiment_labels = {0: "NEGATIVE", 1: "NEUTRAL", 2: "POSITIVE"}
19 return sentiment_labels[predicted_class], predictions[0].tolist()
20
21# Example usage
22text = "Món ăn rất ngon nhưng giá hơi đắt"
23entity = "Nhà hàng ABC"
24sentiment, confidence = predict_sentiment(text, entity, model, tokenizer)
25print(f"Sentiment: {sentiment}")