Google Colab

데이콘 대회 참여 - 06 교차검증과 파라미터 튜닝

공지

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

사전작업

!pip install https://github.com/pandas-profiling/pandas-profiling/archive/master.zip
Collecting https://github.com/pandas-profiling/pandas-profiling/archive/master.zip
  Using cached https://github.com/pandas-profiling/pandas-profiling/archive/master.zip
.
.
.
Successfully built pandas-profiling

I. 빅쿼리 연동

  • 지난 시간에 데이콘에서 내려받은 데이터를 빅쿼리에 넣는 작업을 진행하였다.
  • 빅쿼리에 저장된 데이터를 구글 코랩으로 불러오려면 다음과 같이 진행한다.

(1) 사용자 계정 인증

구글 코랩을 사용해서 인증 절차를 밟도록 한다. 아래 소스코드는 변경시키지 않는다. 아래 절차대로 진행하면 된다. Gmail 인증 절차와 비슷하다.

데이콘 대회 참여 - 05 GBM 파라미터 튜닝

공지

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

사전작업

!pip install https://github.com/pandas-profiling/pandas-profiling/archive/master.zip
Collecting https://github.com/pandas-profiling/pandas-profiling/archive/master.zip
  Using cached https://github.com/pandas-profiling/pandas-profiling/archive/master.zip
.
.
.
Successfully built pandas-profiling

I. 빅쿼리 연동

  • 지난 시간에 데이콘에서 내려받은 데이터를 빅쿼리에 넣는 작업을 진행하였다.
  • 빅쿼리에 저장된 데이터를 구글 코랩으로 불러오려면 다음과 같이 진행한다.

(1) 사용자 계정 인증

구글 코랩을 사용해서 인증 절차를 밟도록 한다. 아래 소스코드는 변경시키지 않는다. 아래 절차대로 진행하면 된다. Gmail 인증 절차와 비슷하다.

데이콘 대회 참여 - 04 데이터셋 분리

공지

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

사전작업

!pip install https://github.com/pandas-profiling/pandas-profiling/archive/master.zip
Collecting https://github.com/pandas-profiling/pandas-profiling/archive/master.zip
  Using cached https://github.com/pandas-profiling/pandas-profiling/archive/master.zip
.
.
.
Successfully built pandas-profiling

I. 빅쿼리 연동

  • 지난 시간에 데이콘에서 내려받은 데이터를 빅쿼리에 넣는 작업을 진행하였다.
  • 빅쿼리에 저장된 데이터를 구글 코랩으로 불러오려면 다음과 같이 진행한다.

(1) 사용자 계정 인증

구글 코랩을 사용해서 인증 절차를 밟도록 한다. 아래 소스코드는 변경시키지 않는다. 아래 절차대로 진행하면 된다. Gmail 인증 절차와 비슷하다.

데이콘 대회 참여 - 03 데이터 샘플링과 종속변수 로그변환

공지

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

사전작업

!pip install https://github.com/pandas-profiling/pandas-profiling/archive/master.zip
Collecting https://github.com/pandas-profiling/pandas-profiling/archive/master.zip
  Using cached https://github.com/pandas-profiling/pandas-profiling/archive/master.zip
.
.
.
Successfully built pandas-profiling

I. 빅쿼리 연동

  • 지난 시간에 데이콘에서 내려받은 데이터를 빅쿼리에 넣는 작업을 진행하였다.
  • 빅쿼리에 저장된 데이터를 구글 코랩으로 불러오려면 다음과 같이 진행한다.

(1) 사용자 계정 인증

구글 코랩을 사용해서 인증 절차를 밟도록 한다. 아래 소스코드는 변경시키지 않는다. 아래 절차대로 진행하면 된다. Gmail 인증 절차와 비슷하다.

데이콘 대회 참여 - 02 GBM을 활용한 머신러닝 예제

공지

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

개요

  • 본 예제에서는 제주 빅데이터 경진대회에서 제공하는 베이스라인 코드를 살려서 작성하였다.
  • 처음 대회를 입문하는 데 있어서, 빠르게 제출하는 것에 의미부여를 하기 바란다.
  • 다만, 데이터를 불러오는 영역 및 머신러닝 모형 알고리즘만 조금 수정하였다.
  • 향후 매일 업데이트 하면서 일종의 가이드라인이 되었으면 좋겠다.

I. 빅쿼리 연동

(1) 사용자 계정 인증

구글 코랩을 사용해서 인증 절차를 밟도록 한다. 아래 소스코드는 변경시키지 않는다. 아래 절차대로 진행하면 된다. Gmail 인증 절차와 비슷하다.

Google Colab with Kaggle - Beginner

I. 개요

  • 데이터 시각화와 변환에 대해 짧게 익혔다면 바로 실전 데이터를 활용한다.
  • 이론이 조금 부족하게 느껴질 수 있지만, 모든 것을 다 알려드릴 수는 없다.
    • 결국 공부는 스스로 해야 한다.
  • 이 강의의 목적이 Kaggle 데이터를 활용한 Python 포트폴리오 제작 강의임을 잊지 말자.

II. Kaggle KPI 설치

  • Google Colab에서 Kaggle API를 불러오려면 다음 소스코드를 실행한다.
!pip install kaggle
Requirement already satisfied: kaggle in /usr/local/lib/python3.6/dist-packages (1.5.6)
Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from kaggle) (2.23.0)
Requirement already satisfied: python-dateutil in /usr/local/lib/python3.6/dist-packages (from kaggle) (2.8.1)
Requirement already satisfied: six>=1.10 in /usr/local/lib/python3.6/dist-packages (from kaggle) (1.12.0)
Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from kaggle) (4.41.1)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from kaggle) (1.24.3)
Requirement already satisfied: certifi in /usr/local/lib/python3.6/dist-packages (from kaggle) (2020.4.5.1)
Requirement already satisfied: python-slugify in /usr/local/lib/python3.6/dist-packages (from kaggle) (4.0.0)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->kaggle) (3.0.4)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->kaggle) (2.9)
Requirement already satisfied: text-unidecode>=1.3 in /usr/local/lib/python3.6/dist-packages (from python-slugify->kaggle) (1.3)

III. Kaggle Token 다운로드

  • Kaggle에서 API Token을 다운로드 받는다.
  • [Kaggle]-[My Account]-[API]-[Create New API Token]을 누르면 kaggle.json 파일이 다운로드 된다.
  • 이 파일을 바탕화면에 옮긴 뒤, 아래 코드를 실행 시킨다.
from google.colab import files
uploaded = files.upload()
for fn in uploaded.keys():
  print('uploaded file "{name}" with length {length} bytes'.format(
      name=fn, length=len(uploaded[fn])))
  
# kaggle.json을 아래 폴더로 옮긴 뒤, file을 사용할 수 있도록 권한을 부여한다. 
!mkdir -p ~/.kaggle/ && mv kaggle.json ~/.kaggle/ && chmod 600 ~/.kaggle/kaggle.json

Upload widget is only available when the cell has been executed in the current browser session. Please rerun this cell to enable.

Chapter 1.6 Google Colab with Kaggle

강의 홍보

I. 개요

  • 데이터 시각화와 변환에 대해 짧게 익혔다면 바로 실전 데이터를 활용한다.
  • 이론이 조금 부족하게 느껴질 수 있지만, 모든 것을 다 알려드릴 수는 없다.
    • 결국 공부는 스스로 해야 한다.
  • 이 강의의 목적이 Kaggle 데이터를 활용한 Python 포트폴리오 제작 강의임을 잊지 말자.

II. Kaggle KPI 설치

  • Google Colab에서 Kaggle API를 불러오려면 다음 소스코드를 실행한다.
!pip install kaggle
Requirement already satisfied: kaggle in /usr/local/lib/python3.6/dist-packages (1.5.6)
Requirement already satisfied: python-slugify in /usr/local/lib/python3.6/dist-packages (from kaggle) (4.0.0)
Requirement already satisfied: certifi in /usr/local/lib/python3.6/dist-packages (from kaggle) (2020.4.5.1)
Requirement already satisfied: python-dateutil in /usr/local/lib/python3.6/dist-packages (from kaggle) (2.8.1)
Requirement already satisfied: six>=1.10 in /usr/local/lib/python3.6/dist-packages (from kaggle) (1.12.0)
Requirement already satisfied: requests in /usr/local/lib/python3.6/dist-packages (from kaggle) (2.23.0)
Requirement already satisfied: tqdm in /usr/local/lib/python3.6/dist-packages (from kaggle) (4.41.1)
Requirement already satisfied: urllib3<1.25,>=1.21.1 in /usr/local/lib/python3.6/dist-packages (from kaggle) (1.24.3)
Requirement already satisfied: text-unidecode>=1.3 in /usr/local/lib/python3.6/dist-packages (from python-slugify->kaggle) (1.3)
Requirement already satisfied: idna<3,>=2.5 in /usr/local/lib/python3.6/dist-packages (from requests->kaggle) (2.9)
Requirement already satisfied: chardet<4,>=3.0.2 in /usr/local/lib/python3.6/dist-packages (from requests->kaggle) (3.0.4)

III. Kaggle Token 다운로드

  • Kaggle에서 API Token을 다운로드 받는다.
  • [Kaggle]-[My Account]-[API]-[Create New API Token]을 누르면 kaggle.json 파일이 다운로드 된다.
  • 이 파일을 바탕화면에 옮긴 뒤, 아래 코드를 실행 시킨다.

Google Colab with R

I. 들어가며

  • 빅데이터 시대에 맞춰서 다양한 툴이 나오는 가운데, Google Colab은 가히 혁명적이라 할 수 있다.
  • 과거 높은 사양의 컴퓨터에서만 수행할 수 있었던 머신러닝과 딥러닝을 구글 코랩의 환경에서 무료로 배울 수 있는 기회를 구글이 제공하기 시작했다.
  • 간단하게 아래 소스코드를 실행하여 CPU와 GPU의 연산속도를 비교 해보자.

II. Google Colab with R

  • Google Colab은 매우 편리하다. 실제 강의를 시작하면서 파이썬 관련 모든 강의안은 Google Colab으로 제작중이다.
  • 문제는 현재로써는 Google Colab만 지원한다는 점이다.
  • RStudio가 개발용으로 매우 훌륭한 도구이지만, 교육 목적으로는 조금 부족한 감이 있다. (UI 관점에서)
  • 일단 환경이 다르면 강의하는 입장에서는 여러가지로 어렵다.
  • 그래서 이번에 온라인 Tutorial을 제작하면서, Google Colab에서 R을 실행하고 또한 이를 바탕으로 강의를 제작하기로 했다.

III. Set up

  • 다음 소스코드를 그대로 실행한다.
%load_ext rpy2.ipython
The rpy2.ipython extension is already loaded. To reload it, use:
  %reload_ext rpy2.ipython
  • 간단한 EDAJupyter에서 실행할 수 있다.

IV. R 소스코드 실행

  • 이제 간단하게 R 소스코드를 실행해보자.
  • 이 때, 임시적으로 %%R 매직 command를 활용한다.

(1) 패키지 설치

  • R에서 필요한 필수 패키지를 설치한다.
  • EDA를 위한 tidyverse 패키지와 머신러닝을 위한 caret패키지를 설치한다.
%%R
# 1. 패키지가 설치 function
install_pkgs <- function(pkg){
  new.pkg <- pkg[!(pkg %in% installed.packages()[, "Package"])]
  if (length(new.pkg)) 
    install.packages(new.pkg, dependencies = TRUE)
  sapply(pkg, require, character.only = TRUE)
}

pkgs <- c("tidyverse", "nycflights13", "mlbench")
install_pkgs(pkgs)
R[write to console]: Installing packages into ‘/usr/local/lib/R/site-library’
(as ‘lib’ is unspecified)

R[write to console]: trying URL 'https://cran.rstudio.com/src/contrib/nycflights13_1.0.1.tar.gz'
.
.

   tidyverse nycflights13      mlbench 
        TRUE         TRUE         TRUE 

(2) EDA with tidyverse

  • tidyverse 패키지를 활용하여 간단한 EDA를 작업해보자.
%%R
nycflights13::flights %>% 
  mutate(
    cancelled = is.na(dep_time),
    sched_hour = sched_dep_time %/% 100,
    sched_min = sched_dep_time %% 100,
    sched_dep_time = sched_hour + sched_min / 60
  ) %>% 
  ggplot(mapping = aes(sched_dep_time)) + 
    geom_freqpoly(mapping = aes(colour = cancelled), binwidth = 1/4)

png

Google Colab Intro

강의 홍보

I. 들어가며

  • 빅데이터 시대에 맞춰서 다양한 툴이 나오는 가운데, Google Colab은 가히 혁명적이라 할 수 있다.
  • 과거 높은 사양의 컴퓨터에서만 수행할 수 있었던 머신러닝과 딥러닝을 구글 코랩의 환경에서 무료로 배울 수 있는 기회를 구글이 제공하기 시작했다.
  • 간단하게 아래 소스코드를 실행하여 CPU와 GPU의 연산속도를 비교 해보자.

II. Data Transformation 예제

  • 이제 간단하게 데이터 가공의 예를 실습해보자.

(1) 딕셔너리에서 시리즈로 변환하기

  • 다음의 소스코드를 실행하여 딕셔너리에서 시리즈로 변환하는 것을 실습해보자.
# pandas 불러오기
import pandas as pd

# key:value 형태로 딕셔너리를 만들고 temp_dic으로 저장
temp_dic = {'evan': 30, 'chloe': 27}
print(temp_dic)
{'evan': 30, 'chloe': 27}
# 시리즈로 변환하고 출력값 확인
data = pd.Series(temp_dic)
print(data)
evan     30
chloe    27
dtype: int64
  • 위 출력값에서 인덱스는 evanchloe이다.

(2) 리스트에서 시리즈로 변환하기

  • 이번에는 리스트에서 시리즈로 변환한다. 이 때 출력값의 인덱스가 어떻게 나타나는지 확인해본다.
import pandas as pd
temp_list = ['2020-05-29', 1.11, '가나다', 'ABC', 100, True]
data = pd.Series(temp_list)
print(data)
0    2020-05-29
1          1.11
2           가나다
3           ABC
4           100
5          True
dtype: object
  • 이번에는 인덱스의 값이 자동으로 0부터 시작하는 것을 알 수 있다.

III. Data Visualisation 예제

  • 이번에는 간단하게 시각화를 작성해본다.
import numpy as np
import matplotlib.pyplot as plt

N = 5
menMeans = (20, 35, 30, 35, 27)
womenMeans = (25, 32, 34, 20, 25)
menStd = (2, 3, 4, 1, 2)
womenStd = (3, 5, 2, 3, 3)
ind = np.arange(N)    # the x locations for the groups
width = 0.35       # the width of the bars: can also be len(x) sequence

p1 = plt.bar(ind, menMeans, width, yerr=menStd)
p2 = plt.bar(ind, womenMeans, width,
             bottom=menMeans, yerr=womenStd)

plt.ylabel('Scores')
plt.title('Scores by group and gender')
plt.xticks(ind, ('G1', 'G2', 'G3', 'G4', 'G5'))
plt.yticks(np.arange(0, 81, 10))
plt.legend((p1[0], p2[0]), ('Men', 'Women'))

plt.show()

png

Kakao Arena 3 EDA on Google Colab

공지

제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 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