티스토리의 편리함은 종종 글을 올려주는데 도움을 주었지만, 개발블로그로 관리할 것의 고민은 늘 있었다. 블로그도 블로그지만, 책을 출판하고 싶은 욕심이 있었다. 

 

종종 개발블로그를 보아왔지만, 개발블로거 보다는 사람들에게 보다 쉽게 데이터 분석을 알려줄 수 있는 Tools 소개하는 책을 출판하고 싶은 욕심은 늘 있어왔다. 

 

기존에 회사를 다닐 때는 원치 않는 일도 종종 해서, 개발블로그를 작성 및 관리할 기회가 없었지만, 앞으로는 이쪽 분야로만 계속 일을 해야 하니, 전통 통계, 머신러닝, 딥러닝, 시각화 등 빅데이터와 관련된 종합적인 글을 주기적으로 쓰는데 주안점을 두려고 한다. 

 

티스토리는 아마 백업용으로 관리가 되지 않을까 싶다. 티스토리 나름의 편리함이 있기 때문이다. 

 

그럼 시작해보자. 


Reference

  1. 블로그 구축기 1 (Hugo github.io). (2019, February 22). Retrieved March 14, 2020, from https://ialy1595.github.io/post/blog-construct-1/

  2. Integerous. (2020, March 12). Integerous/Integerous.github.io. Retrieved March 14, 2020, from https://github.com/Integerous/Integerous.github.io

  3. Korea, D. T. (2019, January 30). GitHub Pages를 이용한 기술 블로그 제작 후기. Retrieved from https://medium.com/deliverytechkorea/github-pages%EB%A5%BC-%EC%9D%B4%EC%9A%A9%ED%95%9C-%EA%B8%B0%EC%88%A0-%EB%B8%94%EB%A1%9C%EA%B7%B8-%EC%A0%9C%EC%9E%91-%ED%9B%84%EA%B8%B0-77ce4b5e5564

  4. kim, yoj. (2018, September 17). Hugo와 Github Pages를 이용한 기술 블로그 만들기 (1). Retrieved March 14, 2020, from https://yojkim.me/posts/how-to-make-blog-with-hugo/

 

블로그 구축기 1 (Hugo + github.io) | ialy's blog

22 Feb 2019, 20:07 블로그 구축기 1 (Hugo + github.io)

ialy1595.github.io

 

Integerous/Integerous.github.io

:memo: Hugo로 github.io 블로그 만들기. Contribute to Integerous/Integerous.github.io development by creating an account on GitHub.

github.com

 

GitHub Pages를 이용한 기술 블로그 제작 후기

개발자와 디자이너 부부의 첫 공식 작업 — 신범철, iOS Developer

medium.com

 

Hugo와 Github Pages를 이용한 기술 블로그 만들기 (1) | yojkim dev.

최근들어서 공부한 것에 대한 기록물이 필요하다는 사실을 뼈저리게 깨닫게 되었고 기술(?) 및 기타 활동을 적는 블로그 활동을 다시 시작해보려했다. 이전에 블로그를 구성했었을때는 Github pages와 기본적으로 지원하는 jekyll을 활용해서 구성해보았었는데 이전에 jekyll을 한 번 사용해봤으니 다른걸 해보고 싶다는 생각에 이번에는 hugo를 활용해서 블로그를 구성했고 여러분이 보고 있는 이 블로그가 바로 그 결과물이다. Homebrew를 이용해서

yojkim.me

1, 2번 글을 통해서 대략적인 감을 익혔고, 3번 글을 통해서 Hugo Vs. Jekyll 차이점을 알 수 있었고, Ruby라는 환경설정을 다시 해야 하는 번잡스러움을 피하기 위해 Hugo를 선택하는데 주저함이 없었다. 그러나, 자동배포에 관심이 많으신 '개발자 (Developer)'분들에게는 오히려 Jekyll이 더 낫지 않나 싶습니다 (사실 잘 모르겠다). 마지막 4번글을 통해서 Mac에서 Hugo를 활용한 github.io 개발 블로그를 만들었다. 


Why Hugo?

큰 이유는 없다. 편하다고 한다. Go 언어가 기반인 것은 흥미가 있다. 나의 첫 언어인 R 다음에 선택할 언어로 늘 항상 Go를 염두에 두고 있기 때문이다. Okay. Let's get it. 


Installation

당연한 얘기이지만, github 블로그를 만드는 것이니, 당연히 git이 설치가 되어야 한다. git 설치는 어렵지 않으니 Pass. git 환경구축은 여기서는 다루지는 않겠다. git이 처음이신 분들은... (어떡하지? 나중에 한번 작성해서 공유하겠습니다.)

brew install hugo

Homebrew를 이용해서 매우 간편하게 hugo를 설치할 수 있다. (macOS 기준)

brew가 없어요? 여기 클릭하세요! Homebrew

 

Homebrew

The Missing Package Manager for macOS (or Linux).

brew.sh


Check If hugo is correctly installed

 

~ % which hugo
/usr/local/bin/hugo
# show your version
~ % ls -l $( which hugo )
lrwxr-xr-x 1 your_user_name admin 30 Mar 14 21:03 /usr/local/bin/hugo -> ../Cellar/hugo/0.67.0/bin/hugo

 

위 소스 코드가 정상적으로 나온다면 잘 설치가 된 것이다.


Create New Site

 

엥? 별다른 설정 없이 바로 New Site를 만들라고 한다. 일단, 기본 파일에 만들수는 없으니, 새로운 폴더를 만들고 거기에서 다음 명령어를 실행해본다. 난 다음과 같이 만들었다.

 

~ % cd Documents
Documents % mkdir hugoBlog
Documents % cd hugoBlog
hugoBlog % hugo new site name_of_project

 

name_of_project 대신에 난 data_science_with_evan 이라 명했다. 

 

 

hugo new site name_of_project 명령어를 입력하면 여러 형태의 파일이 구성된다. 폴더 트리구조는 아래와 같다. 

 

.
└── data_science_with_evan
├── archetypes
│   └── default.md
├── config.toml
├── content
├── data
├── layouts
├── static
└── themes

 


Directory Structure

디렉토리 구조에 대한 자세한 설명은 아래 싸이트에서 확인하기를 바란다. 추후에 기회가 되면 번역해서 작업하도록 한다. 오늘은 일단 싸이트 구경좀 하자~ ^^

 

https://gohugo.io/getting-started/directory-structure/

 

Directory Structure

Hugo's CLI scaffolds a project directory structure and then takes that single directory and uses it as the input to create a complete website.

gohugo.io


config.toml

여기에서 중요한 것은 사실 이거다. config.toml 파일을 열면 아래와 같이 구성되어 있다. 

 

baseURL = "http://example.org/"
languageCode = "en-us"
title = "My New Hugo Site"

 

그런데, 처음에 웹사이트 만들때는 기본으로 만들 것이니, 일단 건드리지 않는다.


Theme Settings

hugo에는 다양한 종류의 웹사이트 테마가 있다. 블로그를 운영해보신 분들은 아시겠지만, 기본적으로 제공하는 테마가 있는데, hugo도 제공한다. 

 

https://themes.gohugo.io/

불러오는 중입니다...

다양한 종류의 테마가 있는데, 여기에서 하나 마음에 드는 것을 고른다. 난 Techdoc이란 테마를 설정했다. 

 


개인 취향이니 본인이 원하는 걸 선택하면 될 것 같다. 이 다음이 중요하다. 다운로드 버튼을 클릭하면 github 화면으로 이동하는데 거기에서, git 주소를 복사(copy)한다. 다시 프로젝트로 와서 /themes/에 경로를 지정한다. 

themes % git clone https://github.com/thingsym/hugo-theme-techdoc.git

tree 구조는 아래서 보는 것처럼 매우 많다. 

 

.
└── hugo-theme-techdoc
├── LICENSE.md
├── README.md
├── archetypes
│   └── default.md
├── exampleSite
│   ├── config.toml
│   ├── content
│   │   ├── _index.md
│   │   ├── about.md
│   │   ├── archives
│   │   │   ├── hello_world.md
│   │   │   ├── hello_world1.md
│   │   │   └── hello_world2.md
│   │   ├── blog
│   │   │   ├── hello_world.md
│   │   │   ├── hello_world1.md
│   │   │   └── hello_world2.md
│   │   ├── chapter1
│   │   │   ├── 1.md
│   │   │   ├── 2.md
│   │   │   ├── 3.md
│   │   │   ├── 4.md
│   │   │   └── _index.md
│   │   ├── chapter2
│   │   │   ├── 1.md
│   │   │   ├── 2.md
│   │   │   ├── 3.md
│   │   │   ├── 4.md
│   │   │   └── _index.md
│   │   ├── chapter3
│   │   │   ├── 1.md
│   │   │   ├── 3.md
│   │   │   ├── 4.md
│   │   │   ├── _index.md
│   │   │   └── chapter3-2
│   │   │   ├── 1.md
│   │   │   ├── 2.md
│   │   │   ├── 3.md
│   │   │   ├── 4.md
│   │   │   └── _index.md
│   │   ├── entry
│   │   │   ├── hello_world.md
│   │   │   ├── hello_world1.md
│   │   │   └── hello_world2.md
│   │   ├── getting-started
│   │   │   ├── _index.md
│   │   │   ├── configuration.md
│   │   │   ├── installation.md
│   │   │   └── screenshot.md
│   │   ├── hello_world.md
│   │   ├── post
│   │   │   ├── creating-a-new-theme.md
│   │   │   ├── goisforlovers.md
│   │   │   ├── hugoisforlovers.md
│   │   │   └── migrate-from-jekyll.md
│   │   ├── posts
│   │   │   └── hello_world.md
│   │   └── sample
│   │   ├── _index.md
│   │   ├── build-in-shortcodes.md
│   │   ├── custom-shortcodes.md
│   │   └── table-of-contents.md
│   └── static
│   └── images
│   ├── og-image.png
│   └── pexels-photo-196666.jpeg
├── gulpfile.js
├── images
│   ├── screenshot-edit-link.png
│   ├── screenshot-open-menu.png
│   ├── screenshot-slide-menu.gif
│   ├── screenshot-theme-color.png
│   ├── screenshot.png
│   └── tn.png
├── layouts
│   ├── 404.html
│   ├── _default
│   │   ├── baseof.html
│   │   ├── list.html
│   │   └── single.html
│   ├── blog
│   │   ├── li.html
│   │   ├── list.html
│   │   ├── single.html
│   │   └── summary.html
│   ├── index.html
│   ├── partials
│   │   ├── content-footer.html
│   │   ├── custom-css.html
│   │   ├── custom-head.html
│   │   ├── edit-meta.html
│   │   ├── edit-page.html
│   │   ├── footer.html
│   │   ├── global-menu.html
│   │   ├── head.html
│   │   ├── last-updated.html
│   │   ├── menu
│   │   │   ├── open-menu.html
│   │   │   └── slide-menu.html
│   │   ├── meta
│   │   │   ├── chroma.html
│   │   │   ├── google-analytics-async.html
│   │   │   ├── google-site-verification.html
│   │   │   └── tag-manager.html
│   │   ├── notification.html
│   │   ├── pagination.html
│   │   ├── powered.html
│   │   ├── prepend-body.html
│   │   ├── sidebar-footer.html
│   │   ├── sidebar.html
│   │   ├── site-header.html
│   │   └── table-of-contents.html
│   ├── posts
│   │   ├── list.html
│   │   └── single.html
│   └── shortcodes
│   ├── button.html
│   └── panel.html
├── package-lock.json
├── package.json
├── src
│   ├── js
│   │   ├── jquery.backtothetop
│   │   │   ├── jquery.backtothetop.js
│   │   │   └── jquery.backtothetop.min.js
│   │   ├── keydown-nav.js
│   │   ├── main.js
│   │   └── sidebar-menu.js
│   └── scss
│   ├── _component.scss
│   ├── _foundation.scss
│   ├── _function.scss
│   ├── _project.scss
│   ├── _structure.scss
│   ├── _variable.scss
│   ├── chroma.scss
│   ├── foundation
│   │   ├── _element.scss
│   │   ├── _normalize.scss
│   │   ├── _reset.scss
│   │   └── _stack.scss
│   ├── function
│   │   ├── _calc-font-size.scss
│   │   ├── _calc-stack.scss
│   │   ├── _contrast-color.scss
│   │   └── _strip-unit.scss
│   └── theme.scss
├── static
│   ├── css
│   │   ├── chroma.css
│   │   ├── chroma.min.css
│   │   ├── theme.css
│   │   └── theme.min.css
│   └── js
│   └── bundle.js
├── theme.toml
└── webpack.config.js
35 directories, 123 files

config.toml

여기에서 중요한 것은 사실 이거다. /themes/hugo-theme-techdoc 폴더가 있는지 확인한다. 다른 테마를 설정했다면, 당연히 다른 이름이 들어갈 것이니 체크한다. 

 

그 다음 해야할 일은 config.toml 파일을 열고 theme = "hugo-theme-techdoc" 입력한다. 

baseURL = "http://example.org/"
languageCode = "en-us"
title = "Data Science | Evan Jung"
themes = "hugo-theme-techdoc"

위와 같이 수정했다. 

Server

수정이 끝나고 나면 한번 localhost에서 실행이 되는지 확인해보자. 보통 이러한 테마에는 README.md 파일이 있는데, 서버 실행에 대한 설명이 나와 있다. 

 

내 README.md 파일에는 아래와 같이 있었다. 

 

### Preview site
To preview your site, run Hugo's built-in local server.
```
hugo server -t hugo-theme-techdoc
```
Browse site on http://localhost:1313

 

위 서식대로 따라해본다. 이 때, 디렉토리는 개인 프로젝트(나의 경우 data_science_with_evan) 하단에서 실행해야 한다는 점을 유의하자

data_science_with_evan % hugo server -t hugo-theme-techdoc

그다음 http://localhost:1313 실행하면 아래와 같은 화면이 나왔다. 

 

오! 신기하다! 

그 다음 진행해야 하는 것이 Content Organization인데, 이 부분은 다음에 한다. 

아직! github.io 형태의 웹사이트가 만들어진 것은 아니다! 

 

역시 뭐든지 글쓰면서 동시 병행하니, 3-4시간만에 뚝딱 만들어지는 건 없나보다! 그럼 내일 계속 만들어봅시다. 

 

다음편에 계속

불러오는 중입니다...

 

# ------------------
# 본 장은 R에서 Keras를 실습하는 과정입니다.  
# 딥러닝에 대한 자세한 이론 설명은 별도로 하지 않습니다. 
# 추후 딥러닝 강좌 개설 시, 중요 개념들에 대해 짚고 넘어갑니다. 
# ------------------


1단계: 패키지 설치

R에서 패키지 설치 진행은 아래와 같이 진행하시면 됩니다. 

파이썬이 없는 경우 자동으로 설치를 도와주기 때문에 큰 걱정은 안하셔도 됩니다. 

 

# 패키지는 H2O와 다르게 쉽습니다.
devtools::install_github("rstudio/keras")
library(keras)

R의 다른 패키지와 달리, keras는 실행함수가 하나 더 있습니다. 

# 텐서플로우 설치: tensorflow를 벡엔드로 사용하기 때문.
install_keras()
Collecting package metadata (current_repodata.json): ...working... done
Solving environment: ...working... done
# All requested packages already installed.
==> WARNING: A newer version of conda exists. <==
current version: 4.7.12
latest version: 4.8.2
Please update conda by running
$ conda update -n base -c defaults conda
Requirement already up-to-date: tensorflow==2.0.0 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (2.0.0)
Requirement already up-to-date: keras in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (2.3.1)
Requirement already up-to-date: tensorflow-hub in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (0.7.0)
Requirement already up-to-date: h5py in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (2.10.0)
Requirement already up-to-date: pyyaml in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (5.3)
Requirement already up-to-date: requests in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (2.23.0)
Requirement already up-to-date: Pillow in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (7.0.0)
Requirement already up-to-date: scipy in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (1.4.1)
Requirement already satisfied, skipping upgrade: wheel>=0.26 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (0.34.2)
Requirement already satisfied, skipping upgrade: gast==0.2.2 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (0.2.2)
Requirement already satisfied, skipping upgrade: keras-preprocessing>=1.0.5 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (1.1.0)
Requirement already satisfied, skipping upgrade: opt-einsum>=2.3.2 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (3.2.0)
Requirement already satisfied, skipping upgrade: termcolor>=1.1.0 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (1.1.0)
Requirement already satisfied, skipping upgrade: google-pasta>=0.1.6 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (0.1.8)
Requirement already satisfied, skipping upgrade: tensorboard<2.1.0,>=2.0.0 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (2.0.2)
Requirement already satisfied, skipping upgrade: tensorflow-estimator<2.1.0,>=2.0.0 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (2.0.1)
Requirement already satisfied, skipping upgrade: wrapt>=1.11.1 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (1.12.1)
Requirement already satisfied, skipping upgrade: grpcio>=1.8.6 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (1.27.2)
Requirement already satisfied, skipping upgrade: keras-applications>=1.0.8 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (1.0.8)
Requirement already satisfied, skipping upgrade: numpy<2.0,>=1.16.0 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (1.18.1)
Requirement already satisfied, skipping upgrade: six>=1.10.0 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (1.14.0)
Requirement already satisfied, skipping upgrade: astor>=0.6.0 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (0.8.1)
Requirement already satisfied, skipping upgrade: absl-py>=0.7.0 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (0.9.0)
Requirement already satisfied, skipping upgrade: protobuf>=3.6.1 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorflow==2.0.0) (3.11.3)
Requirement already satisfied, skipping upgrade: chardet<4,>=3.0.2 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from requests) (3.0.4)
Requirement already satisfied, skipping upgrade: idna<3,>=2.5 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from requests) (2.9)
Requirement already satisfied, skipping upgrade: urllib3!=1.25.0,!=1.25.1,<1.26,>=1.21.1 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from requests) (1.25.8)
Requirement already satisfied, skipping upgrade: certifi>=2017.4.17 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from requests) (2019.11.28)
Requirement already satisfied, skipping upgrade: setuptools>=41.0.0 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorboard<2.1.0,>=2.0.0->tensorflow==2.0.0) (45.2.0.post20200210)
Requirement already satisfied, skipping upgrade: markdown>=2.6.8 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorboard<2.1.0,>=2.0.0->tensorflow==2.0.0) (3.2.1)
Requirement already satisfied, skipping upgrade: werkzeug>=0.11.15 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorboard<2.1.0,>=2.0.0->tensorflow==2.0.0) (1.0.0)
Requirement already satisfied, skipping upgrade: google-auth-oauthlib<0.5,>=0.4.1 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorboard<2.1.0,>=2.0.0->tensorflow==2.0.0) (0.4.1)
Requirement already satisfied, skipping upgrade: google-auth<2,>=1.6.3 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from tensorboard<2.1.0,>=2.0.0->tensorflow==2.0.0) (1.11.2)
Requirement already satisfied, skipping upgrade: requests-oauthlib>=0.7.0 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.1.0,>=2.0.0->tensorflow==2.0.0) (1.3.0)
Requirement already satisfied, skipping upgrade: rsa<4.1,>=3.1.4 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.1.0,>=2.0.0->tensorflow==2.0.0) (4.0)
Requirement already satisfied, skipping upgrade: pyasn1-modules>=0.2.1 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.1.0,>=2.0.0->tensorflow==2.0.0) (0.2.8)
Requirement already satisfied, skipping upgrade: cachetools<5.0,>=2.0.0 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from google-auth<2,>=1.6.3->tensorboard<2.1.0,>=2.0.0->tensorflow==2.0.0) (4.0.0)
Requirement already satisfied, skipping upgrade: oauthlib>=3.0.0 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from requests-oauthlib>=0.7.0->google-auth-oauthlib<0.5,>=0.4.1->tensorboard<2.1.0,>=2.0.0->tensorflow==2.0.0) (3.1.0)
Requirement already satisfied, skipping upgrade: pyasn1>=0.1.3 in /Users/jihoonjung/Library/r-miniconda/envs/r-reticulate/lib/python3.6/site-packages (from rsa<4.1,>=3.1.4->google-auth<2,>=1.6.3->tensorboard<2.1.0,>=2.0.0->tensorflow==2.0.0) (0.4.8)
Installation complete.

위와 같은 표시가 나오면 R에서도 keras를 사용할 수 있습니다. 


2단계: 데이터 불러오기

간단하게 iris 데이터를 활용하도록 합니다. iris 데이터를 활용하는 이유는, R은 데이터프레임에 최적화된 언어이고, 대부분의 사용자가 데이터프레임에 익숙합니다. 따라서, 데이터프레임 데이터를 어떻게 적용하는 것이 궁금하실 것 같아서 일부러 쉬운 데이터를 적용했습니다. 

 

R에서도 당연히 이미지 분류 등이 가능합니다. 

#### 2단계: 데이터 불러오기 ####
iris <- iris

3단계: 간단하게 상관관계 그래프 그리기

사실 여기는 굳이 하지 않으셔도 됩니다. 다만, 분석가는 늘 데이터를 시각화해서 데이터의 관계 등을 확인하는 EDA(탐색적 자료 분석)을 꼭 진행하는 걸 권장합니다. 

#### 3단계: 상관관계 그래프 작성하기 (옵션) ####
library(corrplot)
# 수치형 데이터를 상관관계수로 변환하기
M <- cor(iris[,1:4])
# 상관관계 그래프 작성하기
corrplot(M, method="circle")

 

이렇게 나오면 됩니다. 


4단계: 데이터 전처리 및 가공

 

여기가 핵심입니다. 분류 모형이지만, 딥러닝은 행렬로 연산하기 때문에, 매트릭스 형태로 변환해야 합니다. 또한 데이터 정규화도 같이 진행합니다. 본 장에서는 왜 이러한 작업을 하는지는 구체적으로 설명하지 않습니다. 

 

추후 딥러닝 이론은 요약해서 올릴 예정입니다. 

# (1) 데이터프레임을 행렬로 변환 -------------------
# 범주형을 숫자로 바꿔야 한다.
# 딥러닝은 데이터프레임이 아니라 행렬형태로 데이터를 받는다.
iris[,5] <- as.numeric(as.factor(unlist(iris[,5]))) -1
iris <- as.matrix(iris)
dimnames(iris) <- NULL
# (2) 데이터 정규화 -------------------
# keras 패키지에는 normalize 함수가 있다.
iris_x <- normalize(iris[,1:4])
# 정규화가 진행된 데이터를 다시 5 column과 합친 코드이다.
iris_mat <- cbind(iris_x, iris[,5])
head(iris_mat)
# 아래는 결과 값입니다.
[,1] [,2] [,3] [,4] [,5]
[1,] 0.8037728 0.5516088 0.2206435 0.03152050 0
[2,] 0.8281329 0.5070201 0.2366094 0.03380134 0
[3,] 0.8053331 0.5483119 0.2227517 0.03426949 0
[4,] 0.8000302 0.5391508 0.2608794 0.03478392 0
[5,] 0.7909650 0.5694948 0.2214702 0.03163860 0
[6,] 0.7841750 0.5663486 0.2468699 0.05808704 0

5단계: 딥러닝 모형 데이터셋 분리

# 데이터 셋 나누기 index
ind <- sample(2, nrow(iris_mat), replace=TRUE, prob=c(0.67, 0.33))
# 모형 설계행렬
iris.training <- iris_mat[ind==1, 1:4]
iris.test <- iris_mat[ind==2, 1:4]
# 모형 예측변수
iris.trainingtarget <- iris_mat[ind==1, 5]
iris.testtarget <- iris_mat[ind==2, 5]
# One-Hot 인코딩: 훈련예측변수
iris.trainLabels <- to_categorical(iris.trainingtarget)
# One-Hot 인코딩: 검증예측변수
iris.testLabels <- to_categorical(iris.testtarget)

6단계: 딥러닝 모형 개발

데이터에 적합한 딥러닝 모형을 적용해야 하는데 신경망 계층(layer)은 몇층으로 할지, 노드는 몇개로 할지, 활성화(activation) 함수는 무엇으로 할지, 하이퍼 모수 학습률(learning rate)은 어떻게 정할지, 이렇게 다양한 조합이 모형의 성능에 영향을 미치게 된다. 그런 점에서 케라스는 모형자체에 개발자가 집중할 수 있도록 함으로써 큰 도움을 주고 있다.

 

일단 잘 모르겠다. 

 

그냥 한번 만들어 보자. 

set.seed(777)
# (1) 모형 초기화
model <- keras_model_sequential()
# 여기에 우선적으로 아래와 같이 신경망 계층을 만듭니다.
# output 값이 3개입니다. (versicolor, virginica, setosa)
# 8 hidden notes를 만들었고, input shape = 4개로 만들었는데,
# 이유는 4개의 column이 존재하기 때문입니다.
model %>%
layer_dense(units = 8, activation = 'relu', input_shape = c(4)) %>%
layer_dense(units = 3, activation = 'softmax')
2020-03-12 22:46:36.235402: I tensorflow/core/platform/cpu_feature_guard.cc:142] Your CPU supports instructions that this TensorFlow binary was not compiled to use: AVX2 FMA
2020-03-12 22:46:36.297796: I tensorflow/compiler/xla/service/service.cc:168] XLA service 0x7fa12eb3fe50 executing computations on platform Host. Devices:
2020-03-12 22:46:36.297819: I tensorflow/compiler/xla/service/service.cc:175] StreamExecutor device (0): Host, Default Version
# 모형 요약
summary(model)
Model: "sequential"
_______________________________________________________________________________
Layer (type) Output Shape Param #
===============================================================================
dense (Dense) (None, 8) 40
_______________________________________________________________________________
dense_1 (Dense) (None, 3) 27
===============================================================================
Total params: 67
Trainable params: 67
Non-trainable params: 0
_______________________________________________________________________________
# 모형 configuration
get_config(model)
{'name': 'sequential', 'layers': ...} # 직접 콘솔에서 확인 바랍니다.
# layer configuration
get_layer(model, index = 1)
<tensorflow.python.keras.layers.core.Dense>
# List the model's layers
model$layers
[[1]]
<tensorflow.python.keras.layers.core.Dense>
[[2]]
<tensorflow.python.keras.layers.core.Dense>
# List the input tensors
model$inputs
[[1]]
Tensor("dense_input:0", shape=(None, 4), dtype=float32)
# List the output tensors
model$outputs
[[1]]
Tensor("dense_1/Identity:0", shape=(None, 3), dtype=float32)
  • output 값이 3개입니다. (versicolor, virginica, setosa)
  • 8 hidden notes를 만들었고, input shape = 4개로 만들었는데,
  • 이유는 4개의 column이 존재하기 때문입니다. 

7단계: 딥러닝 모형 컴파일

  • categorical_crossentropy는 다중 분류를 의미합니다. 
  • 만약 이중분류를 하고 싶다면, 'binary_crossentropy' 입력하면 됩니다.
  • 가장 많이 사용되는 최적화 알고리즘은 SGD (Stochastic Gradient Descent), ADAM 및 RMSprop입니다. 
model %>% compile(
loss = 'categorical_crossentropy',
optimizer = 'adam',
metrics = 'accuracy'
)

8단계: 딥러닝 모형 적합

드디어 우리가 하려고 하는 것이 나왔습니다. 시간이 조금 걸립니다. 멋진 그래프가 움직이는 것을 보는 경험을 할 것입니다. 저는 처음에 조금 신기했습니다. 

model %>% fit(
iris.training,
iris.trainLabels,
epochs = 500,
batch_size = 5,
validation_split = 0.1
)

궁금하신 분만 보세요, 약 3분 45초 러닝타임 나옵니다. iris 데이터만 해도 3분 45초이니.. 다른 큰 데이터는 로컬 환경에서는 못할 듯 싶습니다. (참고로 맥북 에어로 작업중입니다!) 


9단계: 예측 모형 테스트

# 테스트 데이터를 활용한 예측값 산출
classes <- model %>% predict_classes(iris.test, batch_size = 128)
# 혼동행렬
table(iris.testtarget, classes)
# 결과표
classes
iris.testtarget 0 1 2
0 19 0 0
1 0 13 2
2 0 1 13

10단계: 모형 평가

# 테스트 데이터를 기반으로 모형을 평가한다.
score <- model %>% evaluate(iris.test, iris.testLabels, batch_size = 128)
# loss 및 accuracy가 산출 된 것을 확인할 수 있다.
print(score)
$loss
[1] 0.1443771
$accuracy
[1] 0.9375

 

자세한 내용은 keras 홈페이지에 참고하세요. https://keras.io/

 

Home - Keras Documentation

Keras: The Python Deep Learning library You have just found Keras. Keras is a high-level neural networks API, written in Python and capable of running on top of TensorFlow, CNTK, or Theano. It was developed with a focus on enabling fast experimentation. Be

keras.io


여기서부터 광고합니다. 

 

- 강사가 필요한 곳은 언제든지 연락 주세요. (2020년 6월부터 가능)

- 온라인 강의 제작도 가능합니다.

- Kaggle 데이터 시각화 위주로 공동으로 책 쓰실 분 찾습니다.

- 안타깝지만 개인 과외는 하지 않습니다!

 

연락처: j2hoon85@gmail.com

 

--- 커리큘럼은 아래와 같습니다. ---

* 소스코드 및 강의안 (PPT) 모두 준비 완료

1일차: 데이터 전처리와 시각화

- R & RStudio 설치 및 CRAN 생태계 설명

- 데이터 전처리: dplyr 활용

- 데이터 시각화: ggplot2 패키지 & 그외 동적 시각화 패키지

*웹크롤링, 몽고DB 연동, shiny 대시보드 연동 커리큘럼도 제작중입니다. 

 

2일차: 기초통계 및 회귀분석 ML모형

- 통계분석: 기술통계분석, 교차분석, 집단간 차이분석, 회귀분석 및 보고서 작성 요령

- 회귀모형개발: 선형회귀, 다중회귀, caret 패키지 활용

*통계분석은 지속적으로 업데이트 될 예정입니다.

 

3일차: 분류모형 및 h2o 패키지 소개

- 이상치 및 결측치 처리

- 이항 및 다항분류

- caret 패키지 & h2o 패키지 활용 모형 개발

 

4일차: 모형성능 향상 및 딥러닝 예제

- 통계적 preProcessing 절차 소개

- Parameter Tuning 절차 및 Sample 소개

- 딥러닝 소개 및 keras and tensorflow 2.0 Sample 튜토리얼

* shiny에서 머신러닝 모형 deploy 하는법도 올 상반기 중으로 준비중입니다 (GCP 서버 활용)

 

2020년은 끝내지 못한 대학원 학위를 마무리해야 합니다. 

 

R/Python 공부며, 강의 준비며 할거 많지만, 학력이 경쟁력인 사회에서는 어쩔 수 없죠!! 학위 논문까지... 영어로 써야하는 과정인 만큼, 영어로 논문 공부하는 사람들을 위해 준비했습니다. 

 

참고로, 현재 보고 있는 책 공유합니다. 

 

 

위 책은 현재 Reference 형태로 쓰고 있습니다. 똑같은 내용이 반복 될 때, 다른 문구는 없는지.. 확인하면서 말이죠, 가장 좋은 건, 사실 외국 논문을 응용하는 게 제일 좋습니다! 

 

저는 현재 모 대학에서 스타트업 성과에 관련된 양적 방법론(Quantitative Research)을 활용한 논문을 작성하고 있습니다. 데이터가 수집되는 대로 분석에 들어갈 예정인데, 추후에 R로 진행하는 논문 통계 영역도 같이 공유 드리도록 하겠습니다 (한 3-4개월 뒤!?).

 

이 책의 이런 비교가 있다. (실제 자연과학 논문을 다루지 않아서 잘 모르겠지만!)

인문과학 자연과학
a considerable amount of much
a majority of  most
a number of many
are of the same opinion agree
at this point in time now
... ...
인문과학은 말이 많다! 자연과학은 말이 적다! (필자 생각)

 

논문 쓰면서 가끔씩 좋은 표현들은 공유하려고 합니다. 

 

 

 

 

 

 

 

 

가끔 대화를 하다보면 주제에서 벗어난 얘기를 할 때가 있죠? 그리고, 아! 주제에서 벗어나려고 한 건 아니었는데.. 하는 경우가 있습니다.

 

이 때 쓰는 표현입니다. 

I didn't mean to get us off topic, sorry. 

 

"I didn't mean to get us off topic with that question about marketing. Let's get back to our meeting."

"마케팅에 대한 질문으로 주제에서 잠깐 벗어났어요. 우리 미팅으로 다시 돌아갑시다."

"I'm sorry, I didn't mean to get us off topic but um.. we need to take a minute to discuss this."
"죄송합니다, 제가 주제에서 벗어나게 하려고 한 것은 아닌데, 잠시 이 문제에 대해 토론할 필요는 있습니다."

+ Recent posts