Tokenizerを触ってみた

まずはパッケージをインストール

! pip install transformers fugashi ipadic

東北大学のBERTモデルを利用

from transformers import AutoTokenizer, AutoModelForMaskedLM

tokenizer = AutoTokenizer.from_pretrained("cl-tohoku/bert-base-japanese-whole-word-masking")

トークナイズしてみる

text_1 = '最近猛暑日が続いてます。'
text_2 = '毎朝プロテイン、マグネシウム、ビタミンを飲んでます。'

text_list = [text_1,text_2]

for text in text_list:
  print(tokenizer.tokenize(text))


['最近', '猛', '##暑', '日', 'が', '続い', 'て', 'ます', '。']
['毎', '##朝', 'プロテ', '##イン', '、', 'マグネシウム', '、', 'ビタミン', 'を', '飲ん', 'で', 'ます', '。']

「猛暑」「毎朝」「プロテイン」などは、サブワードに分割されている。

for text in text_list:
  encode = tokenizer.encode(text)
  print(encode)
  print(tokenizer.convert_ids_to_tokens(encode))


[2, 5233, 6336, 30835, 32, 14, 1822, 16, 2610, 8, 3]
['[CLS]', '最近', '猛', '##暑', '日', 'が', '続い', 'て', 'ます', '。', '[SEP]']
[2, 979, 28956, 6723, 217, 6, 22916, 6, 12218, 11, 14716, 12, 2610, 8, 3]
['[CLS]', '毎', '##朝', 'プロテ', '##イン', '、', 'マグネシウム', '、', 'ビタミン', 'を', '飲ん', 'で', 'ます', '。', '[SEP]']

[CLS]、[SEP]は特殊トークン。

for text in text_list:
  encode = tokenizer(text,max_length=15,padding='max_length',truncation=True)
  print(encode)
  print(tokenizer.convert_ids_to_tokens(encode['input_ids']))


{'input_ids': [2, 5233, 6336, 30835, 32, 14, 1822, 16, 2610, 8, 3, 0, 0, 0, 0], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0]}
['[CLS]', '最近', '猛', '##暑', '日', 'が', '続い', 'て', 'ます', '。', '[SEP]', '[PAD]', '[PAD]', '[PAD]', '[PAD]']
{'input_ids': [2, 979, 28956, 6723, 217, 6, 22916, 6, 12218, 11, 14716, 12, 2610, 8, 3], 'token_type_ids': [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], 'attention_mask': [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]}
['[CLS]', '毎', '##朝', 'プロテ', '##イン', '、', 'マグネシウム', '、', 'ビタミン', 'を', '飲ん', 'で', 'ます', '。', '[SEP]']

系列の長さを15(max_length)に設定し、超過分は切り捨て(truncation=True)。

第一文には特殊トークン[PAD]で系列長が15になるように調整されていることがわかる。

ikunobu
NLP