共起ネットワークの作成
この例では、bag-of-words モデルを使用して共起ネットワークを作成する方法を示します。
文書のコーパスが与えられた場合、共起ネットワークは無向グラフになります。ノードはボキャブラリ内の一意の単語に対応し、エッジは文書内で共起する単語の頻度に対応します。共起ネットワークを使用して、文書のコーパス内における単語間の関係に関する情報を可視化および抽出します。たとえば、共起ネットワークを使用して、指定した単語と一緒によく出現する単語を検出することができます。
テキスト データのインポート
readtable
を使用して、ファイル weekendUpdates.xlsx
内のテキスト データを抽出します。ファイル weekendUpdates.xlsx
には、ハッシュタグ "#weekend"
と "#vacation"
を含むステータス更新が含まれています。関数 readtable
を使用してデータを読み取り、TextData
列からテキスト データを抽出します。
filename = "weekendUpdates.xlsx"; tbl = readtable(filename,'TextType','string'); textData = tbl.TextData;
最初のいくつかの観測値を表示します。
textData(1:5)
ans = 5x1 string
"Happy anniversary! ❤ Next stop: Paris! ✈ #vacation"
"Haha, BBQ on the beach, engage smug mode! ❤ #vacation"
"getting ready for Saturday night #yum #weekend "
"Say it with me - I NEED A #VACATION!!! ☹"
" Chilling at home for the first time in ages…This is the life! #weekend"
テキスト データの前処理
テキストをトークン化し、それを小文字に変換し、ストップ ワードを削除します。
documents = tokenizedDocument(textData); documents = lower(documents); documents = removeStopWords(documents);
bag-of-words モデルを使用して単語カウントの行列を作成します。
bag = bagOfWords(documents); counts = bag.Counts;
単語の共起を計算するには、単語カウント行列をその転置で乗算します。
cooccurrence = counts.'*counts;
関数 graph
を使用して共起行列をネットワークに変換します。
G = graph(cooccurrence,bag.Vocabulary,'omitselfloops');
関数 plot
を使用してネットワークを可視化します。ラインの太さをエッジの重みの倍数に設定します。
LWidths = 5*G.Edges.Weight/max(G.Edges.Weight); plot(G,'LineWidth',LWidths) title("Co-occurrence Network")
関数 neighbors
を使用して、"great" という単語の近傍を見つけます。
word = "great"
word = "great"
idx = find(bag.Vocabulary == word); nbrs = neighbors(G,idx); bag.Vocabulary(nbrs)'
ans = 18x1 string
"next"
"#vacation"
""
"#weekend"
"☹"
"excited"
"flight"
"delayed"
"stuck"
"airport"
"way"
"spend"
""
"lovely"
"friends"
"-"
"mini"
"everybody"
単語 "great" とその近傍のサブグラフを抽出して、この単語の共起を可視化します。
H = subgraph(G,[idx; nbrs]); LWidths = 5*H.Edges.Weight/max(H.Edges.Weight); plot(H,'LineWidth',LWidths) title("Co-occurrence Network - Word: """ + word + """");
グラフとネットワーク解析の詳細については、グラフとネットワーク アルゴリズムを参照してください。
参考
tokenizedDocument
| bagOfWords
| removeStopWords
| graph