Gensim과 LDA를 활용하여 토픽 모델링의 성능 평가를 위한 빈도수 기반 필터링 방법 실습하기

토픽 모델링은 문서 집합에서 주제를 추출해내는 기법입니다. 이를 통해 문서의 주제와 상관된 단어들을 파악하고, 유사한 주제를 가진 문서들을 그룹화할 수 있습니다. Gensim은 Python에서 토픽 모델링을 위한 라이브러리로, LDA(Latent Dirichlet Allocation) 모델을 구현할 수 있습니다.

이번 실습에서는 Gensim과 LDA를 활용하여 토픽 모델링의 성능을 평가하기 위한 빈도수 기반 필터링 방법을 다루어보겠습니다. 이 방법은 토픽 생성에 영향을 미치는 빈도수가 낮은 단어들을 필터링하여 모델의 정확도를 높이는 방법입니다.

1. 데이터 전처리

먼저, 토픽 모델링을 수행할 문서 데이터를 전처리해야 합니다. 이를 위해 다음과 같은 단계를 따릅니다.

  1. 텍스트 데이터 로드
  2. 텍스트 데이터를 토큰화하여 단어로 분할
  3. 불용어(stopwords) 제거
  4. 단어들을 벡터화

여기서는 예시로 텍스트 데이터로 “news_articles.txt” 파일을 사용하겠습니다.

import gensim
from gensim.utils import simple_preprocess
from gensim.parsing.preprocessing import remove_stopwords
from gensim.corpora import Dictionary

# 텍스트 데이터 로드
data = open("news_articles.txt", "r").read()

# 텍스트 데이터를 토큰화하여 단어로 분할
tokens = [simple_preprocess(article) for article in data.split("\n")]

# 불용어 제거
tokens = [[word for word in article if word not in set(stopwords.words('english'))] for article in tokens]

# 단어들을 벡터화
dictionary = Dictionary(tokens)
corpus = [dictionary.doc2bow(article) for article in tokens]

2. LDA 모델 학습

다음으로, 전처리된 데이터를 활용하여 LDA 모델을 학습합니다.

# LDA 모델 학습
lda_model = gensim.models.ldamodel.LdaModel(corpus=corpus,
                                           id2word=dictionary,
                                           num_topics=10,
                                           random_state=42,
                                           update_every=1,
                                           chunksize=100,
                                           passes=10,
                                           alpha='auto',
                                           per_word_topics=True)

위 코드에서 num_topics는 추출하고자 하는 주제의 수를 나타내며, 다른 파라미터들은 LDA 모델 학습에 사용되는 설정값입니다.

3. 빈도수 기반 필터링

성능 평가를 위해 빈도수 기반 필터링 방법을 적용해보겠습니다. 이 방법은 빈도수가 낮은 단어를 제거하여 모델의 성능을 향상시킵니다. 아래 코드는 빈도수 기반 필터링을 적용한 후, 필터링된 단어를 기준으로 새로운 LDA 모델을 학습하는 예시입니다.

# 단어 빈도수 기반 필터링
word_frequencies = {dictionary[word_id]: freq for word_id, freq in dictionary.cfs.items()}
filtered_words = [word for word in dictionary.itervalues() if word_frequencies.get(word, 0) > 10]

# 빈도수 기반 필터링된 단어를 기준으로 새로운 LDA 모델 학습
filtered_corpus = [[(word_id, freq) for word_id, freq in article if dictionary[word_id] in filtered_words] for article in corpus]
filtered_dictionary = Dictionary(filtered_corpus)
filtered_lda_model = gensim.models.ldamodel.LdaModel(corpus=filtered_corpus,
                                                     id2word=filtered_dictionary,
                                                     num_topics=10,
                                                     random_state=42,
                                                     update_every=1,
                                                     chunksize=100,
                                                     passes=10,
                                                     alpha='auto',
                                                     per_word_topics=True)

위 코드에서 filtered_words는 빈도수 기반 필터링된 단어들의 리스트를 나타내며, filtered_corpusfiltered_dictionary는 필터링된 데이터로 새롭게 생성된 corpus와 dictionary를 나타냅니다.

4. 성능 평가

성능 평가를 위해 토픽의 일관성(coherence)를 계산할 수 있습니다. 토픽 일관성은 토픽 내 단어들 간의 연결성을 측정하는 지표로, 높을수록 좋은 품질의 토픽을 의미합니다.

from gensim.models import CoherenceModel

# Original LDA 모델의 토픽 일관성 계산
coherence_original = CoherenceModel(lda_model, texts=tokens, dictionary=dictionary, coherence='c_v').get_coherence()

# 필터링된 LDA 모델의 토픽 일관성 계산
coherence_filtered = CoherenceModel(filtered_lda_model, texts=tokens, dictionary=filtered_dictionary, coherence='c_v').get_coherence()

print("Original LDA 모델의 토픽 일관성:", coherence_original)
print("필터링된 LDA 모델의 토픽 일관성:", coherence_filtered)

위 코드는 CoherenceModel을 활용하여 토픽 일관성을 계산하고 출력하는 예시입니다. 일관성 값이 높을수록 더 좋은 모델이라고 할 수 있습니다.

마무리

이번 실습에서는 Gensim과 LDA를 활용하여 토픽 모델링의 성능 평가를 위한 빈도수 기반 필터링 방법을 소개했습니다. 이를 통해 더 정확하고 일관성 있는 토픽 모델을 구축할 수 있습니다. 추가로 다른 평가 지표나 필터링 방법을 적용하여 토픽 모델링의 성능을 더욱 개선시킬 수 있습니다.

#Gensim #LDA