Settings

데이콘 대회 참여 - 09 스태킹 알고리즘

공지

제 수업을 듣는 사람들이 계속적으로 실습할 수 있도록 강의 파일을 만들었습니다. 늘 도움이 되기를 바라며. 참고했던 교재 및 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
.
.
.
Successfully installed confuse-1.3.0 htmlmin-0.1.12 imagehash-4.1.0 pandas-profiling-2.8.0 phik-0.10.0 tangled-up-in-unicode-0.0.6 tqdm-4.47.0 visions-0.4.4

I. GBM, XGBoost, Lightgbm의 개요 및 실습

  • 부스팅 알고리즘은 여러 개의 약한 학습기(Weak Learner)를 순차적으로 학습-예측하면서 잘못 예측한 데이터에 가중치 부여를 통해 오류 개선하며 학습하는 방식.

Github Project 포트폴리오

개요

  • 본 포스트는 깃허브 프로젝트 관리에 관한 것이다.

I. 프로필 작성하기

  • 이력서에 준하는 프로필 또는 유니크한 것을 살리는 것이 좋다.
  • 깔끔한 정장을 입고, 이쁘게 화장을 하고, 면접을 보러가듯이 인사담당자가 보는 이로 하여금 좋은 인상을 심어줘야 한다.
  • 성명, 이메일, 전화번호 등은 가급적 자세하게 기록해두는 것이 좋다.
  • 프로젝트는 현재 진행중인 Pinned Repositories 상위 3~4개 정도 올려 놓는 것이 좋다.

  • 만약에 현재 기여하는 오픈 소스 리퍼지토리가 있다면 반드시 메인 화면에 고정시킨다.

II. 깃허브 설치 및 연동

  • 잔디밭은 일종의 열정과 성실함을 보여준다.
  • 데이터 싸이언티스트(=개발자)는 매일마다 새로운 것을 배우고 성장해야 한다. 이 업종을 떠나기 전까지는 우리는 매일 조금씩이라도 코딩하고 꾸준히 커밋하는 습관을 길러야 한다.
  • 그런데, 깃허브가 처음이라면 어떻게 해야할까요?

(1) 깃허브 가입하기

(2) 저장소 추가하기

  • 저장소 추가하는 방법은 왼쪽 상단 [create repository]를 선택한다.

데이콘 대회 참여 - 08 세개의 모델

공지

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

데이콘 대회 참여 - 07 두개의 모델

공지

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

데이콘 대회 참여 - 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 인증 절차와 비슷하다.

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