Views
No views yet
SK_BPE_BLM-pos model in a Python script:1import torch
2from transformers import RobertaForTokenClassification, RobertaTokenizerFast
3from huggingface_hub import hf_hub_download
4import json
5
6class TokenClassifier:
7 def __init__(self, model, tokenizer):
8 self.model = RobertaForTokenClassification.from_pretrained(model, num_labels=14)
9 self.tokenizer = RobertaTokenizerFast.from_pretrained(tokenizer, max_length=256)
10 byte_utf8_mapping_path = hf_hub_download(repo_id=tokenizer, filename="byte_utf8_mapping.json")
11 with open(byte_utf8_mapping_path, "r", encoding="utf-8") as f:
12 self.byte_utf8_mapping = json.load(f)
13
14 def decode(self, tokens):
15 decoded_tokens = []
16 for token in tokens:
17 for k, v in self.byte_utf8_mapping.items():
18 if k in token:
19 token = token.replace(k, v)
20 token = token.replace("Ġ"," ")
21 decoded_tokens.append(token)
22 return decoded_tokens
23
24 def tokenize_text(self, text):
25 encoded_text = self.tokenizer(text.lower(), max_length=256, padding='max_length', truncation=True, return_tensors='pt')
26 return encoded_text
27
28 def classify_tokens(self, text):
29 encoded_text = self.tokenize_text(text)
30 tokens = self.tokenizer.convert_ids_to_tokens(encoded_text['input_ids'].squeeze().tolist())
31
32 with torch.no_grad():
33 output = self.model(**encoded_text)
34 logits = output.logits
35 predictions = torch.argmax(logits, dim=-1)
36
37 active_loss = encoded_text['attention_mask'].view(-1) == 1
38 active_logits = logits.view(-1, self.model.config.num_labels)[active_loss]
39 active_predictions = predictions.view(-1)[active_loss]
40
41 probabilities = torch.softmax(active_logits, dim=-1)
42
43 results = []
44 for token, pred, prob in zip(self.decode(tokens), active_predictions.tolist(), probabilities.tolist()):
45 if token not in ['<s>', '</s>', '<pad>']:
46 result = f"Token: {token: <10} POS tag: ({self.model.config.id2label[pred]} = {max(prob):.4f})"
47 results.append(result)
48
49 return results
50
51# Instantiate the POS token classifier with the specified tokenizer and model
52classifier = TokenClassifier(tokenizer="daviddrzik/SK_BPE_BLM", model="daviddrzik/SK_BPE_BLM-pos")
53
54# Tokenize the input text
55text_to_classify = "Od učenia ešte nikto nezomrel, ale načo riskovať."
56
57# Classify the tokens of the tokenized text
58classification_results = classifier.classify_tokens(text_to_classify)
59print(f"============= POS Token Classification =============")
60print("Text to classify:", text_to_classify)
61for classification_result in classification_results:
62 print(classification_result)1============= POS Token Classification =============
2Text to classify: Od učenia ešte nikto nezomrel, ale načo riskovať.
3Token: od POS tag: (ADP = 0.9984)
4Token: učenia POS tag: (NOUN = 0.9952)
5Token: ešte POS tag: (PART = 0.9720)
6Token: nikto POS tag: (PRON = 0.9947)
7Token: nezom POS tag: (VERB = 0.9973)
8Token: rel POS tag: (VERB = 0.9950)
9Token: , POS tag: (PUNCT = 0.9992)
10Token: ale POS tag: (CCONJ = 0.9981)
11Token: načo POS tag: (ADV = 0.9804)
12Token: riskovať POS tag: (VERB = 0.9948)
13Token: . POS tag: (PUNCT = 0.9994)