Views
No views yet
1from transformers import DistilBertForSequenceClassification, PreTrainedTokenizerFast
2import torch
3
4# Load the tokenizer and model
5tokenizers = PreTrainedTokenizerFast.from_pretrained("FlukeTJ/distilbert-base-thai-sentiment")
6models = DistilBertForSequenceClassification.from_pretrained("FlukeTJ/distilbert-base-thai-sentiment")
7
8# Set device (GPU if available, else CPU)
9device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
10models = models.to(device)
11
12def predict_sentiment(text):
13 # Tokenize the input text without token_type_ids
14 inputs = tokenizers(text, return_tensors="pt", padding=True, truncation=True, max_length=512)
15 inputs.pop("token_type_ids", None) # Remove token_type_ids if present
16
17 inputs = {k: v.to(device) for k, v in inputs.items()}
18
19 # Make prediction
20 with torch.no_grad():
21 outputs = models(**inputs)
22
23 # Get probabilities
24 probabilities = torch.nn.functional.softmax(outputs.logits, dim=-1)
25
26 # Get the predicted class
27 predicted_class = torch.argmax(probabilities, dim=1).item()
28
29 # Map class to sentiment
30 sentiment_map = {1: "Neutral", 0: "Positive", 2: "Negative"}
31 predicted_sentiment = sentiment_map[predicted_class]
32
33 # Get the confidence score
34 confidence = probabilities[0][predicted_class].item()
35
36 return predicted_sentiment, confidence
37
38# Example usage
39texts = [
40 "สุดยอดดด"
41]
42
43for text in texts:
44 sentiment, confidence = predict_sentiment(text)
45 print(f"Text: {text}")
46 print(f"Predicted Sentiment: {sentiment}")
47 print(f"Confidence: {confidence:.2f}")
48
49# =============================
50# Result
51# Text: สุดยอดดด
52# Predicted Sentiment: Positive
53# Confidence: 0.96
54# =============================| Training Loss | Step | Validation Loss | F1 Micro |
|---|---|---|---|
| 0.8035 | 500 | 0.5608 | 0.7821 |
| 0.4855 | 1000 | 0.4392 | 0.8266 |
| 0.3769 | 1500 | 0.3930 | 0.8433 |
| 0.3159 | 2000 | 0.3589 | 0.8675 |
| 0.279 | 2500 | 0.3552 | 0.8697 |
| 0.2463 | 3000 | 0.3812 | 0.8699 |
| 0.226 | 3500 | 0.3619 | 0.8690 |
| 0.2072 | 4000 | 0.3548 | 0.8754 |
| 0.1926 | 4500 | 0.3656 | 0.8763 |