1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

「吾輩は猫である」SentencePiece on Colab

Last updated at Posted at 2019-11-08

吾輩は猫である SentencePiece

今更ですが、Colabで日本語SentencePieceをやるサンプルが見当たらないので、作ってみました。手元にPython環境がなくても気軽にColabで試せます。SentencePiece初心者に役に立てば幸いです。

自然言語処理において、文章を形態素解析したり、トークン化したりする作業が欠かせない。
ここでは夏目漱石の「吾輩は猫である」をSentencePieceでトークン化してみましょう。

インストール

pip install sentencepiece

データダウンロード

「吾輩は猫である」のテキストデータをダウンロード

wget https://raw.githubusercontent.com/google/sentencepiece/master/data/wagahaiwa_nekodearu.txt

テキストデータはこのような内容になっているはずです。

吾輩は猫である
夏目漱石
【テキスト中に現れる記号について】
《》:ルビ
(例)吾輩《わがはい》は猫である
......
入力:柴田卓治
校正:渡部峰子(一)、おのしげひこ(二、五)、田尻幹二(三)、高橋真也(四、七、八、十、十一)、しず(六)、瀬戸さえ子(九)
1999年9月17日公開
2015年2月3日修正
青空文庫作成ファイル:
このファイルは、インターネットの図書館、青空文庫(http://www.aozora.gr.jp/)で作られました。入力、校正、制作にあたったのは、ボランティアの皆さんです。

SentencePiece モデルの学習

トークン化のやり方を覚えさせるために、「吾輩は猫である」のテキストを与えて、
SentencePieceに学習させます。


import sentencepiece as spm

# Train sentencepiece model. Params taken from https://github.com/google/sentencepiece/blob/d4dd947fe71c4fa4ee24ad8297beee32887d8828/src/unigram_model_trainer_test.cc
spm.SentencePieceTrainer.train('--input=wagahaiwa_nekodearu.txt --model_prefix=wagahaiwa_nekodearu --vocab_size=8000 '
  '--normalization_rule_name=identity --model_type=unigram  --max_sentence_length=2048')

# makes segmenter instance and loads the model file
sp = spm.SentencePieceProcessor()
sp.load('wagahaiwa_nekodearu.model')

トークン化の実施

下に定義する text をトークン化すると、 pieces に分解されることを確認しましょう。
また、IDも取得できます。

その後、piecesまたはIDから元の文章を正しく復元 (decode) できることを確認します。

text = (
    "吾輩《わがはい》は猫である。"
    "名前はまだ無い。"
    "どこで生れたかとんと見当《けんとう》がつかぬ。"
    )
pieces = [
          '', '吾輩', '', 'わが', 'はい', '', '', '', 'である', '',  
          '名前', 'はまだ', '無い', '', 
          'どこ', '', '', 'れた', '', 'とん', '', 
          '見当', '', 'けん', 'とう', '', '', 'つか', '', '']
ids = [135, 449, 4, 2388, 143, 3, 16, 184, 35, 5, 679, 1950, 2578, 5, 281, 18, 
       157, 1020, 17, 424, 14, 2401, 4, 302, 236, 3, 13, 277, 152, 5]  

# encode
assert sp.encode_as_pieces(text) == pieces
assert sp.encode_as_ids(text) == ids

# decode
assert sp.decode_pieces(pieces) == sp.decode_ids(ids) == text     

まとめ

SentencePieceで簡単に「吾輩は猫である」のテキストをトークンに分解できました。また、バラバラに分解されたピースを使って、元の文章を再構築できました。Colabノートブックを公開しているので、実際に動かしながら動作を確認するとより理解が深まります。

1
3
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?