Python

텍스트 군집분석

이부일 2020. 3. 2. 11:59

# 패키지 로딩하기
import pandas as pd
from konlpy.tag import Hannanum
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.cluster import KMeans
from sklearn.decomposition import PCA
import matplotlib.pyplot as plt

 

# 한나눔 형태소 분석기 클래스 생성하기
hannanum = Hannanum()

 

# 뉴스 데이터 읽어오기
news = pd.read_csv("d:/deeplearning/textmining/군집분석데이터.csv", engine = "python")

 

# 한나눔 형태소 분석기를 이용한 명사 추출하기
news_docs = [ ]
for i in news["기사내용"]:
     news_docs.append(hannanum.nouns(i))

 

for i in range(len(docs)):
     news_docs[i] = ' '.join(news_docs[i])

 

# 명사를 벡터로 만들기
news_vec = CountVectorizer()
news_x    = news_vec .fit_transform(news_docs)

 

# 벡터를 데이터 프레임으로 만들기
news_df = pd.DataFrame(news_x.toarray(),
columns = vec.get_feature_names())

 

# 텍스트 군집분석
news_kmeans = KMeans(n_clusters = 3).fit(news_df)

 

# 주성분 분석하기
news_pca = PCA(n_components = 2)
news_principalComponents = news_pca.fit_transform(news_df)

 

# 주성분 분석의 결과를 데이터 프레임으로 만들기
news_df_pca = pd.DataFrame(data        = news_principalComponents,

                                         columns = ["PC1", "PC2"])
news_df_pca.index = news["검색어"]

 

# 그래프 작성하기
plt.scatter(news_df_pca.iloc[news_kmeans.labels_ == 0, 0],

              news_df_pca.iloc[news_kmeans.labels_ == 0, 1],

              s       = 10,

              c       = "red",

              label = "Cluster1")

 

plt.scatter(news_df_pca.iloc[news_kmeans.labels_ == 1, 0],

              news_df_pca.iloc[news_kmeans.labels_ == 1, 1],

              s       = 10,

              c       = "blue",

              label = "Cluster2")

 

plt.scatter(news_df_pca.iloc[news_kmeans.labels_ == 2, 0],

              news_df_pca.iloc[news_kmeans.labels_ == 2, 1],

              s       = 10,

              c       = "green",

              label = "Cluster3")

 

plt.legend()
plt.show()

 

 

[출처] 잡아라! 텍스트마이닝 with 파이썬, 서대호 지음, BJ, p81~83