This program loads a pre-trained sentiment analysis model, tokenizes input text, runs the model, and prints the predicted sentiment with confidence scores.
from transformers import AutoModelForSequenceClassification, AutoTokenizer
import torch
model_name = 'distilbert-base-uncased-finetuned-sst-2-english'
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)
text = 'I love learning AI!'
inputs = tokenizer(text, return_tensors='pt')
outputs = model(**inputs)
predictions = torch.nn.functional.softmax(outputs.logits, dim=-1)
labels = ['negative', 'positive']
predicted_label = labels[predictions.argmax()]
print(f'Text: {text}')
print(f'Predicted sentiment: {predicted_label}')
print(f'Confidence scores: {predictions.detach().numpy()}')