logo

[텍스트 분석] 잠재 의미 분석

전처리는 [토픽 모델링을 위한 전처리](/course/text-mining/토픽 모델링을 위한 전처리)를 참조

 

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_)
[<matplotlib.lines.Line2D at 0x2494f3a8370>]
svd = TruncatedSVD(n_components=15, random_state=1234)
doc_emb = svd.fit_transform(dtm)
 

단어 임베딩

word_emb = svd.components_.T

words = cv.get_feature_names_out().tolist()
i = words.index('모발')

plt.plot(word_emb[i])
[<matplotlib.lines.Line2D at 0x249505c2dd0>]

코사인 유사도

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)
모발 80
손상 159
두피 62
모공 78
용기 206
내용물 47

C:\Users\eupho\anaconda3\lib\site-packages\sklearn\manifold\_mds.py:299: FutureWarning: The default value of `normalized_stress` will change to `'auto'` in version 1.4. To suppress this warning, manually set the value of `normalized_stress`.
  warnings.warn(

한글 글꼴 설정

import matplotlib
matplotlib.rc('font', family='Malgun Gothic')
matplotlib.rc('axes', unicode_minus=False)  # 맑은 고딕에는 유니코드 마이너스 글꼴이 없음

plot에서 글자가 겹치지 않도록 조정해주는 adjustText

!pip install adjusttext
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)
6
 

회전

factor_analyzer 설치

pip install factor_analyzer

회전 후 시각화

from factor_analyzer.rotator import Rotator
rotator = Rotator()
rot = rotator.fit_transform(word_emb)
i = words.index('모발')
plt.plot(rot[i])
[<matplotlib.lines.Line2D at 0x24950ed5660>]

관련도 순으로 출력

t = np.argmax(rot[i])
t
4
topic_words_idx = np.argsort(rot[:, t])

for j in topic_words_idx[-1:-11:-1]:
    print(words[j])
모발
두피
도포
단계
손상
방법
염색
후
세척
피

Previous
토픽 모델링을 위한 전처리
Next
NMF