Views
No views yet
1from transformers import AutoModelForSequenceClassification
2from transformers import TFAutoModelForSequenceClassification
3from transformers import AutoTokenizer
4import numpy as np
5from scipy.special import softmax
6import csv
7import urllib.request
8
9# Preprocess text (username and link placeholders)
10def preprocess(text):
11 new_text = []
12
13
14 for t in text.split(" "):
15 t = '@user' if t.startswith('@') and len(t) > 1 else t
16 t = 'http' if t.startswith('http') else t
17 new_text.append(t)
18 return " ".join(new_text)
19
20# Tasks:
21# emoji, emotion, hate, irony, offensive, sentiment
22# stance/abortion, stance/atheism, stance/climate, stance/feminist, stance/hillary
23
24task='sentiment'
25MODEL = f"cardiffnlp/twitter-roberta-base-{task}"
26
27tokenizer = AutoTokenizer.from_pretrained(MODEL)
28
29# download label mapping
30labels=[]
31mapping_link = f"https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/{task}/mapping.txt"
32with urllib.request.urlopen(mapping_link) as f:
33 html = f.read().decode('utf-8').split("\n")
34 csvreader = csv.reader(html, delimiter='\t')
35labels = [row[1] for row in csvreader if len(row) > 1]
36
37# PT
38model = AutoModelForSequenceClassification.from_pretrained(MODEL)
39model.save_pretrained(MODEL)
40
41text = "Good night 😊"
42text = preprocess(text)
43encoded_input = tokenizer(text, return_tensors='pt')
44output = model(**encoded_input)
45scores = output[0][0].detach().numpy()
46scores = softmax(scores)
47
48# # TF
49# model = TFAutoModelForSequenceClassification.from_pretrained(MODEL)
50# model.save_pretrained(MODEL)
51
52# text = "Good night 😊"
53# encoded_input = tokenizer(text, return_tensors='tf')
54# output = model(encoded_input)
55# scores = output[0][0].numpy()
56# scores = softmax(scores)
57
58ranking = np.argsort(scores)
59ranking = ranking[::-1]
60for i in range(scores.shape[0]):
61 l = labels[ranking[i]]
62 s = scores[ranking[i]]
63 print(f"{i+1}) {l} {np.round(float(s), 4)}")
641) positive 0.8466
2) neutral 0.1458
3) negative 0.00761@inproceedings{barbieri-etal-2020-tweeteval,
2 title = "{T}weet{E}val: Unified Benchmark and Comparative Evaluation for Tweet Classification",
3 author = "Barbieri, Francesco and
4 Camacho-Collados, Jose and
5 Espinosa Anke, Luis and
6 Neves, Leonardo",
7 booktitle = "Findings of the Association for Computational Linguistics: EMNLP 2020",
8 month = nov,
9 year = "2020",
10 address = "Online",
11 publisher = "Association for Computational Linguistics",
12 url = "https://aclanthology.org/2020.findings-emnlp.148",
13 doi = "10.18653/v1/2020.findings-emnlp.148",
14 pages = "1644--1650"
15}