Views
No views yet
non-toxic: the text does NOT contain insults, obscenities, and threats, in the sense of the OK ML Cup competition.insultobscenitythreatdangerous: the text is inappropriate, in the sense of Babakov et.al., i.e. it can harm the reputation of the speaker.non-toxic and NOT dangerous.1# !pip install transformers sentencepiece --quiet
2import torch
3from transformers import AutoTokenizer, AutoModelForSequenceClassification
4
5model_checkpoint = 'cointegrated/rubert-tiny-toxicity'
6tokenizer = AutoTokenizer.from_pretrained(model_checkpoint)
7model = AutoModelForSequenceClassification.from_pretrained(model_checkpoint)
8if torch.cuda.is_available():
9 model.cuda()
10
11def text2toxicity(text, aggregate=True):
12 """ Calculate toxicity of a text (if aggregate=True) or a vector of toxicity aspects (if aggregate=False)"""
13 with torch.no_grad():
14 inputs = tokenizer(text, return_tensors='pt', truncation=True, padding=True).to(model.device)
15 proba = torch.sigmoid(model(**inputs).logits).cpu().numpy()
16 if isinstance(text, str):
17 proba = proba[0]
18 if aggregate:
19 return 1 - proba.T[0] * (1 - proba.T[-1])
20 return proba
21
22print(text2toxicity('я люблю нигеров', True))
23# 0.9350118728093193
24
25print(text2toxicity('я люблю нигеров', False))
26# [0.9715758 0.0180863 0.0045551 0.00189755 0.9331106 ]
27
28print(text2toxicity(['я люблю нигеров', 'я люблю африканцев'], True))
29# [0.93501186 0.04156357]
30
31print(text2toxicity(['я люблю нигеров', 'я люблю африканцев'], False))
32# [[9.7157580e-01 1.8086294e-02 4.5550885e-03 1.8975559e-03 9.3311059e-01]
33# [9.9979788e-01 1.9048342e-04 1.5297388e-04 1.7452303e-04 4.1369814e-02]]Adam optimizer, the learning rate of 1e-5, and batch size of 64 for 15 epochs in this Colab notebook.
A text was considered inappropriate if its inappropriateness score was higher than 0.8, and appropriate - if it was lower than 0.2. The per-label ROC AUC on the dev set is:non-toxic : 0.9937
insult : 0.9912
obscenity : 0.9881
threat : 0.9910
dangerous : 0.8295