Views
No views yet
| Model | Backbone | #params | lang | acc | Speed | #Train |
|---|---|---|---|---|---|---|
| zero-shot-classify-SSTuning-base | roberta-base | 125M | En | Low | High | 20.48M |
| zero-shot-classify-SSTuning-large | roberta-large | 355M | En | Medium | Medium | 5.12M |
| zero-shot-classify-SSTuning-ALBERT | albert-xxlarge-v2 | 235M | En | High | Low | 5.12M |
| zero-shot-classify-SSTuning-XLM-R | xlm-roberta-base | 278M | Multi | - | - | 20.48M |
1from transformers import AutoTokenizer, AutoModelForSequenceClassification
2import torch, string, random
3
4tokenizer = AutoTokenizer.from_pretrained("DAMO-NLP-SG/zero-shot-classify-SSTuning-XLM-R")
5model = AutoModelForSequenceClassification.from_pretrained("DAMO-NLP-SG/zero-shot-classify-SSTuning-XLM-R")
6
7text = "I love this place! The food is always so fresh and delicious."
8list_label = ["negative", "positive"]
9
10device = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')
11list_ABC = [x for x in string.ascii_uppercase]
12
13def check_text(model, text, list_label, shuffle=False):
14 list_label = [x+'.' if x[-1] != '.' else x for x in list_label]
15 list_label_new = list_label + [tokenizer.pad_token]* (20 - len(list_label))
16 if shuffle:
17 random.shuffle(list_label_new)
18 s_option = ' '.join(['('+list_ABC[i]+') '+list_label_new[i] for i in range(len(list_label_new))])
19 text = f'{s_option} {tokenizer.sep_token} {text}'
20
21 model.to(device).eval()
22 encoding = tokenizer([text],truncation=True, max_length=512,return_tensors='pt')
23 item = {key: val.to(device) for key, val in encoding.items()}
24 logits = model(**item).logits
25
26 logits = logits if shuffle else logits[:,0:len(list_label)]
27 probs = torch.nn.functional.softmax(logits, dim = -1).tolist()
28 predictions = torch.argmax(logits, dim=-1).item()
29 probabilities = [round(x,5) for x in probs[0]]
30
31 print(f'prediction: {predictions} => ({list_ABC[predictions]}) {list_label_new[predictions]}')
32 print(f'probability: {round(probabilities[predictions]*100,2)}%')
33
34check_text(model, text, list_label)
35# prediction: 1 => (B) positive.
36# probability: 99.92%1@inproceedings{acl23/SSTuning,
2 author = {Chaoqun Liu and
3 Wenxuan Zhang and
4 Guizhen Chen and
5 Xiaobao Wu and
6 Anh Tuan Luu and
7 Chip Hong Chang and
8 Lidong Bing},
9 title = {Zero-Shot Text Classification via Self-Supervised Tuning},
10 booktitle = {Findings of the Association for Computational Linguistics: ACL 2023},
11 year = {2023},
12 url = {https://arxiv.org/abs/2305.11442},
13}