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='emotion'
23MODEL = f"cardiffnlp/twitter-roberta-base-{task}"
24
25tokenizer = AutoTokenizer.from_pretrained(MODEL)
26
27# download label mapping
28mapping_link = f"https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/{task}/mapping.txt"
29with urllib.request.urlopen(mapping_link) as f:
30 html = f.read().decode('utf-8').split("\n")
31 csvreader = csv.reader(html, delimiter='\t')
32labels = [row[1] for row in csvreader if len(row) > 1]
33
34# PT
35model = AutoModelForSequenceClassification.from_pretrained(MODEL)
36model.save_pretrained(MODEL)
37
38text = "Celebrating my promotion 😎"
39text = preprocess(text)
40encoded_input = tokenizer(text, return_tensors='pt')
41output = model(**encoded_input)
42scores = output[0][0].detach().numpy()
43scores = softmax(scores)
44
45# # TF
46# model = TFAutoModelForSequenceClassification.from_pretrained(MODEL)
47# model.save_pretrained(MODEL)
48
49# text = "Celebrating my promotion 😎"
50# encoded_input = tokenizer(text, return_tensors='tf')
51# output = model(encoded_input)
52# scores = output[0][0].numpy()
53# scores = softmax(scores)
54
55ranking = np.argsort(scores)
56ranking = ranking[::-1]
57for i in range(scores.shape[0]):
58 l = labels[ranking[i]]
59 s = scores[ranking[i]]
60 print(f"{i+1}) {l} {np.round(float(s), 4)}")
611) joy 0.9382
2) optimism 0.0362
3) anger 0.0145
4) sadness 0.0112