잠재 의미 분석
전처리는 토픽 모델링을 위한 전처리를 참조
SVD
from sklearn.decomposition import TruncatedSVD
svd = TruncatedSVD(n_components=100, random_state=1234)
doc_emb = svd.fit_transform(dtm)
스크리 플롯
import matplotlib.pyplot as plt
plt.plot(svd.explained_variance_)
단어 임베딩
word_emb = svd.components_.T
words = cv.get_feature_names_out().tolist()
i = words.index('모발')
plt.plot(word_emb[i])
코사인 유사도
from sklearn.metrics.pairwise import cosine_similarity
sim = cosine_similarity(word_emb)
import numpy as np
s = np.argsort(sim[i])
related = s[-2:-12:-1]
for j in related:
print(words[j])
시각화
다차원 척도법
indices = []
target = ['모발', '손상', '두피', '모공',
'용기', '내용물']
for w in target:
i = words.index(w)
indices.append(i)
print(w, i)
dist = 1 - sim[indices, ][:, indices]
from sklearn.manifold import MDS
mds = MDS(dissimilarity='precomputed', random_state=1234)
pos = mds.fit_transform(dist)
plot에서 글자가 겹치지 않도록 조정해주는 adjustText
!pip install adjusttext
from adjustText import adjust_text
from adjustText import adjust_text
plt.plot(pos[:, 0], pos[:, 1], '.')
texts = [plt.text(pos[i, 0], pos[i, 1], w) for i, w in enumerate(target)]
adjust_text(texts)
회전
factor_analyzer 설치
pip install factor_analyzer
회전 후 시각화
from factor_analyzer.rotator import Rotator
rotator = Rotator()
rot = rotator.fit_transform(word_emb)
plt.plot(rot[i])
관련도 순으로 출력
t = np.argmax(rot[i])
topic_words_idx = np.argsort(rot[:, t])
for j in topic_words_idx[-1:-11:-1]:
print(words[j])