Views
No views yet
1pip install pythainlp six sentencepiece python-crfsuite
2git clone https://github.com/ThAIKeras/bert
3# download .vocab and .model files from ThAIKeras/bert > Tokenization section1import collections
2import unicodedata
3import six
4
5def convert_to_unicode(text):
6 """Converts `text` to Unicode (if it's not already), assuming utf-8 input."""
7 if six.PY3:
8 if isinstance(text, str):
9 return text
10 elif isinstance(text, bytes):
11 return text.decode("utf-8", "ignore")
12 else:
13 raise ValueError("Unsupported string type: %s" % (type(text)))
14 elif six.PY2:
15 if isinstance(text, str):
16 return text.decode("utf-8", "ignore")
17 elif isinstance(text, unicode):
18 return text
19 else:
20 raise ValueError("Unsupported string type: %s" % (type(text)))
21 else:
22 raise ValueError("Not running on Python2 or Python 3?")
23
24def load_vocab(vocab_file):
25 vocab = collections.OrderedDict()
26 index = 0
27 with open(vocab_file, "r") as reader:
28 while True:
29 token = reader.readline()
30 if token.split(): token = token.split()[0] # to support SentencePiece vocab file
31 token = convert_to_unicode(token)
32 if not token:
33 break
34 token = token.strip()
35 vocab[token] = index
36 index += 1
37 return vocab
38
39#####
40
41from bert.bpe_helper import BPE
42import sentencepiece as spm
43
44def convert_by_vocab(vocab, items):
45 output = []
46 for item in items:
47 output.append(vocab[item])
48 return output
49
50class ThaiTokenizer(object):
51 """Tokenizes Thai texts."""
52
53 def __init__(self, vocab_file, spm_file):
54 self.vocab = load_vocab(vocab_file)
55 self.inv_vocab = {v: k for k, v in self.vocab.items()}
56
57 self.bpe = BPE(vocab_file)
58 self.s = spm.SentencePieceProcessor()
59 self.s.Load(spm_file)
60
61 def tokenize(self, text):
62 bpe_tokens = self.bpe.encode(text).split(' ')
63 spm_tokens = self.s.EncodeAsPieces(text)
64
65 tokens = bpe_tokens if len(bpe_tokens) < len(spm_tokens) else spm_tokens
66
67 split_tokens = []
68
69 for token in tokens:
70 new_token = token
71
72 if token.startswith('_') and not token in self.vocab:
73 split_tokens.append('_')
74 new_token = token[1:]
75
76 if not new_token in self.vocab:
77 split_tokens.append('<unk>')
78 else:
79 split_tokens.append(new_token)
80
81 return split_tokens
82
83 def convert_tokens_to_ids(self, tokens):
84 return convert_by_vocab(self.vocab, tokens)
85
86 def convert_ids_to_tokens(self, ids):
87 return convert_by_vocab(self.inv_vocab, ids)1from pythainlp import sent_tokenize
2tokenizer = ThaiTokenizer(vocab_file='th.wiki.bpe.op25000.vocab', spm_file='th.wiki.bpe.op25000.model')
3
4txt = "กรุงเทพมหานครเป็นเขตปกครองพิเศษของประเทศไทย มิได้มีสถานะเป็นจังหวัด คำว่า \"กรุงเทพมหานคร\" นั้นยังใช้เรียกองค์กรปกครองส่วนท้องถิ่นของกรุงเทพมหานครอีกด้วย"
5split_sentences = sent_tokenize(txt)
6print(split_sentences)
7"""
8['กรุงเทพมหานครเป็นเขตปกครองพิเศษของประเทศไทย ',
9 'มิได้มีสถานะเป็นจังหวัด ',
10 'คำว่า "กรุงเทพมหานคร" นั้นยังใช้เรียกองค์กรปกครองส่วนท้องถิ่นของกรุงเทพมหานครอีกด้วย']
11"""
12
13split_words = ' '.join(tokenizer.tokenize(' '.join(split_sentences)))
14print(split_words)
15"""
16'▁กรุงเทพมหานคร เป็นเขต ปกครอง พิเศษ ของประเทศไทย ▁มิ ได้มี สถานะเป็น จังหวัด ▁คําว่า ▁" กรุงเทพมหานคร " ▁นั้น...' # continues
17"""BERT-Base, Thai: BERT-Base architecture, Thai-only modelhere.here.SentencePiece and bpe_helper.py from BPEmb are both used to tokenize data. ThaiTokenizer class has been added to BERT's tokenization.py for tokenizing Thai texts.1export BPE_DIR=/path/to/bpe
2export TEXT_DIR=/path/to/text
3export DATA_DIR=/path/to/data
4
5python create_pretraining_data.py \
6 --input_file=$TEXT_DIR/thaiwikitext_sentseg \
7 --output_file=$DATA_DIR/tf_examples.tfrecord \
8 --vocab_file=$BPE_DIR/th.wiki.bpe.op25000.vocab \
9 --max_seq_length=128 \
10 --max_predictions_per_seq=20 \
11 --masked_lm_prob=0.15 \
12 --random_seed=12345 \
13 --dupe_factor=5 \
14 --thai_text=True \
15 --spm_file=$BPE_DIR/th.wiki.bpe.op25000.model1export DATA_DIR=/path/to/data
2export BERT_BASE_DIR=/path/to/bert_base
3
4python run_pretraining.py \
5 --input_file=$DATA_DIR/tf_examples.tfrecord \
6 --output_dir=$BERT_BASE_DIR \
7 --do_train=True \
8 --do_eval=True \
9 --bert_config_file=$BERT_BASE_DIR/bert_config.json \
10 --train_batch_size=32 \
11 --max_seq_length=128 \
12 --max_predictions_per_seq=20 \
13 --num_train_steps=1000000 \
14 --num_warmup_steps=100000 \
15 --learning_rate=1e-4 \
16 --save_checkpoints_steps=200000here.1export BPE_DIR=/path/to/bpe
2export XNLI_DIR=/path/to/xnli
3export OUTPUT_DIR=/path/to/output
4export BERT_BASE_DIR=/path/to/bert_base
5
6python run_classifier.py \
7 --task_name=XNLI \
8 --do_train=true \
9 --do_eval=true \
10 --data_dir=$XNLI_DIR \
11 --vocab_file=$BPE_DIR/th.wiki.bpe.op25000.vocab \
12 --bert_config_file=$BERT_BASE_DIR/bert_config.json \
13 --init_checkpoint=$BERT_BASE_DIR/model.ckpt \
14 --max_seq_length=128 \
15 --train_batch_size=32 \
16 --learning_rate=5e-5 \
17 --num_train_epochs=2.0 \
18 --output_dir=$OUTPUT_DIR \
19 --xnli_language=th \
20 --spm_file=$BPE_DIR/th.wiki.bpe.op25000.model| XNLI Baseline | BERT | ||
| Translate Train | Translate Test | Multilingual Model | Thai-only Model |
| 62.8 | 64.4 | 66.1 | 68.9 |
here and the following script can be run to use the Thai-only model for this task.1export BPE_DIR=/path/to/bpe
2export WONGNAI_DIR=/path/to/wongnai
3export OUTPUT_DIR=/path/to/output
4export BERT_BASE_DIR=/path/to/bert_base
5
6python run_classifier.py \
7 --task_name=wongnai \
8 --do_train=true \
9 --do_predict=true \
10 --data_dir=$WONGNAI_DIR \
11 --vocab_file=$BPE_DIR/th.wiki.bpe.op25000.vocab \
12 --bert_config_file=$BERT_BASE_DIR/bert_config.json \
13 --init_checkpoint=$BERT_BASE_DIR/model.ckpt \
14 --max_seq_length=128 \
15 --train_batch_size=32 \
16 --learning_rate=5e-5 \
17 --num_train_epochs=2.0 \
18 --output_dir=$OUTPUT_DIR \
19 --spm_file=$BPE_DIR/th.wiki.bpe.op25000.model