Views
No views yet
1from transformers import pipeline
2model_path = "cardiffnlp/twitter-xlm-roberta-base-sentiment"
3sentiment_task = pipeline("sentiment-analysis", model=model_path, tokenizer=model_path)
4sentiment_task("T'estimo!")[{'label': 'Positive', 'score': 0.6600581407546997}]1from transformers import AutoModelForSequenceClassification
2from transformers import TFAutoModelForSequenceClassification
3from transformers import AutoTokenizer, AutoConfig
4import numpy as np
5from scipy.special import softmax
6
7# Preprocess text (username and link placeholders)
8def preprocess(text):
9 new_text = []
10 for t in text.split(" "):
11 t = '@user' if t.startswith('@') and len(t) > 1 else t
12 t = 'http' if t.startswith('http') else t
13 new_text.append(t)
14 return " ".join(new_text)
15
16MODEL = f"cardiffnlp/twitter-xlm-roberta-base-sentiment"
17
18tokenizer = AutoTokenizer.from_pretrained(MODEL)
19config = AutoConfig.from_pretrained(MODEL)
20
21# PT
22model = AutoModelForSequenceClassification.from_pretrained(MODEL)
23model.save_pretrained(MODEL)
24
25text = "Good night 😊"
26text = preprocess(text)
27encoded_input = tokenizer(text, return_tensors='pt')
28output = model(**encoded_input)
29scores = output[0][0].detach().numpy()
30scores = softmax(scores)
31
32# # TF
33# model = TFAutoModelForSequenceClassification.from_pretrained(MODEL)
34# model.save_pretrained(MODEL)
35
36# text = "Good night 😊"
37# encoded_input = tokenizer(text, return_tensors='tf')
38# output = model(encoded_input)
39# scores = output[0][0].numpy()
40# scores = softmax(scores)
41
42# Print labels and scores
43ranking = np.argsort(scores)
44ranking = ranking[::-1]
45for i in range(scores.shape[0]):
46 l = config.id2label[ranking[i]]
47 s = scores[ranking[i]]
48 print(f"{i+1}) {l} {np.round(float(s), 4)}")
491) Positive 0.7673
2) Neutral 0.2015
3) Negative 0.0313@inproceedings{barbieri-etal-2022-xlm,
title = "{XLM}-{T}: Multilingual Language Models in {T}witter for Sentiment Analysis and Beyond",
author = "Barbieri, Francesco and
Espinosa Anke, Luis and
Camacho-Collados, Jose",
booktitle = "Proceedings of the Thirteenth Language Resources and Evaluation Conference",
month = jun,
year = "2022",
address = "Marseille, France",
publisher = "European Language Resources Association",
url = "https://aclanthology.org/2022.lrec-1.27",
pages = "258--266"
}