深層学習とその他

機械学習したいマン

chainerで文書分類する その1

アドベントカレンダー18日目です。
今日はchainerのexampleにあるtext_classificationを使って文書分類していきたいと思います。
adventar.org

examplesのtext_classificationを動かす

このソースコードを動かします。
chainer/examples/text_classification at master · chainer/chainer · GitHub

あらかじめよく用いられるネットワークである、LSTMやCNNが含まれていて、使いやすいようにデータセットも簡単にダウンロードできるようになっています。
train_text_classifier.pyを動かすことで学習ができます。

python train_text_classifier.py -g 0 --dataset dbpedia


学習に使うモデルを変える

これらのモデルが含まれています。

・LSTM
・CNN + MLP
・BoW + MLP
・Character-based variant models of those

https://github.com/chainer/chainer/tree/master/examples/text_classification

モデルを切り替える際は、以下のように引数を渡します。

python train_text_classifier.py -g 0  --model bow


含まれているデータセット

データセットは以下のものが含まれています。

・DBPedia Ontology dataset (dbpedia): Predict its ontology class from the abstract of an Wikipedia article.
IMDB Movie Review Dataset (imdb.binary, imdb.fine): Predict its sentiment from a review about a movie. .binary's classes are positive/negative. .fine's classes are ratings [0-1]/[2-3]/[7-8]/[9-10].
・TREC Question Classification (TREC): Predict the type of its answer from a factoid question.
Stanford Sentiment Treebank (stsa.binary, stsa.fine): Predict its sentiment from a review about a movie. .binary's classes are positive/negative. .fine's classes are [negative]/[somewhat negative]/[neutral]/[somewhat positive]/[positive].
・Customer Review Datasets (custrev): Predict its sentiment (positive/negative) from a review about a product.
・MPQA Opinion Corpus (mpqa): Predict its opinion polarity from a phrase.
・Scale Movie Review Dataset (rt-polarity): Predict its sentiment (positive/negative) from a review about a movie.
・Subjectivity datasets (subj): Predict subjectivity (subjective/objective) from a sentnece about a movie.

https://github.com/chainer/chainer/tree/master/examples/text_classification

学習の際に使うデータセットを切り替える場合は、
'dbpedia', 'imdb.binary', 'imdb.fine','TREC', 'stsa.binary', 'stsa.fine','custrev', 'mpqa', 'rt-polarity', 'subj'のどれかを引数として渡すことで切り替えることができます。

python train_text_classifier.py -g 0 --dataset subj


実際に動かしてみる

今回もcolaboratoryで動かしてみました。
ただ動かすだけなら、以下のコマンドだけで十分です。

!curl https://colab.chainer.org/install | sh -
!git clone https://github.com/chainer/chainer.git
cd chainer/examples/text_classification/
python train_text_classifier.py -g 0

今回はデータを少し確認したかったので、colaboratoryに学習部分のコードを移しました。
自分のデータに変えて分類するのも簡単そうです。


まとめ

文書分類を簡単にするだけならtext_classificationをいじるのが楽そうです。