Task-specific models offer high accuracy and efficiency for well-defined classification tasks.
Here's an example using a fine-tuned RoBERTa model for sentiment analysis.
Python code:
$ vi representation-sentiment.py
from transformers import AutoTokenizer, AutoConfig, AutoModelForSequenceClassification
import numpy as np
from scipy.special import softmax
import torch
MODEL = "cardiffnlp/twitter-roberta-base-sentiment-latest"
try:
# load the pre-trained sentiment analysis model, tokenizer, and configuration
model = AutoModelForSequenceClassification.from_pretrained(MODEL)
tokenizer = AutoTokenizer.from_pretrained(MODEL)
config = AutoConfig.from_pretrained(MODEL)
# Tokenize input text
encoded_input = tokenizer("The weather today is great!", return_tensors='pt', truncation=True, padding=True)
# analyze sentiment of input text and return predictions
with torch.no_grad(): # disable gradient computation for inference
output = model(**encoded_input)
# extract and normalize scores using softmax
scores = output.logits[0].detach().numpy()
scores = softmax(scores)
# rank predictions by confidence (highest to lowest)
ranking = np.argsort(scores)[::-1]
for i in range(len(scores)):
label = config.id2label[ranking[i]]
score = scores[ranking[i]]
print(f"{i+1}) {label.capitalize()}: {np.round(float(score), 4)}")
except Exception as e:
print(f"Error: {e}")
Run the Python script:
$ python3 representation-sentiment.py
Output:
1) Positive: 0.9899
2) Neutral: 0.0068
3) Negative: 0.0033