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