전처리된 데이터
import joblib
data = joblib.load('movie.pkl')
locals().update(data)
학습된 모형
from gensim.models.ldamodel import LdaModel
model = LdaModel.load('lda-model')
테스트 데이터셋을 변환한다.
from gensim.matutils import Sparse2Corpus
test_corpus = Sparse2Corpus(x_test.T)
log_perplexity
메소드로 $-H$에 해당하는 값을 구할 수 있다.
log_pp = model.log_perplexity(test_corpus)
혼란도로 바꾸려면 아래와 같이 계산한다.
2 ** -log_pp
137.95661165801067
혼란도는 낮을 수록, log_perplexity
는 높을 수록 좋다.
응집도 계산을 위해 토큰화된 텍스트를 입력해주어야 한다. 텍스트를 불러온다.
import pandas as pd
df = pd.read_csv('movie-plot.zip')
plots = df.loc[index_test, 'Plot']
cv.tokenizer
를 설정해주지 않았기 때문에 다음과 같은 정규식을 이용해 토큰을 추출한다.
cv.token_pattern
'(?u)\\b\\w\\w+\\b'
빠른 정규식 처리를 위해 정규식을 컴파일한다.
import re
token_re = re.compile(cv.token_pattern)
텍스트에서 정규식을 이용해 토큰을 추출한다.
words = set(cv.get_feature_names())
texts = []
for plot in plots:
text = []
for word in token_re.findall(plot):
word = word.lower()
if word in words:
text.append(word)
texts.append(text)
응집도 계산에 필요한 사전을 만든다.
from gensim.corpora.dictionary import Dictionary
dic = Dictionary()
dic.token2id = {t: i for i, t in enumerate(cv.get_feature_names())}
응집도를 계산한다. 계산 방법에는 u_mass
, c_v
, c_uci
, c_npmi
등이 있다.
from gensim.models import CoherenceModel
coh = CoherenceModel(model=model, texts=texts, dictionary=dic, coherence='c_v')
coh.get_coherence()
0.34100143336957994
top_words = set()
for topic in range(5):
for word, prob in model.show_topic(topic, topn=25):
top_words.add(word)
len(top_words)
87
len(top_words) / (25*5)
0.696