기본 콘텐츠로 건너뛰기

SentencePiece 설치 및 사용법


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
NameDescription
input파일목록은 쉼표로 구분합니다.
model_prefixoutput model로 prefix. <model_name>.model과 <model_name>.vocab 이 생성됩니다.
vocab_sizevocabulary size, e.g.. 8000, 16000, or 32000
character_coverageModel에서 다루는 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

댓글

이 블로그의 인기 게시물

[Deep Learning-딥러닝] 신경망 구조

뉴런 표현 및 연산 방법 생물학의 신경 세포를 단순화하여 모델링 한것이 뉴런입니다.  뉴런은 신경망의 기본 단위 입니다. 뉴런은 여러 신호를 받아, 하나의 신호를 만들어 전달하는 역할을 합니다. 출력을 내기 전에 활성 함수(activation function)을 통해서 비선형 특성을 가할 수 있습니다. 뉴런 연산 방법은 다음과 같습니다. 두 벡터  가중치 weight와 입력 x의  내적 을 구한 후 모두 합한다. 편향을 더합니다.  편향이 없으면, 추세선은 원점을 꼭 지나야 합니다. 활성 함수를 적용 해 비선형 함수로 만듭니다. 두 벡터의 내적은 다음과 같이 표현할 수 있습니다. 두 벡터의 내적 FC(Fully Connected) Layer Matrix 곱셈 연산 표현 방법 뉴런이 모인 한 단위를 계층(Layer)라고 하며, 이전 계층과 다음 계층의 모든 뉴런이 서로 연결된 계층을 Fully-Connected Layer(Dense Layer)라고 합니다. N개의 입력, M개의 출력이 있는 네트워크 예제입니다. 매트릭스  W 의  w 0 는 (N*1)의 벡터이며, 이런  w 0 를 M개 나열되어 있습니다. 입력  x 는 N개라 행렬로 표현하면 (N*1)로 표현됩니다. 가중치를 transpose하여 (M*N)*(N*1)을 연산하여 출력은 (M*1) 형태가 됩니다. 얕은 신경망 - Shallow Neural Network 구조 얕은 신경망 - Shallow Neural Network 입력, 은닉, 출력 3개의 계층으로 되어 있으며, 은닉 계측과 출력 계층이 Fully Connected 계층인 모델을 얕은 신경망(Shallow Neural Network)라고 합니다. 입력 계층(Input Layer) 아무런 연산 없이 은닉계층으로 값을 전달함. 계층의 크기=Node의 개수=입력 Scalar의 수=입력 Vecto...

[Deep Learning-딥러닝]SRU(Simple Recurrent Unit)

SRU(Simple Recurrent Unit) SRU는 병렬화와 시퀀스 모델링이 가능한 light recurrence한 unit입니다. 기존 RNN Architecture(RNN, LSTM, GRU)는 previous time step에 대한 의존성 때문에 병렬처리가 불가능하여 학습 속도가 느렸습니다. 이런 단점을 SRU는 높은 병렬화 및 시퀀스 모델링 기능을 제공하여 학습시간 단축시켰습니다. SRU는 분류, 질의응답에서 cuDNN-optimized LSTM보다 5~9배 빠른 속도를 보였고, LSTM과 convolutional models보다 좋은 성능을 보였습니다. 특징 SRU의 state연산은 time-dependent이지만, 각 state 차원은 independent입니다. 이것은 hidden dimension과 time steps에서 병렬화 연산하는 CUDA-level optimization으로 병렬 처리 가능합니다. SRU는 convolutions을 더 많은 recurrent 연결로 대체하였습니다(QRNN과 KNN과 같이). 이건 적은 연산으로 모델링을 유지합니다. SRU는 highway connection방법과 deep architecture에서 gradient전파에 맞게 조정된 매개 변수 초기화 체계를 사용하여 deep recurrent models training을 개선합니다. 연산방법 SRU는 forget gate, state, reset gate, hidden state 연산을 수행합니다. Light recurrence (1, 2번 수식) Forget gate: 정보 흐름을 제어 State: 이전 state와 현재 입력을 forget gate에 따라 조정 특징 - 문자열 정보를 위해 input x와 state c를 연산 - 이전 state에 영향을 받음 - 병렬처리를 위해 matrix multiplication 대신 point-wise multiplication 연산 수행 Highway network (3, 4번 수식) Hidden ...