Sentence Piece
데이터¶
import datasets
dataset_dir = 'data/korean-english'
한영데이터 = datasets.load_dataset('csv', data_files={
'train': f'{dataset_dir}/train.csv',
'validation': f'{dataset_dir}/validation.csv',
'test': f'{dataset_dir}/test.csv'
})
for split in 한영데이터:
print(f"{split:<12}: {len(한영데이터[split]):,}")train : 833,321
validation : 104,165
test : 104,165
# features
print(한영데이터['train'].features){'ko': Value('string'), 'en': Value('string'), 'source': Value('int64')}
import pandas as pd
pd.DataFrame(한영데이터['train'].shuffle(seed=0).take(5))Loading...
분류 = pd.Series(한영데이터['train']['source'])
(pd.DataFrame({
'도수': 분류.value_counts(),
'비율': 분류.value_counts(normalize=True)})
.style.format({'도수': '{:,}', '비율': '{:.2%}'}))Loading...
# 가장 도수가 작은 분류의 도수로 각 분류의 샘플 수를 맞춤
min_count = 분류.value_counts().min()
balanced_samples = []
for source in 분류.unique():
source_samples = 한영데이터['train'].filter(lambda x: x['source'] == source)
balanced_samples.append(source_samples.shuffle(seed=0).take(min_count))
sample_dataset = datasets.concatenate_datasets(balanced_samples)분류 = pd.Series(sample_dataset['source'])
(pd.DataFrame({
'도수': 분류.value_counts(),
'비율': 분류.value_counts(normalize=True)})
.sort_index()
.style.format({'도수': '{:,}', '비율': '{:.2%}'}))Loading...
sentence piece¶
ko_dataset = sample_dataset.select_columns(['ko'])
with open('ko_sents.txt', 'w', encoding='utf-8') as f:
for sent in ko_dataset['ko']:
f.write(sent + '\n')with open('ko_sents.txt', 'r', encoding='utf-8') as f:
for _ in range(5):
print(f.readline().strip())우리나라 보호관찰제도는 1988년 구 보호관찰법(현재 보호관찰 등에 관한 법률)이 제정됨에 따라 명실상부한 보호관찰 도입국이 되었다.
형사 사건에서는 예컨대 구속된 피고인이 석방된다는 조건의 성공 보수 약정은 공서 양속에 어긋나는 것으로 보아야 한다는 것이다.
측면은 각 상품의 특성과 주제, 수요자의 건강 수준에 맞추어 활용이 가능하며, 보다 다양한 방법의 개발이 필요하다.
정보성은 구전 형성에 영향을 미치지 않는 것으로 나타나 가설 9는 기각되었다.
분석 대상이 884편에 이르러 이 논문에서는 양적인 측면에 집중한 한계가 있다.
import sentencepiece as spm
spm.SentencePieceTrainer.Train(
input='ko_sents.txt',
model_prefix='ko_spm_5k',
vocab_size=5000,
)Output
sentencepiece_trainer.cc(78) LOG(INFO) Starts training with :
trainer_spec {
input: ko_sents.txt
input_format:
model_prefix: ko_spm_5k
model_type: UNIGRAM
vocab_size: 5000
self_test_sample_size: 0
character_coverage: 0.9995
input_sentence_size: 0
shuffle_input_sentence: 1
seed_sentencepiece_size: 1000000
shrinking_factor: 0.75
max_sentence_length: 4192
num_threads: 16
num_sub_iterations: 2
max_sentencepiece_length: 16
split_by_unicode_script: 1
split_by_number: 1
split_by_whitespace: 1
split_digits: 0
pretokenization_delimiter:
treat_whitespace_as_suffix: 0
allow_whitespace_only_pieces: 0
required_chars:
byte_fallback: 0
vocabulary_output_piece_score: 1
train_extremely_large_corpus: 0
seed_sentencepieces_file:
hard_vocab_limit: 1
use_all_vocab: 0
unk_id: 0
bos_id: 1
eos_id: 2
pad_id: -1
unk_piece: <unk>
bos_piece: <s>
eos_piece: </s>
pad_piece: <pad>
unk_surface: ⁇
enable_differential_privacy: 0
differential_privacy_noise_level: 0
differential_privacy_clipping_threshold: 0
}
normalizer_spec {
name: nmt_nfkc
add_dummy_prefix: 1
remove_extra_whitespaces: 1
escape_whitespaces: 1
normalization_rule_tsv:
}
denormalizer_spec {}
trainer_interface.cc(353) LOG(INFO) SentenceIterator is not specified. Using MultiFileSentenceIterator.
trainer_interface.cc(185) LOG(INFO) Loading corpus: ko_sents.txt
trainer_interface.cc(380) LOG(WARNING) Found too long line (6005 > 4192).
trainer_interface.cc(382) LOG(WARNING) Too long lines are skipped in the training.
trainer_interface.cc(383) LOG(WARNING) The maximum length can be changed with --max_sentence_length=<size> flag.
trainer_interface.cc(409) LOG(INFO) Loaded all 231749 sentences
trainer_interface.cc(416) LOG(INFO) Skipped 3 too long sentences.
trainer_interface.cc(425) LOG(INFO) Adding meta_piece: <unk>
trainer_interface.cc(425) LOG(INFO) Adding meta_piece: <s>
trainer_interface.cc(425) LOG(INFO) Adding meta_piece: </s>
trainer_interface.cc(430) LOG(INFO) Normalizing sentences...
trainer_interface.cc(539) LOG(INFO) all chars count=20016638
trainer_interface.cc(550) LOG(INFO) Done: 99.9501% characters are covered.
trainer_interface.cc(560) LOG(INFO) Alphabet size=1344
trainer_interface.cc(561) LOG(INFO) Final character coverage=0.999501
trainer_interface.cc(592) LOG(INFO) Done! preprocessed 231749 sentences.
unigram_model_trainer.cc(265) LOG(INFO) Making suffix array...
unigram_model_trainer.cc(269) LOG(INFO) Extracting frequent sub strings... node_num=7450884
unigram_model_trainer.cc(312) LOG(INFO) Initialized 482201 seed sentencepieces
trainer_interface.cc(598) LOG(INFO) Tokenizing input sentences with whitespace: 231749
trainer_interface.cc(609) LOG(INFO) Done! 741944
unigram_model_trainer.cc(602) LOG(INFO) Using 741944 sentences for EM training
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=251118 obj=14.3545 num_tokens=1733515 num_tokens/piece=6.90319
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=220315 obj=13.1192 num_tokens=1739048 num_tokens/piece=7.89346
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=165197 obj=13.0953 num_tokens=1795701 num_tokens/piece=10.8701
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=164975 obj=13.0629 num_tokens=1796508 num_tokens/piece=10.8896
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=123729 obj=13.1624 num_tokens=1865868 num_tokens/piece=15.0803
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=123724 obj=13.1368 num_tokens=1867832 num_tokens/piece=15.0968
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=92793 obj=13.2631 num_tokens=1938368 num_tokens/piece=20.8892
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=92793 obj=13.2332 num_tokens=1938406 num_tokens/piece=20.8896
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=69594 obj=13.3874 num_tokens=2011926 num_tokens/piece=28.9095
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=69594 obj=13.3544 num_tokens=2011894 num_tokens/piece=28.909
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=52195 obj=13.5365 num_tokens=2087817 num_tokens/piece=40.0003
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=52195 obj=13.4994 num_tokens=2087796 num_tokens/piece=39.9999
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=39146 obj=13.7075 num_tokens=2167514 num_tokens/piece=55.37
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=39146 obj=13.6644 num_tokens=2167507 num_tokens/piece=55.3698
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=29359 obj=13.9074 num_tokens=2253714 num_tokens/piece=76.764
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=29359 obj=13.8566 num_tokens=2253688 num_tokens/piece=76.7631
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=22019 obj=14.1296 num_tokens=2343550 num_tokens/piece=106.433
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=22019 obj=14.0717 num_tokens=2343547 num_tokens/piece=106.433
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=16514 obj=14.3858 num_tokens=2440876 num_tokens/piece=147.806
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=16514 obj=14.3172 num_tokens=2440861 num_tokens/piece=147.806
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=12385 obj=14.6778 num_tokens=2547884 num_tokens/piece=205.723
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=12385 obj=14.5977 num_tokens=2547884 num_tokens/piece=205.723
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=9288 obj=15.0103 num_tokens=2659204 num_tokens/piece=286.305
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=9288 obj=14.9092 num_tokens=2659202 num_tokens/piece=286.305
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=6966 obj=15.3828 num_tokens=2780468 num_tokens/piece=399.148
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=6966 obj=15.2702 num_tokens=2780467 num_tokens/piece=399.148
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=0 size=5500 obj=15.7125 num_tokens=2887026 num_tokens/piece=524.914
unigram_model_trainer.cc(618) LOG(INFO) EM sub_iter=1 size=5500 obj=15.6157 num_tokens=2887023 num_tokens/piece=524.913
trainer_interface.cc(687) LOG(INFO) Saving model: ko_spm_5k.model
trainer_interface.cc(699) LOG(INFO) Saving vocabs: ko_spm_5k.vocab
한국어_형태분석기 = spm.SentencePieceProcessor()
assert 한국어_형태분석기.load('ko_spm.model'), "모델 로드 실패"
예문 = '대통령께서 입장하십니다.'
형태소목록 = 한국어_형태분석기.encode(예문, out_type=str)
정수시퀀스 = 한국어_형태분석기.encode(예문, out_type=int)
pd.DataFrame([{정수: 형태소 for 형태소, 정수 in zip(형태소목록, 정수시퀀스)}])Loading...
한국어문장 = 한영데이터.select_columns('ko')
한국어형태분석문장 = 한국어문장.map(
lambda x: {'tokens': 한국어_형태분석기.encode(x['ko'], out_type=str)})
한국어형태분석문장.save_to_disk('ko_tokens')한국어형태분석문장 = datasets.load_from_disk('ko_tokens')
print(한국어형태분석문장.keys())
pd.DataFrame(한국어형태분석문장['train'].shuffle(seed=5).take(5))dict_keys(['train', 'validation', 'test'])
Loading...