기본 콘텐츠로 건너뛰기

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...

[워드임베딩-Word Embedding]원-핫 인코딩(One-hot encoding)

1. 단어 집합(vocabulary) 및 정수 맵핑 텍스트의 모든 단어의 중복을 배제한 집합을 단어 집합(vocabulary) 이라고 합니다. 그리고 이 단어 집합에 고유한 숫자를 부여하는 정수 인코딩 을 진행 합니다. 이를 다른 말로 맵핑(mapping) 이라고 합니다. 보통 인덱스는 빈도수가 높은 단어들만 사용하기 위해서, 단어의 빈도수를 기준으로 내림차순 정렬한 뒤에 부여합니다. 2. 원-핫 인코딩(One-hot encoding) 컴퓨터는 문자보다는 숫자를 더 잘 처리 할 수 있습니다. 이를 위해 문자를 숫자로 바꿔야 합니다. 원-핫 인코딩(One-hot encoding)은 문자를 숫자로 바꿔주는 방법 중 가장 기본적인 방법 입니다. 원-핫 인코딩은 "범주형 데이터" 또는 "다중 클래스 분류" 문제를 처리할 때 레이블을 표현합니다. 원-핫 인코딩의 크기는 선택(Category or Class)개수이고, 정답은 1로 나머지는 0으로 표시하는 방법입니다.  원-핫 인코딩은 단어 집합의 크기를 벡터의 차원 으로 하고, 표현하고 싶은 단어의 인덱스 즉, 정답에 1의 값을 부여 하고, 다른 인덱스에는 0을 부여 하는 단어의 벡터 표현 방식 입니다. 이렇게 표현된 벡터를 원-핫 벡터(One-hot vector) 라고 합니다. 원-핫 인코딩을 위해서 먼저 해야할 일은 단어 집합을 만드는 일입니다. 원-핫 인코딩을 하기 위해서는 우선 각 선택지에 순차적으로 정수 인덱스를 부여합니다. 원-핫 인코딩 수행 과정 단어 집합 생성 각 단어에 고유한 인덱스를 부여 표현하고 싶은 단어의 인덱스의 위치에 1을 부여하고, 다른 단어의 인덱스의 위치에는 0을 부여 카테고리가 6개이므로 6차원 벡터로 표시 3. 원-핫 인코딩의 희소 표현(Sparse Vector) 희소 표현을 이용해 벡터 전체를 표기하지 않고, 숫자 하나(1의 값의 Index를 가지고 표현)로 표현할 수 있습니다. 4. 비용함수 MSE(M...