BOW(Bag Of Words) 文章のベクトル化



ソフトウェア

公開日:2021/9/21          

前提知識
python


■BOW(Bag Of Words)とは
BOW(Bag Of Words)とは文章をベクトル化する手法の一つで、単語の出現回数をカウントする手法です。"バッグに詰め込む"という意味合いでこの呼び名がついております。

■pythonによる実装例
MeCabというライブラリを使用します。ライブラリのインストール方法はこちら

import MeCab
import numpy as np

text = ['今日は月曜日である。' , '明日は火曜日である。']

tagger = MeCab.Tagger("-Owakati")
data = [tagger.parse(n) for n in text]     # 分かち書きに変換

word2id = {}

for line in data:     # 1行ずつ取得
    for word in line.split(' '):     # 1単語ずつ取得
        if word not in word2id and word !='\n':     # 辞書にない単語を取得
            id = len(word2id)
            word2id[word] = id     # 辞書作成

bow = np.zeros((2, len(word2id)))

for i, toks in enumerate(data):
    for tok in toks.split(' '):
        if tok != '\n':
            bow[i, word2id[tok]] += 1    # Bow作成

print(bow)

    → [[1. 1. 1. 1. 1. 1. 1. 0. 0.]
        [0. 1. 0. 1. 1. 1. 1. 1. 1.]]












サブチャンネルあります。⇒ 何かのお役に立てればと

関連記事一覧



ソフトウェア