Views
No views yet

1from transformers import pipeline
2import matplotlib.pyplot as plt
3import seaborn as sns
4
5# Load model directly from Hugging Face
6classifier = pipeline(
7 "text-classification",
8 model="ericwei/attention-sentiment-classifier"
9)
10
11# Standard prediction
12result = classifier("I absolutely loved this movie! The acting was superb.")
13print(f"Sentiment: {result[0]['label']}, Score: {result[0]['score']:.4f}")
14
15# For attention visualization, use the model directly
16from transformers import AutoTokenizer, AutoModel
17import torch
18
19tokenizer = AutoTokenizer.from_pretrained("ericwei/attention-sentiment-classifier")
20model = AutoModel.from_pretrained("weicwei/attention-sentiment-classifier")
21
22text = "I absolutely loved this movie! The acting was superb."
23inputs = tokenizer(text, return_tensors="pt")
24
25# Get prediction with attention weights
26model.eval()
27with torch.no_grad():
28 outputs = model(inputs["input_ids"], return_attention=True, return_dict=True)
29
30# Get prediction results
31logits = outputs["logits"]
32attention_weights = outputs["attention_weights"]
33
34# Visualize attention
35tokens = [tokenizer.convert_ids_to_tokens(id.item()) for id in inputs["input_ids"][0]]
36
37plt.figure(figsize=(10, 2))
38sns.heatmap(
39 attention_weights.squeeze(0).cpu().numpy().reshape(1, -1),
40 cmap="YlOrRd",
41 annot=True,
42 fmt=".2f",
43 cbar=False,
44 xticklabels=tokens,
45 yticklabels=["Attention"]
46)
47plt.xticks(rotation=45, ha="right", rotation_mode="anchor")
48plt.title("Attention Weights Visualization")
49plt.tight_layout()
50plt.show()@misc{attention-sentiment-classifier,
author = {Lantian Wei},
title = {Attention-based Sentiment Classifier},
year = {2025},
publisher = {Hugging Face},
howpublished = {\url{https://huggingface.co/your-username/attention-sentiment-classifier}}
}