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 for t in text.split(" "):
14 t = '@user' if t.startswith('@') and len(t) > 1 else t
15 t = 'http' if t.startswith('http') else t
16 new_text.append(t)
17 return " ".join(new_text)
18
19# Tasks:
20# emoji, emotion, hate, irony, offensive, sentiment
21# stance/abortion, stance/atheism, stance/climate, stance/feminist, stance/hillary
22
23task='irony'
24MODEL = f"cardiffnlp/twitter-roberta-base-{task}"
25
26tokenizer = AutoTokenizer.from_pretrained(MODEL)
27
28# download label mapping
29labels=[]
30mapping_link = f"https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/{task}/mapping.txt"
31with urllib.request.urlopen(mapping_link) as f:
32 html = f.read().decode('utf-8').split("\n")
33 csvreader = csv.reader(html, delimiter='\t')
34labels = [row[1] for row in csvreader if len(row) > 1]
35
36# PT
37model = AutoModelForSequenceClassification.from_pretrained(MODEL)
38model.save_pretrained(MODEL)
39
40text = "Great, it broke the first day..."
41text = preprocess(text)
42encoded_input = tokenizer(text, return_tensors='pt')
43output = model(**encoded_input)
44scores = output[0][0].detach().numpy()
45scores = softmax(scores)
46
47# # TF
48# model = TFAutoModelForSequenceClassification.from_pretrained(MODEL)
49# model.save_pretrained(MODEL)
50
51# text = "Great, it broke the first day..."
52# encoded_input = tokenizer(text, return_tensors='tf')
53# output = model(encoded_input)
54# scores = output[0][0].numpy()
55# scores = softmax(scores)
56
57ranking = np.argsort(scores)
58ranking = ranking[::-1]
59for i in range(scores.shape[0]):
60 l = labels[ranking[i]]
61 s = scores[ranking[i]]
62 print(f"{i+1}) {l} {np.round(float(s), 4)}")
631) irony 0.914
2) non_irony 0.0861@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}