티스토리 뷰

Data/Analytics

[DA] WordCloud

jeong_reneer 2022. 2. 10. 22:10

 

1. WordCloud

: 텍스트 데이터에서 단어들의 빈도수를 나타내는 그림

 

텍스트에서 빈도수가 높거나 중요한 단어 직관적 파악 가능

- 빈도수가 높은 단어일수록 더 크고 두껍게 나타남

- 텍스트 데이터의 주제를 파악하는 데 도움

 

2. 모듈 다운로드 및 설치

1) cmd

conda install -c conda-forge wordcloud=1.5
# 설치 실패하거나 DLL load failed 에러 뜰 경우
conda remove pillow
conda install -c conda-forge wordcloud=1.5

2) python shell

from wordcloud import WordCloud, STOPWORDS as stopwords

 

3. WordCloud 만들기

1) text load 및 WordCloud 인스턴스 생성

▪ background_color="black" : 배경색 지정

▪ collocations=True : said King, said Hatter 같이 자주 나타나는 단어를 하나의 어구로 분류

▪ stopwords : 불용어 (문장에서 빈도수는 높지만 분석에 쓸모없는 단어들) 제거하는 작업 필요

  - If None, build-in STOPWORDS list will be used

alice_text = open("/content/drive/MyDrive/Ybigta/NLP/data/alice_novel.txt","r").read()

alicewc = WordCloud(background_color = "white",
                  collocations = False, 
                  stopwords = stopwords)

alicewc.generate(alice_text)

 

2) 각 word의 frequency 확인

- 가장 많이 나온 단어 = 1, 나머지는 상대적인 값

alicewc.words_

 

3) 생성한 WordCloud 시각화

alicewc.to_image()

 

4) 결과 이미지로 저장

alicewc.to_file("my_alice.png") # 다른 확장자도 가능

 

5) 더 많은 단어 담기

(1) size (width, height) 늘리기

- width : int (default=400), height : int (default=200)

alicewc = WordCloud(background_color = 'white',
                   collocations = False,
                   stopwords = stopwords,
                   width = 600, height = 400)

alicewc.generate(alice_text)
alicewc.to_image()

 

(2) min_font_size 줄이기

- min_font_size (default=4)

alicewc = WordCloud(background_color = "white",
                    collocations = False,
                    stopwords = stopwords,
                    colormap = "Reds",
                    min_font_size = 5) 

alicewc.generate(alice_text)
alicewc.to_image()

 

cf) max_font_size

: 가장 빈도수가 높은 단어의 크기 주요 단어들을 얼마나 부각시킬지 설정 가능

alicewc = WordCloud(background_color = "white",
                    collocations = False,
                    stopwords = stopwords,
                    colormap = "Reds",
                    max_font_size = 100) 

alicewc.generate(alice_text)
alicewc.to_image()

 

6) 쓸모없이 보이는 단어 지우기 (ex. said)

- stopwordsadd  (1개) 또는 update (2개 이상) 한 후 generate

stopwords.add("said")
#stopwords.update(["said"," know"]) #여러개일 경우 update 사용

alicewc.generate(alice_text)
alicewc.to_image()

 

7) WordCloud 색 바꾸기

(1) colormap 지정

- 다양한 colormap 가능 (default = "viridis")

https://matplotlib.org/2.0.2/examples/color/colormaps_reference.html

 

color example code: colormaps_reference.py — Matplotlib 2.0.2 documentation

color example code: colormaps_reference.py (Source code) """ ================== Colormap reference ================== Reference for colormaps included with Matplotlib. This reference example shows all colormaps included with Matplotlib. Note that any color

matplotlib.org

alicewc = WordCloud(background_color = "white",
                  collocations = False,
                  stopwords = stopwords,
                   colormap = "flag") 

alicewc.generate(alice_text)
alicewc.to_image()

 

(2) color_func 설정하여 색 적용

- 직접 색 조합 지정 가능

https://www.rapidtables.com/web/color/RGB_Color.html

 

RGB Color Codes Chart 🎨

RGB Color Codes Chart RGB color picker | RGB color codes chart | RGB color space | RGB color format and calculation | RGB color table RGB color picker RGB color codes chart Hover with cursor on color to get the hex and decimal color codes below: RGB color

www.rapidtables.com

def my_color_func(*args, **kwargs):
    #print(args, kwargs)
    font_size = kwargs['font_size']
    if font_size > 50:
        return "rgb(204,0,102)"
    elif font_size > 20:
        return "rgb(255,51,153)"
    else:
        return "rgb(255,153,204)"
        
alicewc = WordCloud(background_color = "white",
                  collocations = False,
                  stopwords = stopwords,
                  color_func = my_color_func)

alicewc.generate(alice_text)
alicewc.to_image()

 

 

 

3. Image Mask에 WordCloud 시각화

1) Image Mask 가져오기

- Image 가져온 후 np.array 통해 nd-array 형태로 변경

- WordCloud size 조정하고 싶다면, nd-array size 조정

from PIL import Image, ImageFilter
Image.open("/content/drive/MyDrive/Ybigta/NLP/data/alice_mask.png")

import numpy as np
mask_array = np.array(Image.open("/content/drive/MyDrive/Ybigta/NLP/data/alice_mask.png"))
#smaller_alice_array = np.array(Image.open("./data/alice_mask.png").resize((200, 200)))

mask_array
# array를 확인할 때 image가 클 경우 오래걸려서 멈출 수 있으므로 주의

 

2) Image Mask 위에 WordCloud 적용하기

- mask 인자로 nd-array 넣어줘야 함

alice_wc = WordCloud(background_color = "white",
                   collocations = False,
                   stopwords = stopwords,
                   mask = mask_array) # 앞에서 np.array로 만든 mask 지정

alice_wc.generate(alice_text)
alice_wc.to_image()

 

 

 

4. Dataframe에서 Text data 추출해 WordCloud 만들기

1) 파일 불러오기

immigration.csv1980~2013 매 해 캐나다로 이민 온 사람들을 국적별로 분류한 dataframe

- Continent : 해당 국가가 위치한 대륙

- Region : 세분화된 지역 분류

- DevName : 해당 국가가 개도국(Developing)인지 선진국(Developed)인지

immigration = pd.read_csv("/content/drive/MyDrive/Ybigta/NLP/data/immigration.csv")
immigration = immigration.set_index("Country")
immigration.head(10)

#총 이민자 수
total_immigration =int(immigration["Total"].sum())
total_immigration

 

2) Text data & WordCloud 생성

: 각 나라의 Total 이민자 수가 총 이민자 수에서 차지하는 비율만큼 Text에 그 국가의 이름 포함시키기 (길이 3000)

→ 3000 * 전체 immigrants 중 각 국가의 국민이 차지하는 비중 ≥ 1 인 국가만 뜸

max_words = 3000
txt = ''
for country in immigration.index.values:
    # 국가이름이 한 단어인 국가들만 고려
    if len(country.split(' ')) == 1:
        repeat_num_times = int(immigration.loc[country, 'Total']/float(total_immigration)*max_words)
        txt = txt + ((country + ' ') * repeat_num_times)  
        
world_wordcloud = WordCloud(background_color = 'white',
                           collocations = False)

world_wordcloud.generate(txt)
world_wordcloud.to_image()

 

 

 

 

'Data > Analytics' 카테고리의 다른 글

[DA] NLP Pipeline - NLTK & KoNLPy  (0) 2022.02.09
[DA] FE (Feature Engineering)  (0) 2022.01.18
[DA] EDA & 시각화  (0) 2022.01.17
[DA] Numpy & Pandas  (0) 2022.01.13
댓글
공지사항