静かなる名辞

pythonとプログラミングのこと


【python】sklearnのfetch_20newsgroupsで文書分類を試す(1)

 fetch_20newsgroupsはUsenetというネットニュースの記事(でいいのかな、良くない気がする)をカテゴリ別に集めたデータセット。sklearnで気楽に使えるので*1、試してみることにする。

 とりあえずこの記事はintroductionとし、使い方とデータの扱い方の説明だけ書いておく。実際の分類は後日やって投稿する。

 参考
sklearn.datasets.fetch_20newsgroups — scikit-learn 0.20.1 documentation

最初にするべきこと

 デフォルトでデータの実体を持っている訳ではない。一回呼んであげるとtarを落としてきてセットアップする。引数は指定しなくて大丈夫(落としたデータを格納するフォルダが~/scikit_learn_dataなんて場所にできるらしいが)。

>>> from sklearn.datasets import fetch_20newsgroups
>>> news20 = fetch_20newsgroups()

 shellで単に呼ぶと、返ったオブジェクトが膨大な文字列として表示される。必ず変数に代入すること。

扱い方

 どんなプロパティがあるのか見てやろう。

>>> dir(news20)
['DESCR', 'data', 'description', 'filenames', 'target', 'target_names']

 もうなんとなく使い方がわかる。色々見てみる。

>>> news20.data[0]
"From: lerxst@wam.umd.edu (where's my thing)\nSubject: WHAT car is this!?\nNntp-Posting-Host: rac3.wam.umd.edu\nOrganization: University of Maryland, College Park\nLines: 15\n\n I was wondering if anyone out there could enlighten me on this car I saw\nthe other day. It was a 2-door sports car, looked to be from the late 60s/\nearly 70s. It was called a Bricklin. The doors were really small. In addition,\nthe front bumper was separate from the rest of the body. This is \nall I know. If anyone can tellme a model name, engine specs, years\nof production, where this car is made, history, or whatever info you\nhave on this funky looking car, please e-mail.\n\nThanks,\n- IL\n   ---- brought to you by your neighborhood Lerxst ----\n\n\n\n\n"
>>> news20.target[:10]
array([ 7,  4,  4,  1, 14, 16, 13,  3,  2,  4])
>>> news20.target_names
['alt.atheism', 'comp.graphics', 'comp.os.ms-windows.misc', 'comp.sys.ibm.pc.hardware', 'comp.sys.mac.hardware', 'comp.windows.x', 'misc.forsale', 'rec.autos', 'rec.motorcycles', 'rec.sport.baseball', 'rec.sport.hockey', 'sci.crypt', 'sci.electronics', 'sci.med', 'sci.space', 'soc.religion.christian', 'talk.politics.guns', 'talk.politics.mideast', 'talk.politics.misc', 'talk.religion.misc']

 こんなもんで良いか。要するにdataが文字列が格納されたリストであり、targetがその正解ラベルで、あとは好きに分類に使ってくれ、ということだろう。

 肝心のdataを見ると、なんかメールアドレスとか入ってるわ、記号とか改行多用してるわで、なかなか萎える。つーか人名とかもたくさん入ってるんだけど、こういうのが原因で変な学習したりしないんだろうか。「この人は○○カテゴリにしか投稿してないから、この人の名前が出てきたら○○カテゴリ!」みたいな。

 まあ、それも含めて上手くやれってことか。

 とりあえずやるべきことはわかったので、今日はここまで。

*1:というかpythonでこれほど気楽に使える文書分類用データセットは他にはあんまりない気がする