ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • 텍스트 군집분석
    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

    'Python' 카테고리의 다른 글

    LDA(Latent Dirichlet Allocation)  (0) 2020.03.02
    텍스트 구조적 군집분석  (0) 2020.03.02
    word cloud  (0) 2020.03.02
    KoNLPy 패키지에서 제공하는 형태소 분석기  (0) 2020.02.27
    nltk 패키지의 어근동일화(stemming)  (0) 2020.02.27
Designed by Tistory.