LoginSignup
4
5

More than 3 years have passed since last update.

GoogleColab での Janome を使用したテキスト解析と頻出単語の可視化

Last updated at Posted at 2021-03-02

はじめに

  • AI について勉強したい、何かきっかけが欲しいなと本屋でブラブラしていたら出会った『人気ブロガーからあげ先生のとにかく楽しいAI自作教室』
  • 環境準備が不要で、自分で実際に手を動かせるサンプルのサイズ感がよく、まずは日本語テキストの解析からチャレンジする
  • 具体的には前述の書籍の 3 章に基づいて Google Colaboratory 上で青空文庫から取得した文章を Janome で形態素解析して名詞を抽出、 WordCloud で可視化するところまでを実施する

使用したツール類

Google Colaboratory

  • Google が無料で提供しているブラウザベースで機械学習が行えるクラウドサービス
    • ブラウザ上で全て完結して環境を気にせず簡易に実行できるのが実に良い
    • この環境上で Python のコーディングや実行、可視化が行える
  • 内容としては Colab がホストする Jupyter ノートブック
  • GPU も使用可
  • ただし、使用時間に制限があり 12 時間立つと環境がリセットされる
    • 自分の Google Drive をマウントしてその上で作業すれば wget したものなどは保持される
    • 最初はマウントすることを知らず wget したものなどが揮発してしまい難儀していた
  • マウントに関しては下記がとても参考になった
  • Google Colaboratory の詳細や操作方法に関しては下記がとても参考になった

Janome

  • Python で使用可能な形態素解析ライブラリの一つ
  • 日本語テキストを解析して品詞ごとに分かち書きできる (単語を区切って表示する)

WordCloud

  • 文章内の単語を検出頻度に応じて大小をつけて表示する Python のライブラリ

やってみた (以降は全て Google Colaboratory 上で実施した)

事前準備1 (テキストファイルのダウンロード)

マウントした作業用ディレクトリに移動し、青空文庫から『吾輩は猫である』を取得して解凍する

%cd /content/drive/MyDrive/textData/
!wget https://github.com/aozorabunko/aozorabunko/raw/master/cards/000148/files/789_ruby_5639.zip
!unzip 789_ruby_5639.zip
!ls
789_ruby_5639.zip  wagahaiwa_nekodearu.txt

事前準備2 (テキストファイルの読み込み)

『吾輩は猫である』のテキストファイルを text_list へ全行読み込む

text_list = []
with open('wagahaiwa_nekodearu.txt', encoding='shift_jis') as f:
  text_list = f.readlines()

Janome のセットアップ

インストールと version の確認

!pip install janome
!janome --version
janome 0.4.1

Janome での形態素解析の実施

『吾輩は猫である』のテキストを格納した text_list を形態素解析し、名詞のみを抽出して分かち書きを行う

from janome.tokenizer import Tokenizer

t = Tokenizer()
words = []
for text in text_list:
  tokens = t.tokenize(text)
  for token in tokens:
    pos = token.part_of_speech.split(',')[0]
    if pos == '名詞':
      words.append(token.surface)

text = ' '.join(words)

解析結果の中身の一部を確認

『吾輩』という単語がみえ、正しく名詞を抽出できている様子

print(text[1000:1100])
路 邸 しき 先 善 い うち 腹 さ 雨 始末 一刻 猶予 仕方 そう 方 方 今 時 家 内 の ここ 吾輩 彼 書生 以外 人間 機会 遭遇 ぐう の 一 の さん これ 前 書生 乱暴 方 吾

WordCloud による可視化

WordCloud と日本語フォントのインストール

!apt -y install fonts-ipafont-gothic
!pip install wordcloud

及び、 Matplotlib のインポートし

from wordcloud import WordCloud
import matplotlib.pyplot as plt

実行

fpath = 'usr/share/fonts/opentype/ipafont-gothic/ipagp.ttf'
wordcloud = WordCloud(background_color="white", font_path=fpath, width=900, height=500).generate(text)
plt.figure(figsize=(15,12))
plt.imshow(wordcloud)
plt.axis("off")
plt.show()

実行結果

  • 『それ』『ところ』『これ』『そう』などなど一般的な文章でよく使用される単語が大きく表示されている
  • 『猫』という単語が最頻出で最も大きく描画されると想定していた (読んだことがないのだけれど) Unknown.png

フィルタの追加と再実行

  • 『吾輩は猫である』特有の頻出単語を検知したいので先述した処理に不要な単語を除外する remove_stopwords メソッドの追加とテキストを読み込むごとに実行するように改修した
  • 再度『吾輩は猫である』のテキストファイルを text_list へ全行読み込む
text_list = []
with open('wagahaiwa_nekodearu.txt', encoding='shift_jis') as f:
  text_list = f.readlines()

不要な単語を除外する remove_stopwords メソッドの定義

import re
def remove_stopwords(text):
  text = re.sub(r'それ', "", text)
  text = re.sub(r'ところ', "", text)
  text = re.sub(r'これ', "", text)
  text = re.sub(r'そう', "", text)
  text = re.sub(r'さん', "", text)
  text = re.sub(r'あれ', "", text)
  text = re.sub(r'そこ', "", text)
  text = re.sub(r'ほか', "", text)
  text = re.sub(r'どこ', "", text)
  text = re.sub(r'よう', "", text)
  text = re.sub(r'もの', "", text)
  text = re.sub(r'うち', "", text)
  text = re.sub(r'ため', "", text)
  text = re.sub(r'いや', "", text)
  text = re.sub(r'こっち', "", text)
  text = re.sub(r'ここ', "", text)
  text.strip()
  return text

text_list から不要な単語を除外した結果を new_text_list に再度格納する

new_text_list = []
for text in text_list:
  text = remove_stopwords(text)
  new_text_list.append(text)

『吾輩は猫である』のテキストから不要な単語を除外して改めて格納した new_text_list を形態素解析し、名詞のみを抽出して分かち書きを行う

from janome.tokenizer import Tokenizer

t = Tokenizer()
words = []
for text in new_text_list:
  tokens = t.tokenize(text)
  for token in tokens:
    pos = token.part_of_speech.split(',')[0]
    if pos == '名詞':
      words.append(token.surface)

text = ' '.join(words)

WordCloud の実行

fpath = 'usr/share/fonts/opentype/ipafont-gothic/ipagp.ttf'
wordcloud = WordCloud(background_color="white", font_path=fpath, width=900, height=500).generate(text)
plt.figure(figsize=(15,12))
plt.imshow(wordcloud)
plt.axis("off")
plt.show()

再実行結果

  • 『主人』が最頻出の名詞で次点が『吾輩』となった
  • 結果から想像するに、主役が『主人』で『吾輩』と適宜絡みがあり『細君』『傍点』『迷亭』『先生』『寒月』などが関わっていく物語だと思われる

Unknown-3.png

おわりに

まずはこういったツール類を使用して機械学習がどういったものなのか掴んでいきたい

参考 書籍/URL:

人気ブロガーからあげ先生のとにかく楽しいAI自作教室

4
5
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
4
5