File size: 1,559 Bytes
5b35880
 
 
 
 
 
18fad45
5b35880
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# Usage
```
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch

# Load model and tokenizer from the Hub
model_name = "FlukeTJ/wangchanberta-base-att-spm-uncased-finetuned-sentiment-cleaned-40k"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)

# Set device (GPU if available, else CPU)
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = model.to(device)

def predict_sentiment(text):
    # Tokenize the input text
    inputs = tokenizer(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
    inputs = {k: v.to(device) for k, v in inputs.items()}
    
    # Make prediction
    with torch.no_grad():
        outputs = model(**inputs)
    
    # Get probabilities
    probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
    
    # Get the predicted class 
    predicted_class = torch.argmax(probabilities, dim=1).item()
    
    # Map class to sentiment
    sentiment_map = {0: "Neutral", 1: "Positive", 2: "Negative"}
    predicted_sentiment = sentiment_map[predicted_class]
    
    # Get the confidence score
    confidence = probabilities[0][predicted_class].item()
    
    return predicted_sentiment, confidence

# Example usage
texts = [
    "สุดยอดดด"
]

for text in texts:
    sentiment, confidence = predict_sentiment(text)
    print(f"Text: {text}")
    print(f"Predicted Sentiment: {sentiment}")
    print(f"Confidence: {confidence:.2f}")
    print()
```