문서 클러스터링

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으로 배우는 군집 분석

문서-용어 행렬과 희소 행렬

  • 문서-용어 행렬 생성
  • 행렬 대부분의 원소는 0

Source

  • 희소 행렬 생성

Source

Python으로 배우는 군집 분석

TF-IDF(단어 빈도-역문서 빈도)

  • 가중치 기준: 코퍼스에서 단어의 문서 내 중요도를 평가
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...