You can download this code by clicking the button below.
This code is now available for download.
This function uses a pre-trained model from the Huggingface Transformers library to classify the sentiment of the input text, determining whether the text is positive or negative.
Technology Stack : Huggingface Transformers
Code Type : The type of code
Code Difficulty : Intermediate
import torch
from transformers import AutoModelForSequenceClassification, AutoTokenizer
def classify_sentiment(text, model_name="distilbert-base-uncased-finetuned-sst-2-english"):
tokenizer = AutoTokenizer.from_pretrained(model_name)
model = AutoModelForSequenceClassification.from_pretrained(model_name)
inputs = tokenizer(text, return_tensors="pt")
outputs = model(**inputs)
_, prediction = torch.max(outputs.logits, dim=1)
return "positive" if prediction.item() == 1 else "negative"