Views
No views yet
1from transformers import AutoModelForSequenceClassification
2from transformers import AutoTokenizer
3import numpy as np
4from scipy.special import softmax
5import csv
6import urllib.request
7
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 = "Sharon1020/twitter-bert-base-emoji"
17tokenizer = AutoTokenizer.from_pretrained(MODEL)
18model = AutoModelForSequenceClassification.from_pretrained(MODEL)
19
20labels = []
21mapping_link = "https://raw.githubusercontent.com/cardiffnlp/tweeteval/main/datasets/emoji/mapping.txt"
22with urllib.request.urlopen(mapping_link) as f:
23 html = f.read().decode('utf-8').split("\n")
24 csvreader = csv.reader(html, delimiter='\t')
25labels = [row[1] for row in csvreader if len(row) > 1]
26
27text = "Looking forward to Christmas"
28text = preprocess(text)
29encoded_input = tokenizer(text, return_tensors='pt')
30output = model(**encoded_input)
31scores = output[0][0].detach().numpy()
32scores = softmax(scores)
33
34ranking = np.argsort(scores)
35ranking = ranking[::-1]
36for i in range(scores.shape[0]):
37 l = labels[ranking[i]]
38 s = scores[ranking[i]]
39 print(f"{i+1}) {l} {np.round(float(s), 4)}")1) 🎄 0.5457
2) 😊 0.1417
3) 😁 0.0649
4) 😍 0.0395
5) ❤️ 0.03
6) 😜 0.028
7) ✨ 0.0263
8) 😉 0.0237
9) 😂 0.0177
10) 😎 0.0166
11) 😘 0.0143
12) 💕 0.014
13) 💙 0.0076
14) 💜 0.0068
15) 🔥 0.0065
16) 💯 0.004
17) 🇺🇸 0.0037
18) 📷 0.0034
19) ☀ 0.0033
20) 📸 0.00211from transformers import pipeline
2
3classifier = pipeline("text-classification",
4 model="Sharon1020/twitter-bert-base-emoji",
5 tokenizer="Sharon1020/twitter-bert-base-emoji")
6
7result = classifier("I love sunny days!")
8print(result)1@inproceedings{barbieri2020tweeteval,
2 title={TweetEval: Unified Benchmark and Comparative Evaluation for Tweet Classification},
3 author={Barbieri, Francesco and Camacho-Collados, Jose and Espinosa-Anke, Luis and Neves, Leonardo},
4 booktitle={Findings of EMNLP},
5 year={2020}
6}