File size: 1,113 Bytes
2c2a85d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch

# Load the pretrained sentiment model
model_name = "distilbert-base-uncased-finetuned-sst-2-english"
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)

# Function to classify sentiment
def analyze_sentiment(text):
    inputs = tokenizer(text, return_tensors="pt", truncation=True, padding=True)
    outputs = model(**inputs)
    probs = torch.softmax(outputs.logits, dim=1)
    prediction = torch.argmax(probs).item()
    label = "positive" if prediction == 1 else "negative"
    return label, probs[0][prediction].item()

# Try it out!
if __name__ == "__main__":
    print("🧠 Sentiment Analyzer (type 'exit' to quit)\n")
    while True:
        sentence = input("Enter a sentence: ").strip()
        if sentence.lower() in ["exit", "quit"]:
            print("👋 Goodbye!")
            break
        sentiment, confidence = analyze_sentiment(sentence)
        print(f"🧠 Sentiment: {sentiment.capitalize()} (Confidence: {confidence:.2f})\n")