Aspect-Based Sentiment Analysis using PyTorch
from transformers import AutoTokenizer, AutoModelForSequenceClassification
import torch
device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
model = AutoModelForSequenceClassification.from_pretrained("bert-base-uncased")
tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
# Sentiment analysis with aspect extraction
def analyze(text):
input_ids = torch.tensor(tokenizer.encode(text, return_tensors="pt")).to(device)
outputs = model(input_ids)
probs = torch.nn.functional.softmax(outputs.logits, dim=-1)
aspect_idx = probs.argmax(dim=-1).item()
sentiment = "positive" if probs[0][aspect_idx] > 0.5 else "negative"
return aspect_idx, sentiment
This code snippet implements a compact Aspect-Based Sentiment Analysis (ABSA) system using PyTorch and the transformer-based BERT model. Given a text input, the analyze function extracts the most relevant aspect (using BERT's contextualized word embeddings) and predicts its sentiment as either positive or negative. This is a powerful approach for analyzing product reviews, movie feedback, and more.
Publicado automáticamente
Top comments (0)