Views
No views yet
1from transformers import AutoTokenizer
2from transformers import AutoModelForTokenClassification
3from pythainlp.tokenize import word_tokenize # pip install pythainlp
4import torch
5
6name="pythainlp/thainer-corpus-v2-base-model"
7tokenizer = AutoTokenizer.from_pretrained(name)
8model = AutoModelForTokenClassification.from_pretrained(name)
9
10sentence="ฉันชื่อ นางสาวมะลิวา บุญสระดี อาศัยอยู่ที่อำเภอนางรอง จังหวัดบุรีรัมย์ อายุ 23 ปี เพิ่งเรียนจบจาก มหาวิทยาลัยขอนแก่น และนี่คือข้อมูลปลอมชื่อคนไม่มีอยู่จริง อายุ 23 ปี"
11cut=word_tokenize(sentence.replace(" ", "<_>"))
12inputs=tokenizer(cut,is_split_into_words=True,return_tensors="pt")
13
14ids = inputs["input_ids"]
15mask = inputs["attention_mask"]
16# forward pass
17outputs = model(ids, attention_mask=mask)
18logits = outputs[0]
19
20predictions = torch.argmax(logits, dim=2)
21predicted_token_class = [model.config.id2label[t.item()] for t in predictions[0]]
22
23def fix_span_error(words,ner):
24 _ner = []
25 _ner=ner
26 _new_tag=[]
27 for i,j in zip(words,_ner):
28 #print(i,j)
29 i=tokenizer.decode(i)
30 if i.isspace() and j.startswith("B-"):
31 j="O"
32 if i=='' or i=='<s>' or i=='</s>':
33 continue
34 if i=="<_>":
35 i=" "
36 _new_tag.append((i,j))
37 return _new_tag
38
39ner_tag=fix_span_error(inputs['input_ids'][0],predicted_token_class)
40print(ner_tag)1[('ฉัน', 'O'),
2 ('ชื่อ', 'O'),
3 (' ', 'O'),
4 ('นางสาว', 'B-PERSON'),
5 ('มะลิ', 'I-PERSON'),
6 ('วา', 'I-PERSON'),
7 (' ', 'I-PERSON'),
8 ('บุญ', 'I-PERSON'),
9 ('สระ', 'I-PERSON'),
10 ('ดี', 'I-PERSON'),
11 (' ', 'O'),
12 ('อาศัย', 'O'),
13 ('อยู่', 'O'),
14 ('ที่', 'O'),
15 ('อําเภอ', 'B-LOCATION'),
16 ('นาง', 'I-LOCATION'),
17 ('รอง', 'I-LOCATION'),
18 (' ', 'O'),
19 ('จังหวัด', 'B-LOCATION'),
20 ('บุรีรัมย์', 'I-LOCATION'),
21 (' ', 'O'),
22 ('อายุ', 'O'),
23 (' ', 'O'),
24 ('23', 'B-AGO'),
25 (' ', 'I-AGO'),
26 ('ปี', 'I-AGO'),
27 (' ', 'O'),
28 ('เพิ่ง', 'O'),
29 ('เรียนจบ', 'O'),
30 ('จาก', 'O'),
31 (' ', 'O'),
32 ('มหาวิทยาลั', 'B-ORGANIZATION'),
33 ('ยขอนแก่น', 'I-ORGANIZATION'),
34 (' ', 'O'),
35 ('และ', 'O'),
36 ('นี่', 'O'),
37 ('คือ', 'O'),
38 ('ข้อมูล', 'O'),
39 ('ปลอม', 'O'),
40 ('ชื่อ', 'O'),
41 ('คน', 'O'),
42 ('ไม่', 'O'),
43 ('มี', 'O'),
44 ('อยู่', 'O'),
45 ('จริง', 'O'),
46 (' ', 'O'),
47 ('อายุ', 'O'),
48 (' ', 'O'),
49 ('23', 'B-AGO'),
50 (' ', 'O'),
51 ('ปี', 'I-AGO')]Wannaphong Phatthiyaphaibun. (2022). Thai NER 2.0 (2.0) [Data set]. Zenodo. https://doi.org/10.5281/zenodo.7761354
@dataset{wannaphong_phatthiyaphaibun_2022_7761354,
author = {Wannaphong Phatthiyaphaibun},
title = {Thai NER 2.0},
month = sep,
year = 2022,
publisher = {Zenodo},
version = {2.0},
doi = {10.5281/zenodo.7761354},
url = {https://doi.org/10.5281/zenodo.7761354}
}