Add looped sentiment inference script
Browse files- sentiment_inference.py +27 -0
sentiment_inference.py
ADDED
@@ -0,0 +1,27 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
1 |
+
from transformers import AutoTokenizer, AutoModelForSequenceClassification
|
2 |
+
import torch
|
3 |
+
|
4 |
+
# Load the pretrained sentiment model
|
5 |
+
model_name = "distilbert-base-uncased-finetuned-sst-2-english"
|
6 |
+
tokenizer = AutoTokenizer.from_pretrained(model_name)
|
7 |
+
model = AutoModelForSequenceClassification.from_pretrained(model_name)
|
8 |
+
|
9 |
+
# Function to classify sentiment
|
10 |
+
def analyze_sentiment(text):
|
11 |
+
inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
|
12 |
+
outputs = model(**inputs)
|
13 |
+
probs = torch.softmax(outputs.logits, dim=1)
|
14 |
+
prediction = torch.argmax(probs).item()
|
15 |
+
label = "positive" if prediction == 1 else "negative"
|
16 |
+
return label, probs[0][prediction].item()
|
17 |
+
|
18 |
+
# Try it out!
|
19 |
+
if __name__ == "__main__":
|
20 |
+
print("🧠 Sentiment Analyzer (type 'exit' to quit)\n")
|
21 |
+
while True:
|
22 |
+
sentence = input("Enter a sentence: ").strip()
|
23 |
+
if sentence.lower() in ["exit", "quit"]:
|
24 |
+
print("👋 Goodbye!")
|
25 |
+
break
|
26 |
+
sentiment, confidence = analyze_sentiment(sentence)
|
27 |
+
print(f"🧠 Sentiment: {sentiment.capitalize()} (Confidence: {confidence:.2f})\n")
|