文書クラスタリング

Pythonで学ぶクラスタ分析

Shaumik Daityari

Business Analyst

文書クラスタリング:基本概念

  1. 処理前にデータをクレンジング
  2. 文書内の語の重要度を算出(TF-IDF 行列)
  3. TF-IDF 行列をクラスタリング
  4. 各クラスタの上位語・文書を取得
Pythonで学ぶクラスタ分析

データのクレンジングとトークン化

  • テキストをトークンに分割し、前処理でクレンジング
from nltk.tokenize import word_tokenize
import re

def remove_noise(text, stop_words = []):
    tokens = word_tokenize(text)

cleaned_tokens = [] for token in tokens: token = re.sub('[^A-Za-z0-9]+', '', token)
if len(token) > 1 and token.lower() not in stop_words: # Get lowercase cleaned_tokens.append(token.lower()) return cleaned_tokens
remove_noise("It is lovely weather we are having. I hope the weather continues.")
['lovely', 'weather', 'hope', 'weather', 'continues']
Pythonで学ぶクラスタ分析

文書-語行列と疎行列

  • 文書-語行列を作成
  • 行列の多くはゼロ要素

Source

  • 疎行列として表現

Source

Pythonで学ぶクラスタ分析

TF-IDF(Term Frequency - Inverse Document Frequency)

  • 重み付き指標:コーパス内での語の重要度を評価
from sklearn.feature_extraction.text import TfidfVectorizer

tfidf_vectorizer = TfidfVectorizer(max_df=0.8, max_features=50, min_df=0.2, tokenizer=remove_noise)
tfidf_matrix = tfidf_vectorizer.fit_transform(data)
Pythonで学ぶクラスタ分析

疎行列でのクラスタリング

  • SciPy の kmeans() は疎行列を未対応
  • .todense() で通常の行列に変換
cluster_centers, distortion = kmeans(tfidf_matrix.todense(), num_clusters)
Pythonで学ぶクラスタ分析

各クラスタの上位語

  • クラスタ中心:語彙数と同じ長さのリスト
  • 中心の各値はその語の重要度
  • 辞書を作り上位語を表示
terms = tfidf_vectorizer.get_feature_names_out()

for i in range(num_clusters):
    center_terms = dict(zip(terms, list(cluster_centers[i])))

sorted_terms = sorted(center_terms, key=center_terms.get, reverse=True)
print(sorted_terms[:3])
['room', 'hotel', 'staff']

['bad', 'location', 'breakfast']
Pythonで学ぶクラスタ分析

追加の考慮点

  • ハイパーリンク、絵文字などへの対応
  • 語の正規化(run, ran, running → run)
  • 大規模データでは .todense() は非現実的な場合あり
Pythonで学ぶクラスタ分析

次は演習です!

Pythonで学ぶクラスタ分析

Preparing Video For Download...