Kakao Arena 3 EDA on Google Colab

Page content

공지

제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 Reference는 꼭 확인하셔서 교재 구매 또는 관련 Reference를 확인하시기를 바랍니다.

이전 포스트인 Colab + Drive + Github Workflow 실전 테스트용으로 생각하면서 읽어주기를 바란다.

I. 개요

  • 프로젝트 폴더 내에서 간단하게 EDA를 실습하는 시간을 갖도록 한다.
  • 관련 패키지는 우선 다른 곳에서 설치 되었다는 것을 가정한다.
  • 본 포스트의 핵심은 환경설정이 Google Colab + Drive내에서 작업하는 것이다.

II. 패키지 불러오기

  • 다음과 같은 순서로 실행한다.
  • 첫째, 나눔고딕 한글 폰트를 설치한다.
  • 둘째, 내부 패키지를 먼저 불러온다.
  • 셋째, 런타임을 다시 실행한다.
  • 넷째, Drive 마운트를 진행한다.
  • 다섯째, 외부 패키지를 불러온다.

(1) 나눔고딕 폰트 불러오기

  • 다음과 같은 방식으로 폰트를 불러온다.
%config InlineBackend.figure_format = 'retina'
!sudo apt-get -qq -y install fonts-nanum
The following NEW packages will be installed:
  fonts-nanum
0 upgraded, 1 newly installed, 0 to remove and 31 not upgraded.
Need to get 9,604 kB of archives.
After this operation, 29.5 MB of additional disk space will be used.
Selecting previously unselected package fonts-nanum.
(Reading database ... 144433 files and directories currently installed.)
Preparing to unpack .../fonts-nanum_20170925-1_all.deb ...
Unpacking fonts-nanum (20170925-1) ...
Setting up fonts-nanum (20170925-1) ...
Processing triggers for fontconfig (2.12.6-0ubuntu2) ...

(2) 내부에 기 설치된 패키지 불러오기

  • 관련 패키지를 불러온다.
from datetime import timedelta, datetime
import glob
from itertools import chain
import json
import os
import re

import numpy as np
import pandas as pd

from wordcloud import WordCloud
import nltk
from nltk.corpus import stopwords
from collections import Counter
from sklearn.feature_extraction.text import TfidfVectorizer
from sklearn.feature_extraction.text import CountVectorizer

from pandas.plotting import register_matplotlib_converters
import seaborn as sns
import matplotlib.pyplot as plt
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.font_manager as fm
fontpath = '/usr/share/fonts/truetype/nanum/NanumBarunGothic.ttf'
font = fm.FontProperties(fname=fontpath, size=9)
plt.rc('font', family='NanumBarunGothic') 
plt.rcParams["figure.figsize"] = (20, 10)
register_matplotlib_converters()
mpl.font_manager._rebuild()
mpl.pyplot.rc('font', family='NanumGothic')
fm._rebuild()

(3) 외부 패키지인 konlpy 불러오기

  • 다음 코드를 실행하기 전 반드시 [런타임]-[런타임 다시 시작]을 누르자.
# Mount Google Drive
from google.colab import drive # import drive from google colab

ROOT = "/content/drive"     # default location for the drive
print(ROOT)                 # print content of ROOT (Optional)
drive.mount(ROOT)           # we mount the google drive at /content/drive
/content/drive
Drive already mounted at /content/drive; to attempt to forcibly remount, call drive.mount("/content/drive", force_remount=True).
import os, sys
my_path = '/content/notebooks'
os.symlink('/content/drive/My Drive/Colab Notebooks/competition/pkgs_folder', my_path)
sys.path.insert(0,my_path)
from konlpy.tag import Twitter
  • 위 코드에서 만약 에러가 나면 처음부터 다시 해야 하니, 유의 바란다.
pd.options.mode.chained_assignment = None

III. 데이터 불러오기

  • 이제 깃허브 프로젝트인 competition으로 파일 경로를 변경 한 뒤, 데이터를 불러오도록 한다.
# import join used to join ROOT path and MY_GOOGLE_DRIVE_PATH
from os.path import join  

# path to your project on Google Drive
MY_GOOGLE_DRIVE_PATH = 'My Drive/Colab Notebooks/competition'

PROJECT_PATH = join(ROOT, MY_GOOGLE_DRIVE_PATH)
%cd "{PROJECT_PATH}"
/content/drive/My Drive/Colab Notebooks/competition
!git status
On branch master
Your branch is up to date with 'origin/master'.

Changes not staged for commit:
  (use "git add/rm <file>..." to update what will be committed)
  (use "git checkout -- <file>..." to discard changes in working directory)

	modified:   .gitignore
	deleted:    kakao_arena_3/source/temp.ipynb
	deleted:    kakao_arena_3/source/temp2.ipynb

Untracked files:
  (use "git add <file>..." to include in what will be committed)

	kakao_arena_3/source/kakao_arena_3_eda.ipynb

no changes added to commit (use "git add" and/or "git commit -a")
!ls
kakao_arena_3  pkgs_folder  README.md
# genre_gn_all.json
genre_gn_all = pd.read_json('kakao_arena_3/data/genre_gn_all.json', typ = 'series')
# 장르코드 : gnr_code, 장르명 : gnr_name
genre_gn_all = pd.DataFrame(genre_gn_all, columns = ['gnr_name']).reset_index().rename(columns = {'index' : 'gnr_code'})
print(genre_gn_all.head())
  gnr_code gnr_name
0   GN0100      발라드
1   GN0101   세부장르전체
2   GN0102      '80
3   GN0103      '90
4   GN0104      '00
# 장르코드 뒷자리 두 자리가 00이 아닌 코드를 필터링
dtl_gnr_code = genre_gn_all[genre_gn_all['gnr_code'].str[-2:] != '00']
dtl_gnr_code.rename(columns = {'gnr_code' : 'dtl_gnr_code', 'gnr_name' : 'dtl_gnr_name'}, inplace = True)
print(dtl_gnr_code.head())
  dtl_gnr_code dtl_gnr_name
1       GN0101       세부장르전체
2       GN0102          '80
3       GN0103          '90
4       GN0104          '00
5       GN0105         '10-

IV. 데이터 시각화 구현

  • 한글 시각화를 구현한다.
# Plotting a bar graph of the number of stores in each city, for the first ten cities listed
# in the column 'City'
dtl_gnr_name_count  = dtl_gnr_code['dtl_gnr_name'].value_counts()
dtl_gnr_name_count = dtl_gnr_name_count[:10,]
plt.figure(figsize=(10,5))
sns.barplot(dtl_gnr_name_count.index, dtl_gnr_name_count.values, alpha=0.8)
plt.title('한글 시각화 테스트')
plt.ylabel('Number of Occurrences', fontsize=12)
plt.xlabel('세부장르', fontsize=12)
plt.show()

png

  • 한글 시각화가 정상적으로 나온 것을 꼭 확인한다.

V. Github 연동

  • 우선 깃허브와 연동하자.
  • 그리고, 작성된 코드를 업데이트 하도록 한다.
# Clone github repository setup
# import join used to join ROOT path and MY_GOOGLE_DRIVE_PATH
from os.path import join  

# path to your project on Google Drive
MY_GOOGLE_DRIVE_PATH = 'My Drive/Colab Notebooks/'

# replace with your github username
GIT_USERNAME = "chloevan"

# definitely replace with your
GIT_TOKEN = "your_token" # this is temporary, whenever you add, need to get token number

# Replace with your github repository in this case we want 
# to clone deep-learning-v2-pytorch repository
GIT_REPOSITORY = "competition"

PROJECT_PATH = join(ROOT, MY_GOOGLE_DRIVE_PATH)

# It's good to print out the value if you are not sure 
print("PROJECT_PATH: ", PROJECT_PATH)  

# In case we haven't created the folder already; we will create a folder in the project path 
# !mkdir "{PROJECT_PATH}"    

#GIT_PATH = "https://{GIT_TOKEN}@github.com/{GIT_USERNAME}/{GIT_REPOSITORY}.git" this return 400 Bad Request for me
GIT_PATH = "https://" + GIT_TOKEN + "@github.com/" + GIT_USERNAME + "/" + GIT_REPOSITORY + ".git"
print("GIT_PATH: ", GIT_PATH)
PROJECT_PATH:  /content/drive/My Drive/Colab Notebooks/
GIT_PATH:  https://619..your_token..46b@github.com/chloevan/competition.git
!git remote set-url origin "{GIT_PATH}"
!git add .

# Linked to account
!git config --global user.email "your_email_address"
!git config --global user.name "your_username"

# Git commit
!git commit -m "finally updated"

!git push
[master c93a004] finally updated
1 file changed, 1 insertion(+), 1 deletion(-)
Counting objects: 15, done.
Delta compression using up to 2 threads.
Compressing objects: 100% (15/15), done.
Writing objects: 100% (15/15), 1.79 KiB | 367.00 KiB/s, done.
Total 15 (delta 9), reused 0 (delta 0)
remote: Resolving deltas: 100% (9/9), completed with 3 local objects.
To https://github.com/chloevan/competition.git
  320ecd5..c93a004  master -> master

V. Reference

PinkWink. (2019, November 18). 구글 Colab에서 한글 문제 대응하기. Retrieved May 24, 2020, from https://pinkwink.kr/1255.

Say, V. (2020, January 01). Google Drive + Google Colab + GitHub; Don’t Just Read, Do It! Retrieved May 24, 2020, from https://towardsdatascience.com/google-drive-google-colab-github-dont-just-read-do-it-5554d5824228

Żero, O. (2019, October 30). Colaboratory + Drive + Github - the workflow made simpler. Retrieved May 24, 2020, from https://towardsdatascience.com/colaboratory-drive-github-the-workflow-made-simpler-bde89fba8a39