0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

自然言語処理TF-IDFの応用Part4(ワードクラウドの作成)

Posted at

前回のおさらい

前回の記事では、各企業の経営方針の単語からTF-IDF値を求めてリスト化しました。例えば、ソニーグループ株式会社では、『ソニー』・『ip』・『制作』・『エンタテイメント』・『リアルタイム』といった単語のTF-IDF値が上位に並びました。これらの単語をワードクラウドとして表現するのが、今回の目標です!

index値の利用

前回の記事で触れた、df.query内の会社名を指定することで、index値を利用できます。

index値
index = df.query('会社名=="トヨタ自動車株式会社"').index[0]
print(index)

# 結果 654

index = df.query('会社名=="ソニーグループ株式会社"').index[0]
print(index)

# 結果 715

index = df.query('会社名=="株式会社三菱UFJフィナンシャル・グループ"').index[0]
print(index)

# 結果 717

ワードクラウドで可視化

ライブラリのインストール
!pip install -q japanize-matplotlib
!apt-get -yq install fonts-ipafont-gothic
!ls /usr/share/fonts/opentype/ipafont-gothic

ワードクラウドでの表示は下のコードで実現できます。
事前に日本語文字フォント(NotoSansJP-Bold.ttf、NotoSansJP-ExtraLight.ttf、NotoSansJP-Regular.ttf)をGoogleFontから入手します。
そして、content下に置きましょう。

ワードクラウド表示する関数
from wordcloud import WordCloud
import japanize_matplotlib
import matplotlib.pyplot as plt
from PIL import Image
from tqdm import tqdm_notebook as tqdm

# --- vecs_dic 作成 ---
def vecs_dic(feature_names, values):
    vecs_dic = []
    for vec in tqdm(values):
        temp_dic = {}
        for i in range(len(vec)):
            try:
                freq = float(vec[i])
            except:
                freq = 0.0
            temp_dic[feature_names[i]] = freq
        vecs_dic.append(temp_dic)
    return vecs_dic

# --- WordCloud 描画 ---
def create_wordcloud(vecs_dic, index, font_path=None):
    font_path = '/content/NotoSansJP-Regular.ttf'
    #トヨタ自動車 colormap="PuBu" font = NotoSansJP-Bold.ttf
    #ソニーグループ colormap="RdPu" font = NotoSansJP-ExtraLight.ttf
    #三菱UFJフィナンシャルグループ colormap="Paired" font = NotoSansJP-Regular.ttf
    fig = plt.figure(figsize=(15, 15))
    wc = WordCloud(
        background_color='white',
        width=2500,
        height=1500,
        font_path=font_path,  # 日本語フォント指定
        max_words=50,
        colormap="Paired",
    )
    wc.generate_from_frequencies(vecs_dic[index])
    plt.imshow(wc, interpolation='bilinear')
    plt.axis("off")
    plt.show()

画像を生成します。

ワードクラウドの表示
# --- 処理実行 ---
vecs = vecs_dic(feature_names, values)
create_wordcloud(vecs, index)  

トヨタ自動車のワードクラウド

トヨタ.png

ソニーグループのワードクラウド

ソニー.png

三菱UFJグループのワードクラウド

三菱UFJ.png

APIの利用、DFを用いたデータ取得・加工、形態素解析MeCab・辞書の利用、そしてワードクラウドの作成と盛りだくさんの内容でした!
TF-IDFは自然言語処理では古典的な手法ですが、効力を体感できたのかと思います。
Part1からPart4まで記事を読んでくださり、本当にありがとうございます!

初回の記事はこちら!

自然言語処理TF-IDFの応用Part1(API活用編)

参考資料

@osn_Lofiさんの資料がとても参考になりました。ありがとうございます!
【自然言語処理】【Python】TF-IDFを使って文書の特徴をつかもう

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?