1
1

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.

tf.kerasのTextVectorizationとsentencepiece組み合わせ

Last updated at Posted at 2020-05-18

1.概要

tensorflow2.2.0が利用可能を眺めている最中にTextVectorizationを発見。
当該機能を紹介されている方のブログもあった。

TextVectorizationは若干の制約はありますが、TokenizationからID変換までを一気にやってくれるという、ものぐさな人にピッタリの便利Layerになっています。

とのことで、手軽にモデル作成するならhuggingface/transformersが良いと思っているけれど、この機能もとても便利そう。
TextVectorizationとsentencepieceを組み合わせれば、
・日本語の処理のためのtokenization
・単語⇔ID変換
・入力用長さ揃え
・tf-idfやone-hotに切り替えたりもなど
を後ろでやってもらい、いきなり層が作れるのでは?と思い試してみることに。
textCNNやったりも。今回はembedding+conv1Dと、TF-IDF densely-connected の2つを作成。※TextVectorizationとsentencepieceの組み合わせは上記のブログでも示唆されていた。

TextVectorizationの引数概要

tf.keras.layers.experimental.preprocessing.TextVectorization(
    max_tokens=None, 
    standardize=LOWER_AND_STRIP_PUNCTUATION,
    split=SPLIT_ON_WHITESPACE, 
    ngrams=None, 
    output_mode=INT,
    output_sequence_length=None, 
    pad_to_max_tokens=True, 
    **kwargs
)

「split=~~」に自分が切りたいように単語分割する関数をtf.stringを入出力としてかませれば実行してくれる。(デフォルトは英語なのでスペースで区切る=SPLIT_ON_WHITESPACE)
他にもngramも作ってくれたり,output_modeで考えそうな出し方(one-hot,tf-idfなど)も選択可能になっている。

2.実行環境

3.工夫点

以下、公式のcolabファイルをもとに、いくつか変更した部分を説明

工夫点1:tensorflowのバージョン

普通にtensorflowをインストールすると、最新の2.3.~がインストールされてしまい、後述のSentencepieceTokenizerがエラーになってしまう。

!pip install tensorflow==2.2.0

工夫点2:sentencepieceの適用部分

!pip install tf_sentencepiece
!pip install sentencepiece
import sentencepiece as spm
spm.SentencePieceTrainer.train('--model_prefix=m2 --input=abst.txt --vocab_size=2000 --normalization_rule_name=nfkc_cf')

でmodelファイルを作って、tensorflow_textでモデルを読み込む際に、sentencepieceではutf8ですべてエンコードされているので、普通にそのまま model='モデル名' で読み込めず、gfile.GFile('モデル名','rb').read()と読み込む必要があった点。

mod = gfile.GFile('m2.model', 'rb').read()
s2 = text.SentencepieceTokenizer(model=mod,out_type=tf.string)

def segment_by_spm(input_data):
    text = s2.tokenize(input_data)
    return text

その他

  • 最初のテキスト準備の時点でスペース区切りで分かち書きされたファイルを準備すれば上のような工夫はいらなくなるけれど、普通の文書をそのまま突っ込めるのは良いと思う。
  • sentencepieceの他にmecabなどでも実行できるように加えたい。
  • tensorflow_text にはいろんなtokenizationの関数があったので、これも使ってみたい。
1
1
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
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?