Jupyter notebook 사용 기준으로 설치 및 사용법을 설명합니다.
Sentencepiece 특징 및 기능 설명은 다음 사이트에서 참고 바랍니다.
one-sentence-per-line raw corpus file. tokenizer, normalizer 또는 preprocessor를 실행할 필요가 없습니다.Default로, Unicode NFKC로 SentencePiece input을 정규화 합니다.
설치방법
VM환경에 pip library가 설치되어 있어야 하며, 다음 명령어를 수행하면 설치됩니다.pip install sentencepiece
사용법
Sentencepiece library import
setencepiece를 import해야 하며 관례적으로 spm으로 사용합니다.
Train SentencePiece Model from corpuse
botchan.txt 파일을 다음 사이트에서 다운로드 받을 수 있습니다.
--mode_type의 기본은 uni type입니다. --model_type에 bpe를 넣으면 bpe 타입으로 생성됩니다. Train이 완료되면 "m.uni.model"과 "m.bpe.model" 이 생성됩니다. 둘 의 차이점은 다음에 확인할 수 있습니다.
Option
Name | Description |
input | 파일목록은 쉼표로 구분합니다. |
model_prefix | output model로 prefix. <model_name>.model과 <model_name>.vocab 이 생성됩니다. |
vocab_size | vocabulary size, e.g.. 8000, 16000, or 32000 |
character_coverage | Model에서 다루는 character 수로, 기본값은 0.9995(일본어, 중국어와 같이 많은 character를 가지고 있을 경우), 그 외 적은 character set은 1.0 입니다. |
model_type |
unigram (default), bpe, char, or word 중 선택합니다. input sentence가 word type을 사용하면, pretokenize 되어야 합니다.
|
SentencePiece Load
Vocab의 사이즈는 500입니다. Special token으로 unknown token, begin token, end token, padding token을 확인할 수 있습니다.
Sentencepiece Encode
Sentencepiece encode 결고를 보면 uni과 bpe type이 다른걸 확인할 수 있습니다.
See all out token
vocab의 모든 token을 확인할 수 있습니다.
--extra_options flag는 input sequence S BOD/EOS 또는 reverse 삽입 하는데 사용됩니다.
% spm_encode --extra_options=eos (add </s> only)
% spm_encode --extra_options=bos:eos (add <s> and </s>)
% spm_encode --extra_options=reverse:bos:eos (reverse input and add <s> and </s>)
SentencePiece. --output_format=(nbest|sample)_(piecelid) flags로 nbest segmentation와 segmentation sampling을 지원합니다.
% spm_encode --model=<model_file> --output_format=sample_piece --nbest_size=-1 --alpha=0.5 <input > output % spm_encode --model=<model_file> --output_format=nbest_id -- nbest_size=10 <input > output
Decode sentence pieces/ids into raw text
% spm_decode --model=<model_file> --input_format=piece <input > output
% spm_decode --model=<model_file> --input_format=id <input >
output
Use --extra_options flag to decode the text in reverse order.
% spm_decode --extra_options=reverse < input > output
End-to-End Example
% spm_train --input=data/botchan.txt --model_prefix=m --vocab_size=1000
unigram_model_trainer.cc(494) LOG(INFO) Starts training with :
input: "../data/botchan.txt"
... <snip>
unigram_model_trainer.cc(529) LOG(INFO) EM sub_iter=1 size=1100 obj=10.4973 num_tokens=37630 num_tokens/piece=34.2091
trainer_interface.cc(272) LOG(INFO) Saving model: m.model
trainer_interface.cc(281) LOG(INFO) Saving vocabs: m.vocab
% echo "I saw a girl with a telescope." | spm_encode --model=m.model
▁I ▁saw ▁a ▁girl ▁with ▁a ▁ te le s c o pe .
% echo "I saw a girl with a telescope." | spm_encode --model=m.model --output_format=id
9 459 11 939 44 11 4 142 82 8 28 21 132 6
% echo "9 459 11 939 44 11 4 142 82 8 28 21 132 6" | spm_decode --model=m.model --input_format=id
I saw a girl with a telescope.
vocabulary id sequence에서 원본 input sequence로 복구할 수 있습니다.
Export vocabulary list
% spm_export_vocab --model=<model_file> --output=<output file>
<output file>은 vocabulary and emission log 확률 목록을 저장합니다. Vocabulary ID는 파일의 줄 번호에 해당합니다.
Redefine special meta tokens
By default, SentencePiece uses Unknown (<unk>), BOS (<s>) and EOS (</s>) tokens which have the ids of 0, 1, and 2 respectively. We can redefine this mapping in the training phase as follows.
% spm_train --bos_id=0 --eos_id=1 --unk_id=5 --input=... --model_prefix=... --character_coverage=...
When setting -1 id e.g., bos_id=-1, this special token is disabled. Note that the unknow id cannot be disabled. We can define an id for padding (<pad>) as --pad_id=3.
If you want to assign another special tokens, please see Use custom symbols.
Redefine special meta tokens
생략....
Vocabulary restriction
spm_encode 은 --vocabulary와 --vocabulary_threshold option을 사용합 니다.
spm_encode vocabulary에 나타난 심볼만 생성합니다(with at least some frequency).
이 기능의 배경은 subword-nmt 페이지에 설명되어 있습니다.
사용법은 기본적으로 subword-nmt와 동일합니다. L1과 L2가 두 가지 언어 (소스 / 대상 언어)라고 가정하고 공유 spm 모델을 학습하고 각 각에 대한 결과 어휘를 얻습니다.
% cat {train_file}.L1 {train_file}.L2 | shuffle > train
% spm_train --input=train --model_prefix=spm --vocab_size=8000 --character_coverage=0.9995
% spm_encode --model=spm.model --generate_vocabulary < {train_file}.L1 > {vocab_file}.L1
% spm_encode --model=spm.model --generate_vocabulary < {train_file}.L2 > {vocab_file}.L2
spm_train이 corpus의 처음 10M lines을 로드하기 때문에(by default) shuffle command가 사용됩니다.
그런 다음 --vocabulary 옵션으로 train/test corpus을 분할 하십시오.
% spm_encode --model=spm.model --vocabulary={vocab_file}.L1 --vocabulary_threshold=50 < {test_file}.L1 > {test_file}.seg.L1
% spm_encode --model=spm.model --vocabulary={vocab_file}.L2 --vocabulary_threshold=50 < {test_file}.L2 > {test_file}.seg.L2
다음 git에서 소스 다운로드 할 수 있습니다.
https://github.com/ynebula/NLP/blob/master/Data_Preprocessing/Sentencepiece/Sentencepiece.ipynb
댓글
댓글 쓰기