[파이썬] nltk LDA 및 NMF를 사용한 텍스트 분해

텍스트 데이터는 양이 많고 복잡한 특성을 가지고 있기 때문에 이를 분석하고 이해하는 것은 도전적인 작업입니다. 텍스트 분해는 이러한 텍스트 데이터를 작은 구성 요소로 분해하여 이해하기 쉬운 형태로 변환하는 기법입니다. 이러한 기법 중에서도 LDA(Latent Dirichlet Allocation)와 NMF(Non-negative Matrix Factorization)는 텍스트 분해에 많이 사용되는 알고리즘입니다.

이 글에서는 Python의 nltk 라이브러리를 사용하여 LDA와 NMF를 텍스트 분해에 적용하는 방법에 대해 알아보겠습니다.

1. LDA (Latent Dirichlet Allocation)

LDA는 텍스트 데이터의 잠재적인 토픽을 추출하는 기법입니다. 이를 통해 텍스트 데이터의 주제를 파악하거나 유사한 주제를 가진 문서들을 그룹화할 수 있습니다.

다음은 LDA를 사용하여 텍스트 데이터를 분해하는 예제 코드입니다.

import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from sklearn.decomposition import LatentDirichletAllocation
from sklearn.feature_extraction.text import CountVectorizer

# 텍스트 데이터
documents = [
    "This is the first document.",
    "This document is the second document.",
    "And this is the third one.",
    "Is this the first document?"
]

# 전처리 단계
lemmatizer = WordNetLemmatizer()
stop_words = set(stopwords.words('english'))

def preprocess_text(text):
    tokens = word_tokenize(text.lower())
    tokens = [lemmatizer.lemmatize(token) for token in tokens if token.isalpha()]
    tokens = [token for token in tokens if token not in stop_words]
    return ' '.join(tokens)

# 텍스트 전처리
preprocessed_documents = [preprocess_text(document) for document in documents]

# 단어 벡터화
count_vectorizer = CountVectorizer()
word_vector = count_vectorizer.fit_transform(preprocessed_documents)

# LDA 모델 생성 및 학습
lda_model = LatentDirichletAllocation(n_components=2)
lda_model.fit(word_vector)

# 토픽 출력
for topic_idx, topic in enumerate(lda_model.components_):
    print(f"Topic {topic_idx}: ")
    print([count_vectorizer.get_feature_names()[i] for i in topic.argsort()[-5:]])
    print()

2. NMF (Non-negative Matrix Factorization)

NMF는 텍스트 데이터를 비음수 행렬의 곱으로 분해하는 기법입니다. 이를 통해 텍스트 데이터의 의미적인 구조를 추출하고 관련성 있는 단어나 문서들을 그룹화할 수 있습니다.

다음은 NMF를 사용하여 텍스트 데이터를 분해하는 예제 코드입니다.

import nltk
from nltk.corpus import stopwords
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize
from sklearn.decomposition import NMF
from sklearn.feature_extraction.text import TfidfVectorizer

# 텍스트 데이터
documents = [
    "This is the first document.",
    "This document is the second document.",
    "And this is the third one.",
    "Is this the first document?"
]

# 전처리 단계
lemmatizer = WordNetLemmatizer()
stop_words = set(stopwords.words('english'))

def preprocess_text(text):
    tokens = word_tokenize(text.lower())
    tokens = [lemmatizer.lemmatize(token) for token in tokens if token.isalpha()]
    tokens = [token for token in tokens if token not in stop_words]
    return ' '.join(tokens)

# 텍스트 전처리
preprocessed_documents = [preprocess_text(document) for document in documents]

# TF-IDF 벡터화
tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix = tfidf_vectorizer.fit_transform(preprocessed_documents)

# NMF 모델 생성 및 학습
nmf_model = NMF(n_components=2)
nmf_model.fit(tfidf_matrix)

# 토픽 출력
for topic_idx, topic in enumerate(nmf_model.components_):
    print(f"Topic {topic_idx}: ")
    print([tfidf_vectorizer.get_feature_names()[i] for i in topic.argsort()[-5:]])
    print()

이렇게 nltk 라이브러리의 LDA와 NMF를 사용하여 텍스트 데이터를 분해할 수 있습니다. 이러한 텍스트 분해 기법을 활용하면 복잡한 텍스트 데이터를 더욱 쉽게 이해하고 분석할 수 있습니다.

참고 자료: