SlideShare a Scribd company logo
누구나 TensorFlow!
J. Kang Ph.D.
누구나 TensorFlow
- Module1 : 파이썬 기초 + 머신러닝 + 텐써 플로우 개요
Jaewook Kang, Ph.D.
jwkang@soundl.ly
Jan. 2018
1
© 2017-2018
Jaewook Kang
All Rights Reserved
누구나 TensorFlow!
J. Kang Ph.D.
 GIST EEC Ph.D. (2015)
 신호처리 과학자, 삽질러
 누구나 TensorFlow Group leader
 https://www.facebook.com/jwkkang
 좋아하는 것:
 통계적 신호처리 / 무선통신 신호처리
 임베디드 오디오 DSP C/C++라이브러리 구현
 머신러닝 기반 오디오 신호처리 알고리즘
 배워서 남주기
2
 대표논문:
Jaewook Kang, et al., "Bayesian Hypothesis Test using Nonparametric Belief Propagation for
Noisy Sparse Recovery," IEEE Trans. on Signal process., Feb. 2015
Jaewook Kang et al., "Fast Signal Separation of 2D Sparse Mixture via Approximate Message-
Passing," IEEE Signal Processing Letters, Nov. 2015
Jaewook Kang (강재욱)
소 개
누구나 TensorFlow!
J. Kang Ph.D.
Contributors to EveryTF Group!
3
Jaewook Kang (Soundlly)
Soonwon Ka (Soundlly) Jihwan Lee (SNU) Cheolyoung Kwak (SNU)
Hyoyoung Jung (GIST) Donghyun Kim (GIST)
누구나 TensorFlow!
J. Kang Ph.D.
Reviewers
 Sun Young Park (Korea Univ.)
 Hongkyong Kim (Korea Aerospace Research Institute, GIST)
 Hansol Kim (GIST)
4
누구나 TensorFlow!
J. Kang Ph.D.
두가지 화두
• 학계와 산업계의 거리
• 지식의 빈부 격차
5
누구나 TensorFlow!
J. Kang Ph.D.
학계와 산업계의 거리
• 학계는 19세기 시스템
• 논문과 학회
• 리뷰프로세스와 퍼브리쉬
• CS 박사학위기간 5년 이상
• 산업계는 21세기 시스템
• 온라인 커뮤니티 & 컨트리뷰터
• 오픈소스 + 개방형 플랫폼
• 블로그
6
누구나 TensorFlow!
J. Kang Ph.D.
학계와 산업계의 거리
• 당신은 둘사이에 어떤 연결고리가 될수 있는가?
• 학계
• 새로운 발견은 대부분 서양학계에서 나온다
• 무선통신, 딥러닝
• 한우물 정신
• 이론적 토대마련, 해석
• 실패와 도전
• 산업계
• 빠른 피드백 사이클
• 머니 머니 머니!: 현실세계에서 효용 == 머니
• 최대한 많은 상호작용
7
누구나 TensorFlow!
J. Kang Ph.D.
지식의 빈부 격차
• 시간에 따라서 지식의 빈부격차가 점점 벌어집니다.
• 세상이 점점 연결됩니다.
• 지식 생산이 점점 효율화 됩니다.
• 지식생산자는 더 영향력을 끼지게 됩니다.
• 지식 소비자는 점점 더 의존적이 됩니다.
8
누구나 TensorFlow!
J. Kang Ph.D.
누구나 TensorFlow!
J. Kang Ph.D.
• 2년전 무엇을 느꼈는가?
• 2년이 지난 이후 무엇이 벌어지고 있는가?
• 무엇을 준비해야하는가?
• 수학
• 코딩
• 머신러닝
10
누구나 TensorFlow!
J. Kang Ph.D.
• 2년전 무엇을 느꼈는가?
• 2년이 지난 이후 무엇이 벌어지고 있는가?
• 무엇을 준비해야하는가?
• 수학: 세상을 설명하는 가장 보편적인 진리
• 코딩: 디지털 문맹이 되지 말자
• 머신러닝: 나 대신 일해주는 시스템
11
누구나 TensorFlow!
J. Kang Ph.D.
나의 선택
• 나는 스타트업이라는 정글로 뛰어들었다.
• 논문 peer 리뷰 보다 빠른 고객/동료 피드백
• 논문 보다 빠른 블로그 (블로그 보다 동영상)
• 특허 보다 쉬운 one more like!
• 효율적인 지식생산 방법론
• 세상을 직접 이롭게 하는 일
12
누구나 TensorFlow!
J. Kang Ph.D.
• 여러분은 지금 어떤 질문을 던지시겠습니까?
• 남은 학위 기간 동안 나는 무엇을 준비해야하는가?
• 나는 세상에 어떤 기여를 하는 사람이 될것 인가?
• 빠른 지식 생산을 위해서 무엇을 고민할 것인가?
• 내 연구를 어떻게 효율화 할것인가?
13
누구나 TensorFlow!
J. Kang Ph.D.
메트릭스의 빨간약
• 믿고 안믿고, 하고 안하고는 여러분의 선택입니다.
• https://www.youtube.com/watch?v=1keotmoOWo4
14
누구나 TensorFlow!
J. Kang Ph.D.
누구나 TensorFlow의 목표
 강의 철학1: 누구나 “머신러닝” 할 수 있다!!
 1) 머신러닝의 기본개념을 수식 머리로 이해한다.
 2) 머신러닝 기본기법을 TensorFlow로 구현할 수 있다.
 3) 수집한 데이터를 파이썬을 통해서 다룰 수 있다.
 4) 내문제에 머신러닝 적용할 수 있다.
 5) 스스로 머신러닝을 더 연구해 보고싶다.
15
누구나 TensorFlow!
J. Kang Ph.D.
누구나 TensorFlow의 목표
 강의 철학2: 당신은 이 강의에서 모든 것을 얻어갈 수 없다!
 1) 머신러닝의 기본개념을 수식 머리로 이해한다.
 2) 머신러닝 기본기법을 TensorFlow로 구현할 수 있다.
 3) 수집한 데이터를 파이썬을 통해서 다룰 수 있다.
 4) 내문제에 머신러닝 적용할 수 있다.
 5) 스스로 머신러닝을 더 연구해 보고싶다.
16
누구나 TensorFlow!
J. Kang Ph.D.
누구나 TensorFlow의 목표
 강의 대상: 머신러닝을 시작하는 모든 사람!!
 1) 머신러닝에 관심을 가지려고 하는 대학교 3학년
 2) 머신러닝을 배워서 취업면접에서 한마디라도 더하고 싶은 취준생
 3) 교수님이 머신러닝을 이용해보라고 하는데 막막한 대학원생
 4) 최소한으로 공부해서 머신러닝을 적용해 보고 싶은 주니어 개발자!
17
누구나 TensorFlow!
J. Kang Ph.D.
강의 일정
일 정 목표 시간 세부 내 용
1일차
1/11 목
Python 준비하기 2 -python scientific framework
-python, numpy 기본
-LAB1: python 예제 실습
머신러닝 가족에게
설명하기
3 -머신러닝이란?
-왜 머신러닝인가?
-최근에 머신러닝이 각광받는 이유
-머신러닝의 종류
-머신러닝의 trade-off
TensorFlow 준비하기 3 -왜 TensorFlow인가? + TensorFlow 설치
-LAB2: Helloworld in TensorFlow
-TensorFlow 기본 요소
-LAB3: TensorFlow 기본예제 line-fitting
18
누구나 TensorFlow!
J. Kang Ph.D.
강의 일정
19
2일차
1/12 금
딥러닝의 선조
뉴럴 네트워크
3 -Lab3.5 : TensorBoard!! 실습
-뉴런을 수학으로 표현하기
-Feed-Forward Neural Networks
-Linear 뉴런의 한계와 Activation 함수
-Gradient descent Revisit
-Backpropagation algorithm
-LAB6: Two-layer neural net with
Backpropagation in TensorFlow
왜 딥러닝 인가? 1 -Neural Network 의 역사 (~1990s)
-딥러닝 이전 인공신경망의 한계
-LAB7: Vanishing Gradient 문제 체험하기
-딥러닝의 열쇠 (2000s)
RBM pre-training하기 2 - RBM이 몬가요?
- RBM Pre-Training
- RBM with Contrastive Divergence
-LAB8: Binary RBM Unsupervised Pre-training
딥러닝 시작하기 2 -Deep Belief Networks (DBN)
-LAB9: Layer-wise Pre-training of DBN
누구나 TensorFlow!
J. Kang Ph.D.
강의 일정
20
3일차
1/13 토
딥러닝 훈련 기법 2 -딥러닝을 위한 몇가지 기법:
-LAB10: Relu Activation 해보기
-LAB11: DropOut 해보기
-LAB12: Batch Normalization 해보기
-LAB13: Adam optimizer 해보기
-LAB14: Revisit DBN with ReLu, DropOut, Batch
nomalization
Convolutional Neural
Net
5 -Biogical inspiration for CNN
-Convolutional layer
-LAB13: Filtering in CNN 실습
-Why convolution?
-Pooling layer
-LAB14: Pooling in CNN 실습
-Old CNN
-Modern CNN
-LAB15: LeNet-5 실습
Wrap up 1 - 강의 리뷰
- Mobile ML lab 소개
누구나 TensorFlow!
J. Kang Ph.D.
GitHub link
GitHub link (all public)
– https://github.com/jwkanggist/EveryBodyTensorFlow
– Facebook page: goo.gl/NvdbWq
Aymeric' s repo
– https://github.com/aymericdamien/TensorFlow-Examples
Prof. Sung Kim’s repo
– https://github.com/hunkim/DeepLearningZeroToAll
21
누구나 TensorFlow!
J. Kang Ph.D.
기타 참고 한글 자료
상혁님 블로그
– http://sanghyukchun.github.io/
테리님의 ML papar repo
– https://github.com/terryum/awesome-deep-learning-papers#old-papers
22
누구나 TensorFlow!
J. Kang Ph.D.
1. Python 준비하기
1. python/ anaconda /pyCharm 설치
2. LAB0: python 개발 환경 구축
3. python, numpy / pandas.DataFrame기본 실습
4.LAB1: python 실습 : 계단 오르기 문제
연구자들이여 MATLAB에서 벗어나라!!
23
누구나 TensorFlow!
J. Kang Ph.D.
Reference : Scientific computing in python
24
Python for
Data Analysis
1st Edition, 2013 O’Reilly
Wes McKinney
누구나 TensorFlow!
J. Kang Ph.D.
Why Python for Scientific Computing ?
 높은 생산성 & 개방성!
 Script language + Concise Grammar  Easy to learn and produce
 License-free +extensive open libraries: numpy, scipy, pandas, tensorflow…
25
helloWorld.java helloWorld.py
public class Main
{
public static void main(String[] args){
System.out.println("hello world");
}
}
print ‘hello world’
누구나 TensorFlow!
J. Kang Ph.D.
Why Python for Scientific Computing ?
 높은 생산성 & 개방성!
 Script language + Concise Grammar  Easy to learn and produce
 License-free +extensive open libraries: numpy, scipy, pandas, tensorflow…
 호환성 & 통합성
 Very good compatibility to other languages: cython, jython,…
 For further your interest, visit this link.
26
MATLAB Python
- MathWork (1984)
- 공학시뮬레이션
- 기본엔진 + 툴박스
- 행렬 계산효율성 매우좋음
- 폐쇄적
- 제한적호환성
- 유료!!
- 파이썬 소프트웨어 재단 (1991)
- 범용성 / 간결한 문법/ 가독성
- 방대한 3rd party 라이브러리
- 개방적 + 호환성 + 이식성
good
- 모든게 무료!!
누구나 TensorFlow!
J. Kang Ph.D.
- Interpreter
- Programming language
- Standard library
- Efficient N-dimensional array data structure
- Fast / flexible matrix&vector computing
- Very good compatibility to C/C++ /Fortran
- Basic pip packages for python scientific computing
- Packages for machine learning extension
Python Scientific Computing Ecosystem
27
누구나 TensorFlow!
J. Kang Ph.D.
Python Scientific Computing Ecosystem
28
Package
name
Description
numpy Based N-dimensional array package
scipy Fundamental library for scientific computing
Ipython Enhanced python interactive console (like MATLAB command
window)
matplotlib Comprehensive 2D plotting
scikit-learn Providing library of off-the-shelf machine learning algorithms
(higher-level)
tensorflow Providing library of low-level machine learning algorithm
Pandas Data analysis framework: Easy data manipulation / importing
/exporting
누구나 TensorFlow!
J. Kang Ph.D.
Python Scientific Computing Ecosystem
29
모든게 다 귀찮다면?
누구나 TensorFlow!
J. Kang Ph.D.
Python Scientific Computing Ecosystem
30
모든게 다 귀찮다면?  Anaconda!
– 뱀이야기 인가요 ?
VS ?
누구나 TensorFlow!
J. Kang Ph.D.
Python Scientific Computing Ecosystem
31
Platform name Description
Python Interpreter + standard library
Anaconda Interpreter + standard libraries +Most of the scientific
computing libraries
모든게 다 귀찮다면?  Anaconda!
– 아니요 -_-;;
– Python + 관련 패키지 통합 distribution !!
– For window users:Anaconda3 4.4 with python 3.6설치
• https://www.anaconda.com/download/#windows
<
누구나 TensorFlow!
J. Kang Ph.D.
Python설치
 우분투/ OSX: 기본적으로 설치되어 있음
– 이것을 “system 파이썬”이라고 가급적 다루지 않는 것이 좋음
– 파이썬 가상 환경을 구성하여 개발해야함
– pyenv + virtualenv : 파이썬 버전별 설치 / 패키지 관리
32
[이미지출처] https://www.extramile.io/blog/how-to-setup-multiple-python-versions-with-pyenv/
누구나 TensorFlow!
J. Kang Ph.D.
Python설치
 우분투/ OSX: 기본적으로 설치되어 있음
– 이것을 “system 파이썬”이라고 가급적 다루지 않는 것이 좋음
– 파이썬 가상 환경을 구성하여 개발해야함
– pyenv + virtualenv : 파이썬 버전별 설치 / 패키지 관리
33
[이미지 출처] http://qiita.com/hedgehoCrow/items/0733c63c690450b14dcf
누구나 TensorFlow!
J. Kang Ph.D.
Python설치
 우분투/ OSX: 기본적으로 설치되어 있음
– 이것을 “system 파이썬”이라고 가급적 다루지 않는 것이 좋음
– 파이썬 가상 환경을 구성하여 개발해야함
– pyenv + virtualenv : 파이썬 버전별 설치 / 패키지 관리
– autoenv : 폴터별 가상환경 구축
• 파이썬 설치 + 가상환경 설치 (OSX) : https://goo.gl/bE8nmS
• 텐서플로 설치 (OSX): https://goo.gl/Vqpw5Q
 Win10: 운영체제에 맞춰서 인스톨러를 다운받아서 설치
• https://www.python.org/downloads/windows/
• Win10에서는 python 3.5 이상만 Tensorflow와 호환됨
• 관리자 권한으로 실행!
– 파이썬 설치 + 텐서플로 설치 (win10): https://goo.gl/GvybRz
34
누구나 TensorFlow!
J. Kang Ph.D.
PyCharm IDE 설치
JetBrain에서 제공하는 파이썬 개발툴 (IDE)
– Git 지원
– Pip 패키지 관리 지원
– IPython console지원
– Debugger 지원
– Terminal 지원 (ubunto/OSX only)
 Ubuntu /OSX/win 설치
– https://www.jetbrains.com/pycharm/download/#section=mac
– 반드시 community version으로 설치할것
– 설치 경로에 한글이 없어야함!
35
누구나 TensorFlow!
J. Kang Ph.D.
LAB0: python 개발환경 구축 설치
 목표: 파이썬을 다루기 위한 기본 개발 환경 설치
 Ubuntu / OSX 사용자
– Pyenv / pyenv-virtualenv 설치
– 파이썬 개발을 위한 가상환경 만들어 보기
– Anaconda3 설치
– PyCharm 커뮤니티 버전 설치
– 가상환경 생성 후 Pip 명령어를 이용한 파이썬 패키지 설치확인
• $ pip install numpy scipy matplotlib pandas scikit-learn
• $ pip list
 Window 사용자
– anaconda3 설치
– pyCharm 커뮤니티 버전 설치
– Pycharm IDE에서 File  Settings  Project Interpreter 에서 anaconda3로
설정
36
누구나 TensorFlow!
J. Kang Ph.D.
LAB0: python 개발환경 구축 설치
 더 자세하게는 아래 파일 참조
– 우분투:
https://docs.google.com/document/d/1DXncq3t9_UezhtiD_1-yWAYqGsnvem8L2TdU2CpeQZc/
– OSX:
https://docs.google.com/document/d/1unqQ8HziRJcZyPiRVX_gMg6eQh65tERM-jhNOIHe44M/
- Win10:
- 파이썬 설치 + 텐서플로 설치 (win10): https://goo.gl/GvybRz
37
누구나 TensorFlow!
J. Kang Ph.D.
1. Python 준비하기
1. python 2.7/ anaconda2 /pyCharm 설치
2. LAB0: python 개발 환경 구축
3. python, numpy / pandas.DataFrame기본 실습
4. LAB1: python 실습 : Random Walk 문제
38
누구나 TensorFlow!
J. Kang Ph.D.
GitHub Repository
모든 소스코드는 GitHub를 통해서
공유됩니다.
– https://github.com/jwkanggist/EveryBodyTensorFlow
39
누구나 TensorFlow!
J. Kang Ph.D.
Python - Hello world
파이썬 기본 문법
– 일단 helloworld부터 찍고 보기
40
Ex1) helloworld.py
$ vim helloworld.py
print ‘Hello world’ # python2
print (‘Hello world!!’) # python3
$ python helloworld.py
Hello world
Hello world!!
누구나 TensorFlow!
J. Kang Ph.D.
Python- package Import
파이썬 기본 문법
– 파이썬 위대함 1: 생각할 수 있는 대부분의 API가 오픈소스로
존재한다.
– 파이썬 위대함 2: pip + import의 조합이 그런 오픈소스API 사용이
매우 쉽다.
41
Ex2) Tensorflow pip 설치 후 import 하기
$ pip install tensorflow
[Installing Tensorflow …]
$ python
>>> import tensorflow as tf
누구나 TensorFlow!
J. Kang Ph.D.
Python - package Import
파이썬 기본 문법
– 파이썬 위대함 1: 생각할 수 있는 대부분의 API가 오픈소스
패키지로 존재한다.
– 파이썬 위대함 2: pip + import의 조합이 그런 오픈소스 패키지
사용이 매우 쉽게 한다.
– 파이썬 위대함 3: 오픈 소스 패키지의 완성도가 매우 높다.
42
Ex3) pandas install 후 import 해서 사용
$ pip install numpy scipy pandas matplotlib
[Installing…]
>>> import numpy as np
>>> import scipy as sp
>>> import pandas as pd
>>> import matplotlib.pyplot as plt
누구나 TensorFlow!
J. Kang Ph.D.
Python- List
파이썬 기본 문법
– 순서가 있는 값들의 나열
– 한가지 / 여러가지 타입으로 이루어진 리스트 구성가능
– 0부터 시작하는 인덱스로 브라우징 가능
43
Ex4) 리스트 관련 example
>>> lst = ['a', 3.14, 55555, 'abcdef', ['a', 'b', 'c']]
>>> lst
['a', 3.14, 55555, 'abcdef', ['a', 'b', 'c']]
>>> lst = [3.14132323, 3535242, 'abc', "def", 'color']
>>> lst
[3.14132323, 3535242, 'abc', 'def', 'color']
누구나 TensorFlow!
J. Kang Ph.D.
Python - List
파이썬 기본 문법
– 대입하는 경우 리스트의 복사가 아니고 참조함
– 다양한 멤버함수를 가지고 있음: append(), insert(),remove(), sort(),
split()
44
Ex4) 리스트 관련 example
>>> a= ['adfa','123','tda','114']
>>> a
['adfa', '123', 'tda', '114']
>>> b=a
>>> b
['adfa', '123', 'tda', '114']
>>> b[0]='0'
>>> a
['0', '123', 'tda', '114']
누구나 TensorFlow!
J. Kang Ph.D.
Python- For statement
파이썬 기본 문법
– 1) range()과 함께 사용
45
Ex5) examplefor.py
$ vim examplefor.py
#-*- coding: utf-8 -*-
for i in range (0,5):
print ‘ printing number: %s ‘ % i
$ python examplefor.py
printing number: 0
printing number: 1
printing number: 2
printing number: 3
printing number: 4
누구나 TensorFlow!
J. Kang Ph.D.
Python- For statement
파이썬 기본 문법
– 1) range()과 함께 사용
– 2) list와 함께 사용
46
Ex6) examplefor2.py
$ vim examplefor2.py
#-*- coding: utf-8 -*-
namelist = [ ‘kim’,’park’,’lee’,’kang’]
for name in namelist:
print ‘ printing name: %s ‘ % name
$ python examplefor2.py
printing name: kim
printing name: park
printing name: lee
printing name: kang
누구나 TensorFlow!
J. Kang Ph.D.
Python- If-elif-else statement
파이썬 기본 문법
– 다양한 부등호와 함께 사용: ==, !=, <, >…
– is, not, and, or의 논리 연산 사용
47
Ex7-1) exampleif.py
$ vim exampleif.py
#-*- coding: utf-8 -*-
number = 0
if number == 0:
print ‘zero’
elif number == 1:
print ‘one’
else:
print ‘any’
누구나 TensorFlow!
J. Kang Ph.D.
Python - If-elif-else statement
파이썬 기본 문법
– 다양한 부등호와 함께 사용: ==, !=, <, >…
– is, not, and, or의 논리 연산 사용
48
Ex7-2) exampleif2.py
$ vim exampleif2.py
#-*- coding: utf-8 -*-
number = 0
number2 = 1
if (number == 0) and (number2 == 1):
print ‘Both True!!’
elif (number == 0) or (number2 == 1):
print ‘one of both is True’
else:
print ‘All False’
누구나 TensorFlow!
J. Kang Ph.D.
Python - user-defined func
파이썬 기본 문법
– “def” 키워드를 가지고 정의할 수 있다.
49
Ex8) examplefunc.py
$ vim examplefunc.py
#-*- coding: utf-8 -*-
def myFuncPrint (keyword, numOfPrint):
for i in range(0,numOfPrint):
print “ The %s-th printing of %s” % (i+1,keyword)
myFuncPrint (‘JaewookKang’, 5)
% python examplefunc.py
The 1-th printing of JaewookKang
The 2-th printing of JaewookKang
The 3-th printing of JaewookKang
The 4-th printing of JaewookKang
The 5-th printing of JaewookKang
누구나 TensorFlow!
J. Kang Ph.D.
Numpy: Numerical Python
 벡터&행렬 연산에 필요한 N차원 배열을 다루기 위한 도구
– 효율적인 N차원 배열 자료 구조: ndarray
– 다양한 ndarray 기반 수학 함수 API
– 간편한 메모리 to ndarray 인터페이스
 Ndarray vs. List
– 벡터&행렬 연산에는 ”ndarray”가 단언컨데 유리함!
50
ndarray List
메모리 사
용 특징
- 한 주소값으로 부터 연속적
으로 메모리에 elem값저장
Elem값이 이산적인 주소값에
저장
연산 특징 sequential한 elem값 연산에
유리
Elem 단위 연산에 유리
구현 Array list (C/C++ array) Linked list
누구나 TensorFlow!
J. Kang Ph.D.
Numpy: Numerical Python
 Numpy에서 꼭 알아야 할것
– ndarray 생성
– ndarray 인덱싱
– ndarray 유니버설 함수
51
누구나 TensorFlow!
J. Kang Ph.D.
ndarray 생성
 Practice1: List로 부터 생성
52
Ex9) ex_ndarray1.py
$ python
>>> import numpy as np
>>> templist = [1,2,3,4,5,6]
>>> templist
[1,2,3,4,5,6]
>>> nptemplist = np.array(templist)
>>> nptemplist
array ([1 ,2 ,3 ,4 ,5 ,6 ])
>>> whos
Variable Type Data/Info
---------------------------------
np module <module 'numpy' from …..
nptemplist ndarray 5: 5 elems, type `int64`, 40 bytessys…..
templist list n=5…
누구나 TensorFlow!
J. Kang Ph.D.
ndarray 생성
 Practice2: List로 부터 생성 + dtype설정
53
Ex10) ex_ndarray2.py
$ python
>>> import numpy as np
>>> templist = [1,2,3,4,5,6]
>>> templist
[1,2,3,4,5,6]
>>> nptemplist = np.array( templist, dtype = np.int8 )
>>> nptemplist
array ([1 ,2 ,3 ,4 ,5 ,6 ])
>>> whos
Variable Type Data/Info
---------------------------------
np module <module 'numpy' from …..
nptemplist ndarray 5: 5 elems, type `int8`, 40 bytessys…..
templist list n=5…
누구나 TensorFlow!
J. Kang Ph.D.
ndarray 생성
 Practice3: all zeros/ones 벡터&행렬 생성
54
Ex11) ex_zeros.py
$ python
>>> import numpy as np
>>>np.zeros(1)
array([ 0.])
>>> np.zeros(2)
array([ 0., 0.])
>>> np.zeros([2,1])
array([[ 0.], [ 0.]])
>>> np.zeros([2,2])
array([[ 0., 0.], [ 0., 0.]])
누구나 TensorFlow!
J. Kang Ph.D.
ndarray 생성
 Practice3: all zeros/ones 벡터&행렬 생성
55
Ex12) ex_ones.py
$ python
>>> import numpy as np
>>>np.ones(1)
array([ 1.])
>>> np.ones(2)
array([ 1., 1.])
>>> np.ones([2,1])
array([[ 1.], [ 1.]])
>>> np.ones([2,2])
array([[ 1., 1.], [ 1., 1.]])
누구나 TensorFlow!
J. Kang Ph.D.
ndarray 인덱싱
 Practice4: ndarray 의 인덱싱은 참조를 사용한다.
– 슬라이싱 기능: “:”를 가지고 인덱싱하는 것
– 리스트와의 중요한 차이점은 slice은 원본배열의 view라는 점
56
Ex13) ex_indexing.py
>>> arr = np.arange(10)
>>> arr
array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
>>>arr[5]
5
>>> arr[5:8]
array([5, 6, 7])
>>> arr[5:8] = 12
>>> arr
array([ 0, 1, 2, 3, 4, 12, 12, 12, 8, 9])
누구나 TensorFlow!
J. Kang Ph.D.
ndarray 인덱싱
 Practice5: ndarray 의 인덱싱은 참조를 사용한다.
– 슬라이싱 기능: “:”를 가지고 인덱싱하는 것
– 리스트와의 중요한 차이점은 slice은 원본배열의 view라는점
– ndarray의 복사복을 얻고싶다면 arr[5:8].copy()를 사용
57
Ex14) ex_slicing.py
>>> arr_slice = arr[5:8]
>>> arr_slice[1] = 12345
>>> arr
array([ 0, 1, 2, 3, 4, 12, 12345, 12, 8, 9])
>>> arr_slice[:] = 128
>>> arr
array([ 0, 1, 2, 3, 4, 128, 128, 128, 8, 9])
누구나 TensorFlow!
J. Kang Ph.D.
ndarray 유니버설 함수
 Practice6: ndarray안에 있는 데이터 원소별로 연산을
수행하는 함수
58
함수 설명
abs, fabs 각 원소의 절대값을 구한다. 복소수가 아닌 경우
에는 빠른 연산을 위해 fabs를 사용한다.
sqrt 각 원소의 제곱근을 계산한다.
square 각 원소의 제곱을 계산한다.
Log, log10, log2 각 원소의 지수 exp^x를 계산한다.
ceil 각 원소의 소수자리를 올린다.
floor 각 원소의 소수자리를 버린다.
modf 각 원소의 몫과 나머지를 각각의 배열로 반환한
다.
Isnan, isinf 각 원소의 nan/inf 상태를 불리안값을 가지고 확
인한다.
Cos, cosh, sin, sinh, tan, tanh 각 원소의삼각/쌍곡 함수
누구나 TensorFlow!
J. Kang Ph.D.
ndarray 유니버설 함수
 Practice6: ndarray안에 있는 데이터 원소별로 연산을
수행하는 함수
59
함수 설명
Add 두 ndarray를 원소단위로 덧셈한다.
Substract 두 ndarray를 원소단위로 뺄셈한다.
Multiply 두 ndarray를 원소단위로 나눗셈한다.
Divide, floor_divide 첫 번째 배열의 원소에서 두번째 배열의 원소를
나눈다. Floor_divide는 몫만 취한다.
Power 첫번째 배열의 원소에서 두번쨰 배열의 원소만
큼 제곱한다.
Maximum, fmax 두중 큰값을 반환 fmax는 NaN은 무시한다.
Minimum, fmin 두중 작은값을 반환 fmin은 NaN은 무시한다.
Logical_and, logical_or, logical_xor 각각 두 원소 간의 논리연산 결과를 반환한다.
Mod 첫번째 배열원소에 두번째 배열원소로 나눈 나
머지값을 반환한다.
누구나 TensorFlow!
J. Kang Ph.D.
LAB1: Random walk 문제
 계단을 0층 부터 시작하여 같은 확률로 계단을 한칸 올라가거 나
내려갈수 있다.
 시행횟수에 따른 계단 층수를 시뮬레이션 해보자
– 초기위치: position = 0
– 시행횟수: step = 10
 random walk 값이 음수가 되는 값만 출력해보자
 Numpy를 사용해서 구현해보자
– Naïve구현
• For문 IF문 사용
– Numpy API사용 구현
• np.where()
• np.random.randint(2,size=1)
• np.cumsum()
 참고 github link:
https://github.com/jwkanggist/EveryBodyTensorFlow/blob/master/lab1_randomwalk.py
60
누구나 TensorFlow!
J. Kang Ph.D.
1. 머신러닝 가족에게 설명하기
- 머신러닝 이란?
- 최근에 머신러닝이 각광받는 이유
- 머신러닝의 3대 요소
- 머신러닝의 종류
- 머신러닝에서의 Trade-off
61
누구나 TensorFlow!
J. Kang Ph.D.
Reference : Machine learning fundamental
62
Hands-On Machine Learning
With Scikit-Learn &
TensorFlow
2017 Aurelien Geron, Google
O’Reilly
본 강의는 해당 교재를 참고했음을
사전에 알립니다.
누구나 TensorFlow!
J. Kang Ph.D.
What Machine Learning?
63
머신러닝은 무엇인가?
누구나 TensorFlow!
J. Kang Ph.D.
What Machine Learning?
64
머신러닝은 무엇인가?
– 컴퓨터가 지능을 갖는 것? 인공지능? AlphaGo?
– 데이터를 통해서 예측하는 것?
– 컴퓨터에게 알려주는거?
누구나 TensorFlow!
J. Kang Ph.D.
What Machine Learning?
65
Definition (Machine Learning):
Field of study that gives computers the ability to learn without being explicitly
programmed.
- Arthur Samuel, 1959
머신러닝은 무엇인가?
– 컴퓨터가 지능을 갖는 것? 인공지능? AlphaGo?
– 데이터를 통해서 예측하는 것?
– 컴퓨터에게 알려주는거?
누구나 TensorFlow!
J. Kang Ph.D.
What Machine Learning?
66
머신러닝은 무엇인가?
– 컴퓨터가 지능을 갖는 것? 인공지능? AlphaGo?
– 데이터를 통해서 예측하는 것?
– 컴퓨터에게 알려주는거?
Definition (Machine Learning):
A computer program is said to learn rom experience E with respect to some
task T and some performance measure P, if its performance on T, measured
by P, is improved with experience E.
- Tom Mitchell, 1997
누구나 TensorFlow!
J. Kang Ph.D.
What Machine Learning?
67
머신러닝은 무엇인가?
– 임의의 업무 생산성/정확성/능률 (P) 의 척도 대해서
데이터라는 경험 (E) 을 통해서 컴퓨터가 업무 (T) 를
볼수 있도록 훈련시키는 일
Definition (Machine Learning):
A computer program is said to learn rom experience E with respect to some
task T and some performance measure P, if its performance on T, measured
by P, is improved with experience E.
- Tom Mitchell, 1997
누구나 TensorFlow!
J. Kang Ph.D.
머신러닝의 구성요소
머신러닝을 하기위해서 무엇이 필요한가?
– 경험 (E): Training data Set
– 업무 (T): System or model to be learned
– 척도 (P): performance measure, accuracy
68
누구나 TensorFlow!
J. Kang Ph.D.
머신러닝의 구성요소
머신러닝을 하기위해서 무엇이 필요한가?
– 경험 (E): Training data Set
– 업무 (T): System or model to be learned
– 척도 (P): performance measure, accuracy
69
Training Step:
T: Spam mail
Filtering
system
(E):User flagged
Spam list
(T): Smap Filtering
system
(P): Filtering
Accuracy
Training
Collecting
Training DataSpam ✔
Spam ✔
Spam ✔
누구나 TensorFlow!
J. Kang Ph.D.
머신러닝의 구성요소
머신러닝을 하기위해서 무엇이 필요한가?
– 경험 (E): Training data Set
– 업무 (T): System or model to be learned
– 척도 (P): performance measure, accuracy
70
Tasking Step:
T: Spam mail
Filtering
system
Arbitrary
Input
SPAM
Filtering
(spam classification)
누구나 TensorFlow!
J. Kang Ph.D.
Why Machine Learning?
Conventional approach
– 단편적인 현상을 통해 프로그래머가 인지한 몇가지 rule를 가지고
문제를 해결
• 보편적인 rule 을 만들기 어려움
• 실제 문제의 해결을 보장하지 않음
• 결과물은 엔지니어의 경험에 매우 의존적임
71
Study the
Problem
Establish
rules
Evaluate
Analyze
errors
Release!
누구나 TensorFlow!
J. Kang Ph.D.
Why Machine Learning?
ML approach
– 데이터로 부터 문제 해결을 위한 보편적인 rule을 찾는다.
• Training data set에 대한 일반화
• 데이터에 의한 문제해결
72
Study the
Problem
Train ML
algorithm
Evaluate
Analyze
errors
Release!
Lots of Data
누구나 TensorFlow!
J. Kang Ph.D.
Why Machine Learning?
ML approach
– 데이터로 부터 문제 해결을 위한 rule을 자동으로 찾는다.
• 머신러닝이 진정한 의미가 있기 위해서는…
• 빅데이터가 있고
• 자동으로 시스템이 러닝될 수 있다.
73
Train ML
algorithm
Evaluate
Solution
Update
Data
Release!
Lots of Data
Can be
automated
누구나 TensorFlow!
J. Kang Ph.D.
ML approach 특징 요약
– All from data!!
• Larger data  Better systems
• Simple but universal rule
• Easy update rule given new data
• Getting unrecognized insights about complex problems
Why Machine Learning?
74
Inspect the
solution
Lots of Data
Study the
Problem
Train ML
algorithm
Iterate
If needed
Understand the
problem
better
Solution
New Insight
누구나 TensorFlow!
J. Kang Ph.D.
Why Machine learning Now?
머신러닝 3요소
– 빅데이터: SmartDevices, IoT, sensor networks
– 알고리즘: deep learning / reinforcement-learning
– 컴퓨팅 파워: GPU, parallel / distributed
computing
75
누구나 TensorFlow!
J. Kang Ph.D.
Why Machine learning Now?
머신러닝 3요소
– 빅데이터 >> 컴퓨팅 파워 > 알고리즘
• 품질 좋은/많은 량의 데이터만 있으면 머신러닝
시스템의 성능을 무조건 좋다.
76
누구나 TensorFlow!
J. Kang Ph.D.
Why Machine learning Now?
머신러닝 3요소
– 빅데이터 >> 컴퓨팅 파워 > 알고리즘
• 품질 좋은/많은 량의 데이터만 있으면 머신러닝
시스템의 성능을 무조건 좋다.
 그럼 데이터만 있으면 엔지니어는 이제 필요없나요 ?
– 아니요!: 위 세가지는 항상 모두 주어지지 않음
 We need ”Domain Adaptation !!”
 목표: 성능개선 + 러닝 시간 단축 + 데이터 용량 최소화
77
누구나 TensorFlow!
J. Kang Ph.D.
We Still Need ML Engineers!
Domain Adaptation 1 – Feature Extraction
– 데이터를 특징을 잘 뽑아서 데이터량을 줄인다
– Simplify data without losing too much information !
– Feature extraction을 잘하기 위해서는 도메인 지식이 중요
Domain Adaptation 2 – Learning Environment
– 모바일에서는 컴퓨팅 파워와 데이터 저장소가 부족
– 긴 러닝 타임도 부담
– Google’s Approach in Mobile ML env. (utblink)
• Pre-training model in cloud
• Local fine-Tuning with private data in mobile APP
• Run prediction engine in mobile APP
78
+
Cloud ML
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
 학습방식에 따라서
– Supervised
– Unsupervised
– Reinforcement
 데이터 업데이트 방식에 따라서
– Batch-based learning
– Online-based learning
79
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Supervised learning
– Training data set이 시스템의 입력과 출력의 pair 로
구성된 경우
• 여기서 출력을 label이라고 함
• 여기서 입력을 instance (또는 feature)라고 함
80
2
1 1
2
1
2
?
New instance
Training Set
Instance
Label
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Supervised learning
– Training data set이 시스템의 입력과 출력의 pair 로 구성된 경우
– 컴퓨터가 러닝하는데 선생이 있어서 답(label)을 알려주는 경우
– 머신 러닝의 가장 보편적인 형태
81
An example: Spam filter revisited
T: Spam mail
Filtering
system
(E):User flagged
Spam list
(T): Smap Filtering
system
(P): Filtering
Accuracy
Training
Collecting
Training DataSpam ✔
Spam ✔
Spam ✔
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Supervised learning
– Regression
– Classification
Models in Supervised learning
– Linear Models
– Neural networks
– SVM, RVM
82
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Unsupervised learning
– Training data set이 입력만 있는 경우
– 컴퓨터가 러닝하는데 선생님이 없는 경우
– 세상에 존재하는 대부분의 데이터는 label이 없다
83
Training Set
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Unsupervised learning
– Training data set이 입력만 있는 경우
– 컴퓨터가 러닝하는데 선생님이 없는 경우
– 세상에 존재하는 대부분의 데이터는 label이 없다
84
Training Set
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Unsupervised learning
– Clustering
– Dimensionality reduction
• The goal is to simplify the data without losing too much
information
– Feature extraction:
• which is a kind of dimensionality reduction
• Reducing computational& memory cost for ML
• Making ML system efficient!
• Domain knowledge is required
85
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Semisupervised learning
– Combination of supervised and unsupervised learning
• 1) Supervised learning with labeled data
• 2) Unsupervised learning with unlabeled data
• 3) Self-labelling of unlabeled data using step1 and step2
• 4) re-training of the system
86
이미지 출처:
https://www.researchgate.net/publication/277605013_Signal_
Processing_Approaches_to_Minimize_or_Suppress_Calibration
_Time_in_Oscillatory_Activity-Based_Brain-
Computer_Interfaces
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Semisupervised learning
– Training data set = labeled data + unlabeled data
– Combination of supervised and unsupervised learning
87 feature1
Feature 1
Feature 2
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Semisupervised learning
– Training data set = labeled data + unlabeled data
– Combination of supervised and unsupervised learning
88
Supervised learning with
Labeled data
feature1
Feature 1
Feature 2
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Semisupervised learning
– Training data set = labeled data + unlabeled data
– Combination of supervised and unsupervised learning
89
Labeling unlabed data
With trained classifier
Feature 1
Feature 2
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Semisupervised learning
– Training data set = labeled data + unlabeled data
– Combination of supervised and unsupervised learning
90
Re-training and
classifier update
Feature 1
Feature 2
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Reinforcement learning
– 컴퓨터가 시간에 따라서 보상을 통해서 최고의 행동전략을
환경으로 부터 스스로 배워가는 것
– 결과로 부터 스스로 학습법
91
[이미지 출처]
https://www.analyticsvidhya.com/bl
og/2016/12/getting-ready-for-ai-
based-gaming-agents-overview-of-
open-source-reinforcement-
learning-platforms/
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
MarI/O (2015)
– 목적: 게임에 대한 연속적인 버튼선택 러닝
• https://www.youtube.com/watch?v=qv6UVOQ0F44
– 게임의 각 프레임 상황을 supervised DNN으로 모델링
• 입력: 프레임 화면 이미지
• 출력: 각 화면 이미지에 대한 버튼선택 (A,B,X,Y,R,L,up,down,right,left)
– 강화학습
– 환경으로 부터 DNN 훈련 데이터를 스스로 만들어내는 과정
• 각 프레임의 환경을 “State”로 정의 (블록배치, enemy위치)
• 현재 state의 Action (버튼 선택)에 따라 다음 state가 정해진다.
• 각 State 에 대해서 Action (버튼 선택)에 따른 ”Reward” (Fitness) 를 피드백
– 살아있으면 + 1
– 버섯, 코인, 먹으면 + X
– Enemy 에 접촉해서 데미지를 입으면 - Y
• Reward가 높은 state의 action에 대한 확률이 높인다
• Reward는 과거 N-state에 대해서 피드백 된다.
– 생성되는 DNN 훈련데이터는 sequential 데이터 이다.
92
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Google DeepMind 벽돌깨기 (2016)
– https://www.youtube.com/watch?v=V1eYniJ0Rnk
– AI가 살아남는 것을 넘어서 편하게 점수를 따는 전략을 스스로
찾아냄
– AI가 스스로 행동전략을 진화시킨 첫번째 케이스로 알려짐
93
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Batch learning
– Training data set를 통째로 넣어서 한번에 시스템을
러닝하는 것
• 장점: simple / 주어진 데이터 안에서 안정적인 동작
• 단점:
– 급격하게 변화하는 데이터 대처에 비효율
– Learning cost가 크다
» 계산량: 데이터가 크니깐 크다
» 메모리: training data를 항상 보관하고 있어야 한다.
» 시간 : 데이터가 크니깐 러닝타임이 길다.
94
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Online Learning
– 시스템을 러닝한 후에도 instance data가 들어오면 online으로
시스템을 incrementally 업데이트 할수 있는 학습법
95
Evaluate
Solution
Lots of Data
Train ML
algorithm
Run and
Update
Model
Release!
New Data New Data New Data
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Online Learning
– 시스템을 러닝한 후에도 instance data가 들어오면 online으로
시스템을 incrementally 업데이트 할수 있는 학습법
– 하드웨어의 계산부담을 줄이기위해서 batch learning을 online
learning으로 쪼개서 할수도 있음 (실제로 다 그렇케 함)
96
Study the
Problem
Train online
ML algorithm
Analyze
errors
Evaluate
Release!
Lots of Data
Chop into
pieces
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Online Learning
– 장점:
• 변화하는 데이터에 바로바로 대처
• 러닝 비용을 낮출 수 있다
• Training data를 들고 있지 않아도 된다.
– 단점: 데이터의 변화에 너무 시스템이 민감해질 수 있다.
97
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
Model selection
– Underfitting
– Overfitting
Curse of dimensionality
98
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
Model selection
– 대상으로하는 데이터의 범주에 맞는 머신러닝 모델 선택이
중요하다!
– 목적으로하는 데이터 범주에 대해서
99
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
Model selection
– 대상으로하는 데이터의 범주에 맞는 머신러닝 모델 선택이
중요하다!
– 목적으로하는 데이터 범주에 대해서
• 설명을 잘못하는 모델  예측 오류값이 매우 크다 (Underfitting)
100
Training data
Validation data
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
Model selection
– 대상으로하는 데이터의 범주에 맞는 머신러닝 모델 선택이
중요하다!
– 목적으로하는 데이터 범주에 대해서
• 설명을 잘못하는 모델  예측 오류값이 매우 크다 (Underfitting)
• 훈련데이터에 대해서만 작은 오류값을 출력하는 모델 (Overfitting)
–  일반화된 예측결과를 제공 못함
101
Training data
Validation data
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
Model selection
– 대상으로하는 데이터의 범주에 맞는 머신러닝 모델 선택이
중요하다!
– 목적으로하는 데이터 범주에 대해서
• 설명을 잘못하는 모델  예측 오류값이 매우 크다 (Underfitting)
• 훈련데이터에 대해서만 작은 오류값을 출력하는 모델 (Overfitting)
–  일반화된 예측결과를 제공 못함
• 필요이상으로 복잡하지 않은 모델
102
Training data
Validation data
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
Model selection
– 간단한 모델
• Good:
– 1) 주어진 데이터 셋에 대해서 일반화 된 결과를 내놓는다.
– 2) 작은 데이터 셋을 가지고 훈련이 가능하다.
– 3) 작은 범위의 데이터 셋에 대해서 성능이 복잡한 모델 보다 좋다.
• Bad :
– 1) Underfitting: 다양한/넓은 범위의 데이터 셋에 대해서 설명 (모델링) 하지
못한다.
– 복잡한 모델
• Good:
– 1) 다양한/넓은 범위의 데이터 셋에 대해서 설명(모델링)이 가능하다.
• Bad :
– 1) 작은 범위의 데이터 셋에 대해서 성능이 간단한 모델에 비해서 열화된다.
– 2) 훈련을 위해서 다양하고 큰 데이터 셋이 필요하다.
– 3) Overfitting: 대상으로 하는 데이터 셋에 대해서 일반화 된 결과를 내 놓기
어렵다.
103
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
Model selection
104
Given a certain size of data…
Validation
error
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
The Curse of Dimensionality
– 데이터의 차원이 증가할 수록 학습에 필요한 데이터의 개수를
기하급수적으로 늘어나는 문제
– 같은 비율의 공간을 모델링하기 위해서 필요한 데이터 량이
급속도록 증가
– Example: 공간의 20%를 채우기 위해서 필요한 데이터 수
• 0.2(1차원)  0.9(2차원)  1.74 (3차원)
105
[이미지 출처] http://www.visiondummy.com/2014/04/curse-
dimensionality-affect-classification/
1차원 데이터
0.2 = 0.2
2차원 데이터
0.2 = 0.45 * 0.45
3차원 데이터
0.2 = 0.58 * 0.58 * 0.58
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
The Curse of Dimensionality
– 저차원에서는 충분했던 데이터 양도 고차원이 되면
공간(학습 모델)을 설명하기에 부족해 질수 있음
• 모델 고차원화  모델설명을 위한 데이터 부족 Overfitting문제
106
[이미지 출처] http://www.visiondummy.com/2014/04/curse-
dimensionality-affect-classification/
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
The Curse of Dimensionality
– 저차원에서는 충분했던 데이터 양도 고차원이 되면
공간(학습 모델)을 설명하기에 부족해 질수 있음
• 모델 고차원화  모델설명을 위한 데이터 부족 Overfitting문제
107
[이미지 출처] http://www.visiondummy.com/2014/04/curse-
dimensionality-affect-classification/
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
The Curse of Dimensionality
– 저차원에서는 충분했던 데이터 양도 고차원이 되면
공간(학습모델)을 설명하기에 부족해 질수 있음
– 모델을 설명하기에 데이터가 부족해?
108
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
The Curse of Dimensionality
– 저차원에서는 충분했던 데이터 양도 고차원이 되면
공간(학습모델)을 설명하기에 부족해 질수 있음
– 모델을 설명하기에 데이터가 부족해? Overfitting문제
– 해결책
• 데이터 양 + 다양성 늘리기
• 중요한 특징만 뽑자  데이터차원 축소 (Dimensionality
Reduction)
– Feature Extraction
– Feature Selection
• 사전지식 이용  Regularziation
109
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
Raw data vs Featured data
110
Raw data Featured Data
No information loss
 Discover Unrecognized
patterns
Some information loss
 Degrade performance
sometime
Curse of dimensionality Dimensionality Reduction
Higher computational cost
 Slower learning time
Lower computation cost
 Faster learning time
Large-scale storage
is required
Small-scale storage
is fine
누구나 TensorFlow!
J. Kang Ph.D.
Trade-off in ML
Big data vs. Small data
111
Big data Small Data
No overfitting to
training data
Overfitting to training
data is possible
Working with complex models
for difficult problems
Working with simple models for
easy problems
Higher computational cost
 Slower learning time
Lower computation cost
 Faster learning time
Large-scale storage
is required
Small-scale storage
is fine
누구나 TensorFlow!
J. Kang Ph.D.
3. Tensorflow 준비하기
- 왜 TensorFlow인가? + TensorFlow 설치
- LAB2: Helloworld in TensorFlow
- TensorFlow의 기본요소
- LAB3: TensorFlow 기본예제 line-fitting
- ML training in TensorFlow
- LAB4: TensorFlow 기본예제 Curve-fitting
이제야 준비 끝! 텐플 소개 시작….
112
누구나 TensorFlow!
J. Kang Ph.D.
Reference : Machine learning fundamental
113
Hands-On Machine Learning
With Scikit-Learn &
TensorFlow
2017 Aurelien Geron, Google
O’Reilly
본 강의는 해당 교재를 참고했음을
사전에 알립니다.
누구나 TensorFlow!
J. Kang Ph.D.
Reference: Machine Learning Crash Course
(MLCC)
114
https://cloud.google.com/blog/big-data/
본 강의는 구글에서 제공한 자료의
일부를 참고했음을 사전에 알립니다.
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 요약
A open source software library for ML
– https://www.tensorflow.org/
– ML 모델 프로토타이핑 용도
– 연산 환경
• 분산 훈련 환경 지원
• CPU/GPU/TPU + 모바일 환경 지원
– 코어 구현: C++, fast!
– Front end: python, C++, Java
– 현재 버전 r1.4 (2017 Nov)
115
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 요약
A open source software library for ML
– https://www.tensorflow.org/
– ML 모델 프로토타이밍 용도
– 연산 환경
• 분산 훈련 환경 지원
• CPU/GPU/TPU + 모바일 환경 지원
– 코어 구현: C++, fast!
– Front end: python, C++
116
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 요약
A open source software library for ML
– 2015 년 12월 이후 21,122 커밋수 (상당수가 외부)
– 1000 명 이상의 기여자
117
누구나 TensorFlow!
J. Kang Ph.D.
Why TensorFlow ?
장/단점 (다른 ML프레임워크와의 비교)
– 장점
• 간편한 front-end interface
• 호환성 == 폭 넓은 OS지원
• 빠른 러닝 속도 (Torch 보다는 느림)
• 구글 문서화 (Google!!)
• 넓은 사용자 커뮤니티: 많은 third-party 라이브러리 및
오픈소스 예제
• 강력한 시각화 기능
– 단점
• 잦은 문법 변경 (현재 릴리즈 문법이 다음릴리즈에 변경 ㅋㅋ)
• Define-by-Run 모델: 훈련 실행중에 변경 불가
• 세세한 모델링 / 훈련 설정이 초보자에게 어려움
118
누구나 TensorFlow!
J. Kang Ph.D.
Tensorflow 설치 (OSX, ubuntu)
Easy: pip를 이용한 설치
119
Ubuntu 16.04: shell commands
$ pyenv virtualenv 2.7.12 tensorflow #가상환경 설정
$ pyenv shell tensorflow
(tensorflow) $ pip install numpy scipy matplotlib scikit-learn pandas
(tensorflow) $ pip install –upgrade tensorflow==1.4.0
Collecting tensorflow==1.4.0
…..
(tnesorflow) $ pip list
.....
tensorflow (1.3.0)
.....
누구나 TensorFlow!
J. Kang Ph.D.
Tensorflow 설치 (win10)
Easy: anaconda3 prompt + pip를 이용한 설치
– Win10에서는…. Python 3.5 이상만 tensorflow와
호환된다고 함ㅠ
– Anaconda 4.4 with python 3.6설치
• https://www.anaconda.com/download/#windows
– jwkang 가이드 문서
• https://goo.gl/GvybRz
120
누구나 TensorFlow!
J. Kang Ph.D.
Tensorflow 설치 (win10)
Easy: anaconda prompt + pip +conda를
이용한 설치
– 관리자 권한으로 anaconda prompt 실행
121
Anaconda prompt in win10
 $ python –m pip install --upgrade pip
 $ pip install tensorflow
누구나 TensorFlow!
J. Kang Ph.D.
Tensorflow 설치
Adv: github에서 직접 소스 다운해서 설치
– 자신의 러닝머신에 커스터 마이즈해서 빌드
• CPU / GPU support
• Python 버전
• CUDA 버전
– 러닝 속도 최적화
– 링크 참고
• http://startupphd.blogspot.kr/2017/06/git-source-tensorflow-r12-with-gpu.html
122
누구나 TensorFlow!
J. Kang Ph.D.
LAB2: helloWorld in Tensorflow
Pip를 통해서 tensorflow를 설치하고 helloWorld를
찍어보자!
– 일단 무작정 따라해 보자
– 파이참 project 생성후 project interpreter 설정
123
누구나 TensorFlow!
J. Kang Ph.D.
LAB2: helloWorld in Tensorflow
Pip를 통해서 tensorflow를 설치하고 helloWorld를
찍어보자!
124
lab2_runHelloTensorflow.py
(tensorflow) $ vim helloworld.py
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!')
sess = tf.Session()
print ('[Lab2] %s' % sess.run(hello))
# Hello, TensorFlow!
a = tf.constant(10)
b = tf.constant(32)
print ('[Lab2] a + b = %s' % sess.run(a+b))
# 42
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
계산그래프 (Computational graph)
– 정의: 연산노드와 텐서노드(Variable/Constant)로 구성된
그래프로 학습 모델을 묘사한다.
125
그림출처: https://medium.com/@camrongodbout/tensorflow-
in-a-nutshell-part-one-basics-3f4403709c9d
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
계산그래프 (Computational graph)
– 정의: 연산노드와 텐서노드(Variable/Constant)로 구성된
그래프로 학습 모델을 묘사한다.
126
그림출처: https://medium.com/@camrongodbout/tensorflow-
in-a-nutshell-part-one-basics-3f4403709c9d
연산노드 텐서노드텐서노드
텐서노드
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
계산그래프 (Computational graph)
– 텐플 (TensorFlow) 스크립트는 두부분으로 구성된다.
• Part I) 계산 그래프 정의 하기
• Part II) 계산 그래프 평가 하기
127
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
PART I) 계산그래프 정의하기
128
ex_runTFconstant.py
#-*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
g = tf.Graph()
with g.as_default():
x = tf.constant(6,name="x_const")# 상수노드 1
y = tf.constant(14,name="y_const") # 상수 노드2
sum = tf.add(x,y,name="sum_xy")# 연산 노드
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
PART I) 계산그래프 정의하기
– tf.constant()는 상수 Tensor입니다.
129
+
x = 6 y = 14
x = tf.constant(6,name="x_const") y = tf.constant(14,name=”y_const")
sum = tf.add(x,y,name="sum_xy")
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
PART II) 계산그래프 평가하기
– 계산그래프를 평가하기 위해서는 tf.Session()을 열어야
한다.
130
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
PART II) 계산그래프 평가하기
– 계산그래프를 평가하기 위해서는 tf.Session()을 열어야
한다.
– 응? Session() 연다구?
131
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
PART II) 계산그래프 평가하기
– 계산그래프를 평가하기 위해서는 tf.Session()을 열어야
한다.
– 응? Session() 연다구?
•  session()을 연다는 것은
• 1) Front-end interface(python)을 통해서 계산디바이스 (cpu든
gpu든 cloud computing이든)에 접속하고
• 2) 계산그래프 구조를 전달하여 평가준비를 시키는 것
– https://www.tensorflow.org/programmers_guide/graphs
132
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
PART II) 계산그래프 평가하기
– 계산그래프를 평가하기 위해서는 tf.Session()을 열어야
한다.
– 방법1: tf.Session().run() 메소드
• sess = tf.Session()
• sess=tf.Session(graph=graph0)
• sess.run(x)
• sess.run(y)
• sess.run(sum)
133
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
PART II) 계산그래프 평가하기
– 계산그래프를 평가하기 위해서는 tf.Session()을 열어야
한다.
– 방법2: with 키워드 이용하기
• Indent 안 블럭에서는 매번 run()을 호출하지 않아도 된다.
• 블럭이 끝나면 자동으로 session이 종료된다.
– sum.eval()
• tf.constant()는 그래프 평가 중에 값이 변경될 수 없다.
134
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
PART II) 계산그래프 평가하기
135
ex_runTFconstant.py
#-*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
g = tf.Graph()
with g.as_default():
x = tf.constant(6,name="x_const")
y = tf.constant(14,name="y_const")
sum = tf.add(x,y,name="sum_xy")
# 세션 블럭 시작
with tf.Session(graph=g) as sess:
print ('sum.eval()=%d'%sum.eval())
print ('sess.run(sum)=%d'%sess.run(sum))
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
PART II) 계산그래프 평가하기
136
ex_runTFconstant.py
#-*- coding: utf-8 -*-
import tensorflow as tf
import numpy as np
g = tf.Graph()
with g.as_default():
x = tf.constant(6,name="x_const")
y = tf.constant(14,name="y_const")
sum = tf.add(x,y,name="sum_xy")
# 세션 블럭 시작 (with g.as_default() 블록에 속하므로 g를 default graph로 취급)
with tf.Session() as sess:
print ('sum.eval()=%d'%sum.eval())
print ('sess.run(sum)=%d'%sess.run(sum))
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
PART II) 계산그래프 평가하기
– tf.constant()는 그래프 평가중 값이 변경될 수 없다.
137
+
x = 6 y = 14
x = tf.constant(6,name="x_const") y = tf.constant(14,name=”y_const")
sum = tf.add(x,y,name="sum_xy")
6 14
20
누구나 TensorFlow!
J. Kang Ph.D.
Revisit LAB2
계산그래프 정의/평가 파트를 구분해보자
138
lab2_runHelloTensorflow.py
(tensorflow) $ vim helloworld.py
import tensorflow as tf
hello = tf.constant('Hello, TensorFlow!') # graph construction
sess = tf.Session() # graph에 대한 명시가 없으면 default graph사용
print ('[Lab2] %s' % sess.run(hello) ) # graph evaluation
# Hello, TensorFlow!
a = tf.constant(10)
b = tf.constant(32)
print ('[Lab2] a + b = %s' % sess.run(a+b))
# 42
누구나 TensorFlow!
J. Kang Ph.D.
LAB2.5 Matrix Multiplication
Matrix multiplication Tensorflow로 해보기
– 1 by 2 vector 생성 [[2.,3.]]
– 2 by 1 vector 생성 [[1.],[2.]]
– tf.matmul(mtx1,mtx2)
– 세션 생성
– 세션 실행
– 결과 출력
– 세션 종료
139
누구나 TensorFlow!
J. Kang Ph.D.
LAB2.5 Matrix Multiplication
Matrix multiplication Tensorflow로 해보기
140
lab25_runTFmatmul.py
(tensorflow) $ vim lab25_runTFmatmul.py
import tensorflow as tf
mtx1 = tf.constant([[2., 3.]]) # 1 by 2 vector 생성
mtx2 = tf.constant([[1.],[2.]]) # 2 by 1 vector 생성
product = tf.matmul(mtx1,mtx2)
sess = tf.Session()
eval_result = sess.run(product)
print (‘# [TF result] eval_result = %s’ % eval_result)
sess.close()
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
tf.Variable()
– tf.constant()와 는 다르게 그래프 평가 중 값이 변경될 수 있다.
– 그래프 평가중 중간 결과값 저장에 사용
– 값을 할당하기 위해서는 tf.assign()을 사용한다.
141
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
tf.Variable()
142
ex_runTFvariable.py
import tensorflow as tf
g = tf.Graph()
with g.as_default():
state = tf.Variable(0, name="cnt")
one = tf.constant(1) # 상수 노드
add_one = tf.add(state, one) # 연산 노드
cnt_update = tf.assign(state, add_one) # state에 연산결과를 대입
# 변수는 그래프가 올라간 뒤 ‘init’ 연산 실행으로 초기화
init_op = tf.global_variables_initializer()
# 계산 그래프를 올리고 연산을 실행합니다.
with tf.Session() as sess:
sess.run(init_op) #변수를 사용하기 위해서 ‘init’ 연산을 실행
print(sess.run(state)) # ‘state’의 초기값 출력
# ‘state’를 갱신하는 연산 실행 후 ‘state’를 출력
for _ in range(3):
sess.run(cnt_update)
print(sess.run(state))
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
tf.Variable()
143
+
one = 1 State
state =
tf.Variable(0,name=”cnt”
add_one = tf.add(state,one)
1 0,1,2,…
x = tf.constant(1)
cnt_update = tf.assign(state, add_one)
1,2,3,…
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
tf.placeholder()와 data feeding
– 계산 그래프 평가 실행중 그래프 입력에 훈련 데이터
값을 전달 할 수 있다.
– 평가 실행중 같은 그래프 연산을 다른 입력값을 가지고
반복 수행할 수 있다.
– Online-learning을 가능하게 한다.
144
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Online Learning
– 기억? 나죠?
145
Study the
Problem
Train online
ML algorithm
Analyze
errors
Evaluate
Release!
Lots of Data
Chop into
pieces
누구나 TensorFlow!
J. Kang Ph.D.
Types of ML Systems
Online Learning
– 기억? 나죠?
146
Study the
Problem
Train online
ML algorithm
Analyze
errors
Evaluate
Release!
Lots of Data
Chop into
pieces
Data feeding!
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow 기본요소
tf.placeholder()와 data feeding
147
ex_runTFfeed.py
import tensorflow as tf
in1 = tf.placeholder(tf.float32)
in2 = tf.placeholder(tf.float32)
mul_op = tf.multiply(in1, in2)
with tf.Session() as sess:
# 계산 그래프를 세션에 올리고 그 입력으로 아래를 그래프 내에서 할당
print(sess.run([mul_op], feed_dict={in1:[6.], in2:[14.]}))
누구나 TensorFlow!
J. Kang Ph.D.
TensorFlow API reference
모르는 API가 나오면 스스로 찾아보자!
– https://www.tensorflow.org/api_docs/python/
148
누구나 TensorFlow!
J. Kang Ph.D.
3. Tensorflow 준비하기
- 왜 TensorFlow인가? + TensorFlow 설치
- LAB2: Helloworld in TensorFlow
- TensorFlow의 기본요소
- LAB3: TensorFlow 기본예제, Line-fitting -
이제한번 해보자!
149
누구나 TensorFlow!
J. Kang Ph.D.
Data set의 종류
Training Set
– For model training
Validation Set
– For overfitting preventing
– Learning parameter adjustment
• Learning_rate
• Batch_size
Test Set
– For final performance evaluation
Training : validation : test = 5:3:2
150
누구나 TensorFlow!
J. Kang Ph.D.
머신러닝 훈련 단계
 step I: 해결해야 할 문제 파악하기
 step II: 데이터 수집 + 정제하기 + 관찰하기
 step III: 훈련 모델 정하기
– Linear model ?, Neural network?
– Types of Activation functions ?
– Number of layers?
 step IV: cost function 정하기
– 어떤 cost를 가지고 모델 파라미터를 훈련할 것인가?
– MSE, MAE, cross-entropy,…
151
누구나 TensorFlow!
J. Kang Ph.D.
머신러닝 훈련 단계
 step V: 모델 파라미터 찾기위한 optimizer 정하기
– 어떤 solver로 최적화 문제를 풀것인가?
– Gradient descent?, Conjugate gradient? Adam optimizer ?
 step VI: 훈련 설정 정하기
– 데이터 feeding 설정
• training_size : 전체 training set 크기
• batch_size: 단일 minibatch processing에 들어갈 batch사이즈
• Batch 횟수 : total_batch = int(training_size / batch_size)
– 최적화 Solver 설정
• Training_epoch : 같은 데이터 통한 훈련 반복횟수
• Learning_rate: 최적화 속도 opt solver의 단일스텝의 크기
152
누구나 TensorFlow!
J. Kang Ph.D.
Training epoch loop
– Overfitting 방지용: validation set을 가지고 함께 평가
Total_batch loop
– 모델 훈련용: training set을 minibatch로 쪼개서 훈련
153
Loop configuration
for epoch in range(training_epochs):
total_batch = int(training_size / batch_size)
for i in range(total_batch):
# minibatch training by optimizer here
누구나 TensorFlow!
J. Kang Ph.D. 154
- 1) ML모델 수정
- Training set performance
- 2) ML모델 수정 + 러닝 파라미터 조정
- Validation set performance
- 2) 데이터 셋 추가
- Test set performance
누구나 TensorFlow!
J. Kang Ph.D.
LAB3: TensorFlow, Line-fitting
일단 무작정 따라해보자 !
– Ex line-fitting example
• GitHub link
– https://github.com/jwkanggist/EveryBodyTensorFlow/blob/master/lab3_runTFLineFitting.py
• 입력 X, 출력 Y
155
Y
X
누구나 TensorFlow!
J. Kang Ph.D.
ML training in Tensorflow
 텐플에서 모델을 훈련을 위한 스크립트의 기본구성은
다음과 같다.
– Step 1) 데이터셋 준비하기
– Step 2) 러닝 파라미터 설정하기
– Step 3) 계산 그래프 정의하기
– Step 4) 성능 측정 모델 정의하기
– Step 5) 모델 훈련시키기
– Step 6) 시각화 하기
156
누구나 TensorFlow!
J. Kang Ph.D.
ML training in Tensorflow
Step I) 데이터 셋 (X,Y) 준비하기
ML 좋은 데이터 셋을 준비하는 것이 80% 이다!!
X: feature, Y: label
– 1) Outlier & Irregular 데이터 제거
• 빈칸, NaN
– 2) Normalization of data set X
• 데이터 크기(abs)가 [0,1] 범위 안에 들어오록 스케일링
• norm_X = abs( X ) / max_value_abs * sign(X)
– 3) Standardization of data set X
• 데이터의 분포가 zero-mean, unit-variance를 가지게 스케일링
• stand_X = ( X – mean(X) ) / std(X)
157
누구나 TensorFlow!
J. Kang Ph.D. 158
lab3_runTFLineFitting.py
# experiment data generation
total_size = 5000
training_size = 4000
validation_size = 1000
xsize = 20
x_data = np.zeros([xsize, total_size])
a_true = 2
b_true = 0.5
for i in range(total_size):
x_data[:,i] = np.linspace(0,10,xsize)
noise_var = 1.0
noise = np.sqrt(noise_var) * np.random.randn(xsize,total_size)
y_clean = a_true * x_data + b_true
y_data = y_clean + noise
# data segmentation
x_training_data = x_data[:,0:training_size]
y_training_data = y_data[:,0:training_size]
x_validation_data = x_data[:,training_size:-1]
y_validation_data = y_data[:,training_size:-1]
누구나 TensorFlow!
J. Kang Ph.D.
ML training in Tensorflow
Step II) 러닝 파라미터 설정하기
– 1) training_epochs > 0 : 최적화 반복 학습 횟수
• 매 iteration 마다 같은 데이터셋 사용
– 2) learning_rate in (0,1] : model이 데이터로 부터
학습하는 속도를 결정한다.
• learning_rate↑  학습속도 ↑, 발산가능성↑
– 3) batch_size 결정:
• Training data가 batch_size 단위로 나누어 져서 총 total_batch =
int(training_size / batch_size)회 학습이 수행됨
• 데이터 feeding loop가 도는 동안 cost는 누적 계산된다.
159
누구나 TensorFlow!
J. Kang Ph.D. 160
lab3_runTFLineFitting.py
# configure training parameters =====================================
learning_rate = 0.000001
training_epochs = 20
batch_size = 100
display_step = 1
total_batch = int(training_size/batch_size) #
누구나 TensorFlow!
J. Kang Ph.D.
ML training in Tensorflow
Step III) 계산 그래프 정의하기
Ex) Linear model: pred_Y = a*x + b, MSE cost func.
– 1) training data (X, Y) 를 feeding 하기위한 tf.placehoder Tensor 선언
– 2) model parameter (a, b)값 저장을 위한 tf.Variable Tensor 선언
– 3) 학습모델의 입출력 관계 설정
• linear model: y_pred = a * x + b
– 4) Cost function 설정
• cost = tf.reduce_mean(tf.reduce_sum( tf.square(y - pred_y) ,
reduction_indices=1), name="mse")
– 5) optimizer 설정 (GradientDescent)
• optimizer =
tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
161
누구나 TensorFlow!
J. Kang Ph.D. 162
lab3_runTFLineFitting.py
# computational TF graph construction ================================
x = tf.placeholder(tf.float32, [xsize,None])
y = tf.placeholder(tf.float32, [xsize,None])
# Set model weights which is calculated in the TF graph
a = tf.Variable(0.) # initialization by 1
b = tf.Variable(0.)
print ('TF graph nodes are defined')
# Construct model
pred_y = a * x + b
# Minimize error using MSE function
cost = tf.reduce_mean(tf.reduce_sum( tf.square(y - pred_y) , reduction_indices=1),
name="mse")
# Gradient Descent
optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost)
print ('Functions in TF graph are ready')
누구나 TensorFlow!
J. Kang Ph.D.
ML training in Tensorflow
Step IV) 성능 측정 모델 정의하기
– 학습결과에 대한 성능을 측정하기 위한 model을 정의
– 학습모델에 의한 예측값과 실제 데이터의 label값이
어느정도로 일치하는 측정한다.
• 1) Classification: Miss-classification rate를 사용
– training set과 validation set의 성능을 나누어서 측정
– Bayesian theory 에 근거함
• 2) Regression: Mean squared error 사용
163
누구나 TensorFlow!
J. Kang Ph.D. 164
lab3_runTFLineFitting.py
## Performance evaluation model ========================_y===========
# y : data output
# pred_y: prediction output by model, a x + b
correct_prediction = cost
# Calculate error rate using data --------------
accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
error_rate_training = np.zeros(training_epochs)
error_rate_validation = np.zeros(training_epochs)
누구나 TensorFlow!
J. Kang Ph.D.
ML training in Tensorflow
 Step V) 모델 훈련시키기
– 1) 정의한 계산그래프를 tf.Session()에 올려서 계산
– 2) tf.Session() 안에서 variable사용을 위해서…
• init = tf.global_variables_initializer() 정의
• tf.Session() 안에서 가장 먼저 실행한다. (sess.run(init) # this for variable use)
– 3) tf.Sesson()안에서 두개의 for loop 로 구성된다.
• Training epoch Loop: 최적화 반복 학습을 위한 loop
• Total batch Loop: 데이터 feeding 를 위한 loop
– 4) placeholder (x,y)에 training data가 feeding
• 여기서 전체 데이터가 total_batch 번으로 나뉘어서 feeding된다.
• 데이터 feeding loop가 도는 동안 cost는 누적 계산된다.
165
누구나 TensorFlow!
J. Kang Ph.D. 166
lab3_runTFLineFitting.py
# Launch the graph (execution) ========================================
# Initializing the variables
init = tf.global_variables_initializer()
## -------------------- Learning iteration start --------------------
with tf.Session() as sess:
sess.run(init) # this for variable use
# Training cycle
for epoch in range(training_epochs): # training_epoch loop
avg_cost = 0.
total_batch = int(training_size/batch_size)
# Loop over all batches
for i in range(total_batch): # total batch loop
[ Total batch loop inside …]
print("--------------------------------------------")
print("Optimization Finished!")
누구나 TensorFlow!
J. Kang Ph.D. 167
lab3_runTFLineFitting.py
for i in range(total_batch): # total batch loop
data_start_index = i * batch_size
data_end_index = (i + 1) * batch_size
# feed traing data --------------------------
batch_xs = x_training_data[:,data_start_index:data_end_index]
batch_ys = y_training_data[:,data_start_index:data_end_index]
#----------------------------------------------
# Run optimization op (backprop) and cost op (to get loss value)
# feedign training data
_, local_batch_cost = sess.run([optimizer, cost], feed_dict={x: batch_xs, y: batch_ys})
# Compute average loss
avg_cost += local_batch_cost / total_batch
# print ("At %d-th batch in %d-epoch, avg_cost = %f" % (i,epoch,avg_cost) )
# Display logs per epoch step
if (epoch+1) % display_step == 0:
print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost/batch_size))
batch_xs = x_training_data
batch_ys = y_training_data
error_rate_training[epoch] = accuracy.eval({x: batch_xs, y: batch_ys},session=sess)/training_size
error_rate_validation[epoch] = accuracy.eval({x: x_validation_data,
y:y_validation_data},session=sess)/validation_size
print("Training set MSE:", error_rate_training[epoch])
print("Validation set MSE:", error_rate_validation[epoch])
누구나 TensorFlow!
J. Kang Ph.D.
ML training in Tensorflow
Step VI) 시각화 하기
168
누구나 TensorFlow!
J. Kang Ph.D. 169
lab3_runTFLineFitting.py
pred_a = sess.run(a)
pred_b = sess.run(b)
##-------------------------------------------
# # training Result display
print("Validation set Err rate:", accuracy.eval({x: x_validation_data, y:
y_validation_data},session=sess)/validation_size)
hfig1 = plt.figure(1,figsize=(10,10))
epoch_index = np.array([elem for elem in range(training_epochs)])
plt.plot(epoch_index,error_rate_training,label='Training data',color='r',marker='o')
plt.plot(epoch_index,error_rate_validation,label='Validation data',color='b',marker='x')
plt.legend()
plt.title('MSE of prediction:')
plt.xlabel('Iteration epoch')
plt.ylabel('MSE')
hfig2 = plt.figure(2,figsize=(10,10))
pred_y = pred_a * x_data[:,0] + pred_b
plt.plot(x_validation_data[:,0],y_validation_data[:,0],label='noisy data',color='b',marker='*')
plt.plot(x_validation_data[:,0], pred_y,label='prediction',color='r')
plt.legend()
plt.title('A line fitting example:')
plt.xlabel('X data')
plt.ylabel('Y data')
plt.show()
누구나 TensorFlow!
J. Kang Ph.D.
ML training in Tensorflow
Step VI) further 시각화 하기
– Tensorboard를 이용해 보자!
– Tensorflow training 과정을 로그파일로 저장하고, 훈련이후에
localhosting을 이용해서 로그파일을 시각화 해주는 도구
 주요기능
– 주요 훈련지표의 training step에 따른 트래킹
– 그래프의 variable 값의 분포 시각화
– 계산그래프 구조의 시각화
– 참고문서: https://docs.google.com/document/d/1BMZdIXp-3lUWYXaJcJZtcgpX0VAlDGRueZ7-bYht198/edit
170
누구나 TensorFlow!
J. Kang Ph.D.
End of Day1 Lecture
Thank you
–Day2 Lecture link here
171
누구나 TensorFlow!
J. Kang Ph.D.
Call for Contribution to EveryTF Group!
jwkang@soundl.ly 로 메일
– 같이 집단 지성을 만들어가요!
– 관심 분야!
• GAN / VAE
• RL
• Mobile CNN
• Etc. Applications
172
누구나 TensorFlow!
J. Kang Ph.D.
모두연 MoT랩 소개
딥러닝을 활용하여 세상을 이롭게 할 IoT/Mobile
App 개발에 대한 연구를 같이 해봐요!!
 https://www.facebook.com/lab4all/posts/761099760749661
 jwkang@soundl.ly 로 메일
Keywords:
– Thin CNN Model
– Model Pruning
– Tensorflow + lite
– Embedded Sys. (IoT)
– Android Mobile/Things
173

More Related Content

What's hot

MATLAB Programming BASIC @ GIST winter school 2015
MATLAB Programming BASIC @ GIST winter school 2015 MATLAB Programming BASIC @ GIST winter school 2015
MATLAB Programming BASIC @ GIST winter school 2015
Jaewook. Kang
 
181123 poseest101 devfest_pangyo_jwkang
181123 poseest101 devfest_pangyo_jwkang181123 poseest101 devfest_pangyo_jwkang
181123 poseest101 devfest_pangyo_jwkang
Jaewook. Kang
 
Tensorflow for Deep Learning(SK Planet)
Tensorflow for Deep Learning(SK Planet)Tensorflow for Deep Learning(SK Planet)
Tensorflow for Deep Learning(SK Planet)
Tae Young Lee
 
한글 언어 자원과 R: KoNLP 개선과 활용
한글 언어 자원과 R: KoNLP 개선과 활용한글 언어 자원과 R: KoNLP 개선과 활용
한글 언어 자원과 R: KoNLP 개선과 활용
r-kor
 
텐서플로우 설치도 했고 튜토리얼도 봤고 기초 예제도 짜봤다면 TensorFlow KR Meetup 2016
텐서플로우 설치도 했고 튜토리얼도 봤고 기초 예제도 짜봤다면 TensorFlow KR Meetup 2016텐서플로우 설치도 했고 튜토리얼도 봤고 기초 예제도 짜봤다면 TensorFlow KR Meetup 2016
텐서플로우 설치도 했고 튜토리얼도 봤고 기초 예제도 짜봤다면 TensorFlow KR Meetup 2016
Taehoon Kim
 
기계 학습의 현재와 미래
기계 학습의 현재와 미래기계 학습의 현재와 미래
기계 학습의 현재와 미래
Joon Kim
 
지적 대화를 위한 깊고 넓은 딥러닝 PyCon APAC 2016
지적 대화를 위한 깊고 넓은 딥러닝 PyCon APAC 2016지적 대화를 위한 깊고 넓은 딥러닝 PyCon APAC 2016
지적 대화를 위한 깊고 넓은 딥러닝 PyCon APAC 2016
Taehoon Kim
 
[226]대용량 텍스트마이닝 기술 하정우
[226]대용량 텍스트마이닝 기술 하정우[226]대용량 텍스트마이닝 기술 하정우
[226]대용량 텍스트마이닝 기술 하정우
NAVER D2
 
파이썬으로 익히는 딥러닝
파이썬으로 익히는 딥러닝파이썬으로 익히는 딥러닝
파이썬으로 익히는 딥러닝
SK(주) C&C - 강병호
 
Python을 활용한 챗봇 서비스 개발 2일차
Python을 활용한 챗봇 서비스 개발 2일차Python을 활용한 챗봇 서비스 개발 2일차
Python을 활용한 챗봇 서비스 개발 2일차
Taekyung Han
 
딥러닝 기반의 자연어처리 최근 연구 동향
딥러닝 기반의 자연어처리 최근 연구 동향딥러닝 기반의 자연어처리 최근 연구 동향
딥러닝 기반의 자연어처리 최근 연구 동향
LGCNSairesearch
 
[224] backend 개발자의 neural machine translation 개발기 김상경
[224] backend 개발자의 neural machine translation 개발기 김상경[224] backend 개발자의 neural machine translation 개발기 김상경
[224] backend 개발자의 neural machine translation 개발기 김상경
NAVER D2
 
딥러닝을 이용한 자연어처리의 연구동향
딥러닝을 이용한 자연어처리의 연구동향딥러닝을 이용한 자연어처리의 연구동향
딥러닝을 이용한 자연어처리의 연구동향
홍배 김
 
딥러닝 자연어처리 - RNN에서 BERT까지
딥러닝 자연어처리 - RNN에서 BERT까지딥러닝 자연어처리 - RNN에서 BERT까지
딥러닝 자연어처리 - RNN에서 BERT까지
deepseaswjh
 
[221] 딥러닝을 이용한 지역 컨텍스트 검색 김진호
[221] 딥러닝을 이용한 지역 컨텍스트 검색 김진호[221] 딥러닝을 이용한 지역 컨텍스트 검색 김진호
[221] 딥러닝을 이용한 지역 컨텍스트 검색 김진호
NAVER D2
 
파이썬으로 익히는 딥러닝 기본 (18년)
파이썬으로 익히는 딥러닝 기본 (18년)파이썬으로 익히는 딥러닝 기본 (18년)
파이썬으로 익히는 딥러닝 기본 (18년)
SK(주) C&C - 강병호
 
인공지능 방법론 - Deep Learning 쉽게 이해하기
인공지능 방법론 - Deep Learning 쉽게 이해하기인공지능 방법론 - Deep Learning 쉽게 이해하기
인공지능 방법론 - Deep Learning 쉽게 이해하기
Byoung-Hee Kim
 
딥러닝 - 역사와 이론적 기초
딥러닝 - 역사와 이론적 기초딥러닝 - 역사와 이론적 기초
딥러닝 - 역사와 이론적 기초
Hyungsoo Ryoo
 
임태현, Text-CNN을 이용한 Sentiment 분설모델 구현
임태현, Text-CNN을 이용한 Sentiment 분설모델 구현임태현, Text-CNN을 이용한 Sentiment 분설모델 구현
임태현, Text-CNN을 이용한 Sentiment 분설모델 구현
태현 임
 
[기초개념] Recurrent Neural Network (RNN) 소개
[기초개념] Recurrent Neural Network (RNN) 소개[기초개념] Recurrent Neural Network (RNN) 소개
[기초개념] Recurrent Neural Network (RNN) 소개
Donghyeon Kim
 

What's hot (20)

MATLAB Programming BASIC @ GIST winter school 2015
MATLAB Programming BASIC @ GIST winter school 2015 MATLAB Programming BASIC @ GIST winter school 2015
MATLAB Programming BASIC @ GIST winter school 2015
 
181123 poseest101 devfest_pangyo_jwkang
181123 poseest101 devfest_pangyo_jwkang181123 poseest101 devfest_pangyo_jwkang
181123 poseest101 devfest_pangyo_jwkang
 
Tensorflow for Deep Learning(SK Planet)
Tensorflow for Deep Learning(SK Planet)Tensorflow for Deep Learning(SK Planet)
Tensorflow for Deep Learning(SK Planet)
 
한글 언어 자원과 R: KoNLP 개선과 활용
한글 언어 자원과 R: KoNLP 개선과 활용한글 언어 자원과 R: KoNLP 개선과 활용
한글 언어 자원과 R: KoNLP 개선과 활용
 
텐서플로우 설치도 했고 튜토리얼도 봤고 기초 예제도 짜봤다면 TensorFlow KR Meetup 2016
텐서플로우 설치도 했고 튜토리얼도 봤고 기초 예제도 짜봤다면 TensorFlow KR Meetup 2016텐서플로우 설치도 했고 튜토리얼도 봤고 기초 예제도 짜봤다면 TensorFlow KR Meetup 2016
텐서플로우 설치도 했고 튜토리얼도 봤고 기초 예제도 짜봤다면 TensorFlow KR Meetup 2016
 
기계 학습의 현재와 미래
기계 학습의 현재와 미래기계 학습의 현재와 미래
기계 학습의 현재와 미래
 
지적 대화를 위한 깊고 넓은 딥러닝 PyCon APAC 2016
지적 대화를 위한 깊고 넓은 딥러닝 PyCon APAC 2016지적 대화를 위한 깊고 넓은 딥러닝 PyCon APAC 2016
지적 대화를 위한 깊고 넓은 딥러닝 PyCon APAC 2016
 
[226]대용량 텍스트마이닝 기술 하정우
[226]대용량 텍스트마이닝 기술 하정우[226]대용량 텍스트마이닝 기술 하정우
[226]대용량 텍스트마이닝 기술 하정우
 
파이썬으로 익히는 딥러닝
파이썬으로 익히는 딥러닝파이썬으로 익히는 딥러닝
파이썬으로 익히는 딥러닝
 
Python을 활용한 챗봇 서비스 개발 2일차
Python을 활용한 챗봇 서비스 개발 2일차Python을 활용한 챗봇 서비스 개발 2일차
Python을 활용한 챗봇 서비스 개발 2일차
 
딥러닝 기반의 자연어처리 최근 연구 동향
딥러닝 기반의 자연어처리 최근 연구 동향딥러닝 기반의 자연어처리 최근 연구 동향
딥러닝 기반의 자연어처리 최근 연구 동향
 
[224] backend 개발자의 neural machine translation 개발기 김상경
[224] backend 개발자의 neural machine translation 개발기 김상경[224] backend 개발자의 neural machine translation 개발기 김상경
[224] backend 개발자의 neural machine translation 개발기 김상경
 
딥러닝을 이용한 자연어처리의 연구동향
딥러닝을 이용한 자연어처리의 연구동향딥러닝을 이용한 자연어처리의 연구동향
딥러닝을 이용한 자연어처리의 연구동향
 
딥러닝 자연어처리 - RNN에서 BERT까지
딥러닝 자연어처리 - RNN에서 BERT까지딥러닝 자연어처리 - RNN에서 BERT까지
딥러닝 자연어처리 - RNN에서 BERT까지
 
[221] 딥러닝을 이용한 지역 컨텍스트 검색 김진호
[221] 딥러닝을 이용한 지역 컨텍스트 검색 김진호[221] 딥러닝을 이용한 지역 컨텍스트 검색 김진호
[221] 딥러닝을 이용한 지역 컨텍스트 검색 김진호
 
파이썬으로 익히는 딥러닝 기본 (18년)
파이썬으로 익히는 딥러닝 기본 (18년)파이썬으로 익히는 딥러닝 기본 (18년)
파이썬으로 익히는 딥러닝 기본 (18년)
 
인공지능 방법론 - Deep Learning 쉽게 이해하기
인공지능 방법론 - Deep Learning 쉽게 이해하기인공지능 방법론 - Deep Learning 쉽게 이해하기
인공지능 방법론 - Deep Learning 쉽게 이해하기
 
딥러닝 - 역사와 이론적 기초
딥러닝 - 역사와 이론적 기초딥러닝 - 역사와 이론적 기초
딥러닝 - 역사와 이론적 기초
 
임태현, Text-CNN을 이용한 Sentiment 분설모델 구현
임태현, Text-CNN을 이용한 Sentiment 분설모델 구현임태현, Text-CNN을 이용한 Sentiment 분설모델 구현
임태현, Text-CNN을 이용한 Sentiment 분설모델 구현
 
[기초개념] Recurrent Neural Network (RNN) 소개
[기초개념] Recurrent Neural Network (RNN) 소개[기초개념] Recurrent Neural Network (RNN) 소개
[기초개념] Recurrent Neural Network (RNN) 소개
 

Similar to EveryBody Tensorflow module1 GIST Jan 2018 Korean

파이썬 생존 안내서 (자막)
파이썬 생존 안내서 (자막)파이썬 생존 안내서 (자막)
파이썬 생존 안내서 (자막)
Heungsub Lee
 
『고성능 파이썬』 - 맛보기
『고성능 파이썬』 - 맛보기『고성능 파이썬』 - 맛보기
『고성능 파이썬』 - 맛보기
복연 이
 
20160126_python
20160126_python20160126_python
20160126_python
Na-yeon Park
 
JetsonTX2 Python
 JetsonTX2 Python  JetsonTX2 Python
JetsonTX2 Python
taeseon ryu
 
파이썬을 배워야하는 이유 발표자료 - 김연수
파이썬을 배워야하는 이유 발표자료 - 김연수파이썬을 배워야하는 이유 발표자료 - 김연수
파이썬을 배워야하는 이유 발표자료 - 김연수
Yeon Soo Kim
 
Python Recipes for django girls seoul
Python Recipes for django girls seoulPython Recipes for django girls seoul
Python Recipes for django girls seoul
Joeun Park
 
Lecture 1: Introduction to Python and TensorFlow
Lecture 1: Introduction to Python and TensorFlowLecture 1: Introduction to Python and TensorFlow
Lecture 1: Introduction to Python and TensorFlow
Sang Jun Lee
 
코딩은 문제해결이다 (도구로써 파이썬)
코딩은 문제해결이다 (도구로써 파이썬)코딩은 문제해결이다 (도구로써 파이썬)
코딩은 문제해결이다 (도구로써 파이썬)
HYEONGNAM LEE
 
오픈소스 개발참여한 이야기 (NIPA 오픈프론티어 3기 송태웅)
오픈소스 개발참여한 이야기 (NIPA 오픈프론티어 3기 송태웅)오픈소스 개발참여한 이야기 (NIPA 오픈프론티어 3기 송태웅)
오픈소스 개발참여한 이야기 (NIPA 오픈프론티어 3기 송태웅)
Taeung Song
 
파이썬과 커뮤니티와 한국어 오픈데이터
파이썬과 커뮤니티와 한국어 오픈데이터파이썬과 커뮤니티와 한국어 오픈데이터
파이썬과 커뮤니티와 한국어 오픈데이터
Eunjeong (Lucy) Park
 
파이썬으로 할 수 있는 일 - 파이썬 기초 교육
파이썬으로 할 수 있는 일 - 파이썬 기초 교육파이썬으로 할 수 있는 일 - 파이썬 기초 교육
파이썬으로 할 수 있는 일 - 파이썬 기초 교육
테리엇
 
학교에선 알려주지 않는 오픈소스이야기 - 박치완님
학교에선 알려주지 않는 오픈소스이야기 - 박치완님학교에선 알려주지 않는 오픈소스이야기 - 박치완님
학교에선 알려주지 않는 오픈소스이야기 - 박치완님
NAVER D2
 
자바, 미안하다! 파이썬 한국어 NLP
자바, 미안하다! 파이썬 한국어 NLP자바, 미안하다! 파이썬 한국어 NLP
자바, 미안하다! 파이썬 한국어 NLP
Eunjeong (Lucy) Park
 
졸업후 취업까지.ssul
졸업후 취업까지.ssul졸업후 취업까지.ssul
졸업후 취업까지.ssul
승표 홍
 
파이썬 소개
파이썬 소개 파이썬 소개
파이썬 소개
SeongHyun Ahn
 
제주 GDG 발표자료
제주 GDG 발표자료제주 GDG 발표자료
제주 GDG 발표자료
Jicheol Woo
 
맨땅에서 AI학습플랫폼을 만들기까지
맨땅에서 AI학습플랫폼을 만들기까지맨땅에서 AI학습플랫폼을 만들기까지
맨땅에서 AI학습플랫폼을 만들기까지
Sunwoo Park
 
Flask! - python web framework flask 튜토리얼
Flask! - python web framework flask 튜토리얼Flask! - python web framework flask 튜토리얼
Flask! - python web framework flask 튜토리얼
mangonamu
 
『Modern PHP』 - 미리보기
『Modern PHP』 - 미리보기『Modern PHP』 - 미리보기
『Modern PHP』 - 미리보기
복연 이
 
What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )
What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )
What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )
Gunhee Lee
 

Similar to EveryBody Tensorflow module1 GIST Jan 2018 Korean (20)

파이썬 생존 안내서 (자막)
파이썬 생존 안내서 (자막)파이썬 생존 안내서 (자막)
파이썬 생존 안내서 (자막)
 
『고성능 파이썬』 - 맛보기
『고성능 파이썬』 - 맛보기『고성능 파이썬』 - 맛보기
『고성능 파이썬』 - 맛보기
 
20160126_python
20160126_python20160126_python
20160126_python
 
JetsonTX2 Python
 JetsonTX2 Python  JetsonTX2 Python
JetsonTX2 Python
 
파이썬을 배워야하는 이유 발표자료 - 김연수
파이썬을 배워야하는 이유 발표자료 - 김연수파이썬을 배워야하는 이유 발표자료 - 김연수
파이썬을 배워야하는 이유 발표자료 - 김연수
 
Python Recipes for django girls seoul
Python Recipes for django girls seoulPython Recipes for django girls seoul
Python Recipes for django girls seoul
 
Lecture 1: Introduction to Python and TensorFlow
Lecture 1: Introduction to Python and TensorFlowLecture 1: Introduction to Python and TensorFlow
Lecture 1: Introduction to Python and TensorFlow
 
코딩은 문제해결이다 (도구로써 파이썬)
코딩은 문제해결이다 (도구로써 파이썬)코딩은 문제해결이다 (도구로써 파이썬)
코딩은 문제해결이다 (도구로써 파이썬)
 
오픈소스 개발참여한 이야기 (NIPA 오픈프론티어 3기 송태웅)
오픈소스 개발참여한 이야기 (NIPA 오픈프론티어 3기 송태웅)오픈소스 개발참여한 이야기 (NIPA 오픈프론티어 3기 송태웅)
오픈소스 개발참여한 이야기 (NIPA 오픈프론티어 3기 송태웅)
 
파이썬과 커뮤니티와 한국어 오픈데이터
파이썬과 커뮤니티와 한국어 오픈데이터파이썬과 커뮤니티와 한국어 오픈데이터
파이썬과 커뮤니티와 한국어 오픈데이터
 
파이썬으로 할 수 있는 일 - 파이썬 기초 교육
파이썬으로 할 수 있는 일 - 파이썬 기초 교육파이썬으로 할 수 있는 일 - 파이썬 기초 교육
파이썬으로 할 수 있는 일 - 파이썬 기초 교육
 
학교에선 알려주지 않는 오픈소스이야기 - 박치완님
학교에선 알려주지 않는 오픈소스이야기 - 박치완님학교에선 알려주지 않는 오픈소스이야기 - 박치완님
학교에선 알려주지 않는 오픈소스이야기 - 박치완님
 
자바, 미안하다! 파이썬 한국어 NLP
자바, 미안하다! 파이썬 한국어 NLP자바, 미안하다! 파이썬 한국어 NLP
자바, 미안하다! 파이썬 한국어 NLP
 
졸업후 취업까지.ssul
졸업후 취업까지.ssul졸업후 취업까지.ssul
졸업후 취업까지.ssul
 
파이썬 소개
파이썬 소개 파이썬 소개
파이썬 소개
 
제주 GDG 발표자료
제주 GDG 발표자료제주 GDG 발표자료
제주 GDG 발표자료
 
맨땅에서 AI학습플랫폼을 만들기까지
맨땅에서 AI학습플랫폼을 만들기까지맨땅에서 AI학습플랫폼을 만들기까지
맨땅에서 AI학습플랫폼을 만들기까지
 
Flask! - python web framework flask 튜토리얼
Flask! - python web framework flask 튜토리얼Flask! - python web framework flask 튜토리얼
Flask! - python web framework flask 튜토리얼
 
『Modern PHP』 - 미리보기
『Modern PHP』 - 미리보기『Modern PHP』 - 미리보기
『Modern PHP』 - 미리보기
 
What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )
What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )
What's new tensorflow ( Tensorflow.js , Tensorflow Hub, Tensorflow Serving )
 

More from Jaewook. Kang

190111 tf2 preview_jwkang_pub
190111 tf2 preview_jwkang_pub190111 tf2 preview_jwkang_pub
190111 tf2 preview_jwkang_pub
Jaewook. Kang
 
Cloud tpu jae_180814
Cloud tpu jae_180814Cloud tpu jae_180814
Cloud tpu jae_180814
Jaewook. Kang
 
Life is stair-like
Life is stair-likeLife is stair-like
Life is stair-like
Jaewook. Kang
 
A Simple Communication System Design Lab #4 with MATLAB Simulink
A Simple Communication System Design Lab #4 with MATLAB SimulinkA Simple Communication System Design Lab #4 with MATLAB Simulink
A Simple Communication System Design Lab #4 with MATLAB Simulink
Jaewook. Kang
 
A Simple Communication System Design Lab #3 with MATLAB Simulink
A Simple Communication System Design Lab #3 with MATLAB SimulinkA Simple Communication System Design Lab #3 with MATLAB Simulink
A Simple Communication System Design Lab #3 with MATLAB Simulink
Jaewook. Kang
 
A Simple Communication System Design Lab #2 with MATLAB Simulink
A Simple Communication System Design Lab #2 with MATLAB SimulinkA Simple Communication System Design Lab #2 with MATLAB Simulink
A Simple Communication System Design Lab #2 with MATLAB Simulink
Jaewook. Kang
 
A Simple Communication System Design Lab #1 with MATLAB Simulink
A Simple Communication System Design Lab #1 with MATLAB Simulink A Simple Communication System Design Lab #1 with MATLAB Simulink
A Simple Communication System Design Lab #1 with MATLAB Simulink
Jaewook. Kang
 
Jaewook Kang's Phd final defense @ 20151117
Jaewook Kang's  Phd final defense @ 20151117Jaewook Kang's  Phd final defense @ 20151117
Jaewook Kang's Phd final defense @ 20151117
Jaewook. Kang
 
Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...
Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...
Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...
Jaewook. Kang
 

More from Jaewook. Kang (9)

190111 tf2 preview_jwkang_pub
190111 tf2 preview_jwkang_pub190111 tf2 preview_jwkang_pub
190111 tf2 preview_jwkang_pub
 
Cloud tpu jae_180814
Cloud tpu jae_180814Cloud tpu jae_180814
Cloud tpu jae_180814
 
Life is stair-like
Life is stair-likeLife is stair-like
Life is stair-like
 
A Simple Communication System Design Lab #4 with MATLAB Simulink
A Simple Communication System Design Lab #4 with MATLAB SimulinkA Simple Communication System Design Lab #4 with MATLAB Simulink
A Simple Communication System Design Lab #4 with MATLAB Simulink
 
A Simple Communication System Design Lab #3 with MATLAB Simulink
A Simple Communication System Design Lab #3 with MATLAB SimulinkA Simple Communication System Design Lab #3 with MATLAB Simulink
A Simple Communication System Design Lab #3 with MATLAB Simulink
 
A Simple Communication System Design Lab #2 with MATLAB Simulink
A Simple Communication System Design Lab #2 with MATLAB SimulinkA Simple Communication System Design Lab #2 with MATLAB Simulink
A Simple Communication System Design Lab #2 with MATLAB Simulink
 
A Simple Communication System Design Lab #1 with MATLAB Simulink
A Simple Communication System Design Lab #1 with MATLAB Simulink A Simple Communication System Design Lab #1 with MATLAB Simulink
A Simple Communication System Design Lab #1 with MATLAB Simulink
 
Jaewook Kang's Phd final defense @ 20151117
Jaewook Kang's  Phd final defense @ 20151117Jaewook Kang's  Phd final defense @ 20151117
Jaewook Kang's Phd final defense @ 20151117
 
Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...
Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...
Introduction to Soundlly 2nd screen services and technology: Seminar in 금오공대 ...
 

EveryBody Tensorflow module1 GIST Jan 2018 Korean

  • 1. 누구나 TensorFlow! J. Kang Ph.D. 누구나 TensorFlow - Module1 : 파이썬 기초 + 머신러닝 + 텐써 플로우 개요 Jaewook Kang, Ph.D. jwkang@soundl.ly Jan. 2018 1 © 2017-2018 Jaewook Kang All Rights Reserved
  • 2. 누구나 TensorFlow! J. Kang Ph.D.  GIST EEC Ph.D. (2015)  신호처리 과학자, 삽질러  누구나 TensorFlow Group leader  https://www.facebook.com/jwkkang  좋아하는 것:  통계적 신호처리 / 무선통신 신호처리  임베디드 오디오 DSP C/C++라이브러리 구현  머신러닝 기반 오디오 신호처리 알고리즘  배워서 남주기 2  대표논문: Jaewook Kang, et al., "Bayesian Hypothesis Test using Nonparametric Belief Propagation for Noisy Sparse Recovery," IEEE Trans. on Signal process., Feb. 2015 Jaewook Kang et al., "Fast Signal Separation of 2D Sparse Mixture via Approximate Message- Passing," IEEE Signal Processing Letters, Nov. 2015 Jaewook Kang (강재욱) 소 개
  • 3. 누구나 TensorFlow! J. Kang Ph.D. Contributors to EveryTF Group! 3 Jaewook Kang (Soundlly) Soonwon Ka (Soundlly) Jihwan Lee (SNU) Cheolyoung Kwak (SNU) Hyoyoung Jung (GIST) Donghyun Kim (GIST)
  • 4. 누구나 TensorFlow! J. Kang Ph.D. Reviewers  Sun Young Park (Korea Univ.)  Hongkyong Kim (Korea Aerospace Research Institute, GIST)  Hansol Kim (GIST) 4
  • 5. 누구나 TensorFlow! J. Kang Ph.D. 두가지 화두 • 학계와 산업계의 거리 • 지식의 빈부 격차 5
  • 6. 누구나 TensorFlow! J. Kang Ph.D. 학계와 산업계의 거리 • 학계는 19세기 시스템 • 논문과 학회 • 리뷰프로세스와 퍼브리쉬 • CS 박사학위기간 5년 이상 • 산업계는 21세기 시스템 • 온라인 커뮤니티 & 컨트리뷰터 • 오픈소스 + 개방형 플랫폼 • 블로그 6
  • 7. 누구나 TensorFlow! J. Kang Ph.D. 학계와 산업계의 거리 • 당신은 둘사이에 어떤 연결고리가 될수 있는가? • 학계 • 새로운 발견은 대부분 서양학계에서 나온다 • 무선통신, 딥러닝 • 한우물 정신 • 이론적 토대마련, 해석 • 실패와 도전 • 산업계 • 빠른 피드백 사이클 • 머니 머니 머니!: 현실세계에서 효용 == 머니 • 최대한 많은 상호작용 7
  • 8. 누구나 TensorFlow! J. Kang Ph.D. 지식의 빈부 격차 • 시간에 따라서 지식의 빈부격차가 점점 벌어집니다. • 세상이 점점 연결됩니다. • 지식 생산이 점점 효율화 됩니다. • 지식생산자는 더 영향력을 끼지게 됩니다. • 지식 소비자는 점점 더 의존적이 됩니다. 8
  • 10. 누구나 TensorFlow! J. Kang Ph.D. • 2년전 무엇을 느꼈는가? • 2년이 지난 이후 무엇이 벌어지고 있는가? • 무엇을 준비해야하는가? • 수학 • 코딩 • 머신러닝 10
  • 11. 누구나 TensorFlow! J. Kang Ph.D. • 2년전 무엇을 느꼈는가? • 2년이 지난 이후 무엇이 벌어지고 있는가? • 무엇을 준비해야하는가? • 수학: 세상을 설명하는 가장 보편적인 진리 • 코딩: 디지털 문맹이 되지 말자 • 머신러닝: 나 대신 일해주는 시스템 11
  • 12. 누구나 TensorFlow! J. Kang Ph.D. 나의 선택 • 나는 스타트업이라는 정글로 뛰어들었다. • 논문 peer 리뷰 보다 빠른 고객/동료 피드백 • 논문 보다 빠른 블로그 (블로그 보다 동영상) • 특허 보다 쉬운 one more like! • 효율적인 지식생산 방법론 • 세상을 직접 이롭게 하는 일 12
  • 13. 누구나 TensorFlow! J. Kang Ph.D. • 여러분은 지금 어떤 질문을 던지시겠습니까? • 남은 학위 기간 동안 나는 무엇을 준비해야하는가? • 나는 세상에 어떤 기여를 하는 사람이 될것 인가? • 빠른 지식 생산을 위해서 무엇을 고민할 것인가? • 내 연구를 어떻게 효율화 할것인가? 13
  • 14. 누구나 TensorFlow! J. Kang Ph.D. 메트릭스의 빨간약 • 믿고 안믿고, 하고 안하고는 여러분의 선택입니다. • https://www.youtube.com/watch?v=1keotmoOWo4 14
  • 15. 누구나 TensorFlow! J. Kang Ph.D. 누구나 TensorFlow의 목표  강의 철학1: 누구나 “머신러닝” 할 수 있다!!  1) 머신러닝의 기본개념을 수식 머리로 이해한다.  2) 머신러닝 기본기법을 TensorFlow로 구현할 수 있다.  3) 수집한 데이터를 파이썬을 통해서 다룰 수 있다.  4) 내문제에 머신러닝 적용할 수 있다.  5) 스스로 머신러닝을 더 연구해 보고싶다. 15
  • 16. 누구나 TensorFlow! J. Kang Ph.D. 누구나 TensorFlow의 목표  강의 철학2: 당신은 이 강의에서 모든 것을 얻어갈 수 없다!  1) 머신러닝의 기본개념을 수식 머리로 이해한다.  2) 머신러닝 기본기법을 TensorFlow로 구현할 수 있다.  3) 수집한 데이터를 파이썬을 통해서 다룰 수 있다.  4) 내문제에 머신러닝 적용할 수 있다.  5) 스스로 머신러닝을 더 연구해 보고싶다. 16
  • 17. 누구나 TensorFlow! J. Kang Ph.D. 누구나 TensorFlow의 목표  강의 대상: 머신러닝을 시작하는 모든 사람!!  1) 머신러닝에 관심을 가지려고 하는 대학교 3학년  2) 머신러닝을 배워서 취업면접에서 한마디라도 더하고 싶은 취준생  3) 교수님이 머신러닝을 이용해보라고 하는데 막막한 대학원생  4) 최소한으로 공부해서 머신러닝을 적용해 보고 싶은 주니어 개발자! 17
  • 18. 누구나 TensorFlow! J. Kang Ph.D. 강의 일정 일 정 목표 시간 세부 내 용 1일차 1/11 목 Python 준비하기 2 -python scientific framework -python, numpy 기본 -LAB1: python 예제 실습 머신러닝 가족에게 설명하기 3 -머신러닝이란? -왜 머신러닝인가? -최근에 머신러닝이 각광받는 이유 -머신러닝의 종류 -머신러닝의 trade-off TensorFlow 준비하기 3 -왜 TensorFlow인가? + TensorFlow 설치 -LAB2: Helloworld in TensorFlow -TensorFlow 기본 요소 -LAB3: TensorFlow 기본예제 line-fitting 18
  • 19. 누구나 TensorFlow! J. Kang Ph.D. 강의 일정 19 2일차 1/12 금 딥러닝의 선조 뉴럴 네트워크 3 -Lab3.5 : TensorBoard!! 실습 -뉴런을 수학으로 표현하기 -Feed-Forward Neural Networks -Linear 뉴런의 한계와 Activation 함수 -Gradient descent Revisit -Backpropagation algorithm -LAB6: Two-layer neural net with Backpropagation in TensorFlow 왜 딥러닝 인가? 1 -Neural Network 의 역사 (~1990s) -딥러닝 이전 인공신경망의 한계 -LAB7: Vanishing Gradient 문제 체험하기 -딥러닝의 열쇠 (2000s) RBM pre-training하기 2 - RBM이 몬가요? - RBM Pre-Training - RBM with Contrastive Divergence -LAB8: Binary RBM Unsupervised Pre-training 딥러닝 시작하기 2 -Deep Belief Networks (DBN) -LAB9: Layer-wise Pre-training of DBN
  • 20. 누구나 TensorFlow! J. Kang Ph.D. 강의 일정 20 3일차 1/13 토 딥러닝 훈련 기법 2 -딥러닝을 위한 몇가지 기법: -LAB10: Relu Activation 해보기 -LAB11: DropOut 해보기 -LAB12: Batch Normalization 해보기 -LAB13: Adam optimizer 해보기 -LAB14: Revisit DBN with ReLu, DropOut, Batch nomalization Convolutional Neural Net 5 -Biogical inspiration for CNN -Convolutional layer -LAB13: Filtering in CNN 실습 -Why convolution? -Pooling layer -LAB14: Pooling in CNN 실습 -Old CNN -Modern CNN -LAB15: LeNet-5 실습 Wrap up 1 - 강의 리뷰 - Mobile ML lab 소개
  • 21. 누구나 TensorFlow! J. Kang Ph.D. GitHub link GitHub link (all public) – https://github.com/jwkanggist/EveryBodyTensorFlow – Facebook page: goo.gl/NvdbWq Aymeric' s repo – https://github.com/aymericdamien/TensorFlow-Examples Prof. Sung Kim’s repo – https://github.com/hunkim/DeepLearningZeroToAll 21
  • 22. 누구나 TensorFlow! J. Kang Ph.D. 기타 참고 한글 자료 상혁님 블로그 – http://sanghyukchun.github.io/ 테리님의 ML papar repo – https://github.com/terryum/awesome-deep-learning-papers#old-papers 22
  • 23. 누구나 TensorFlow! J. Kang Ph.D. 1. Python 준비하기 1. python/ anaconda /pyCharm 설치 2. LAB0: python 개발 환경 구축 3. python, numpy / pandas.DataFrame기본 실습 4.LAB1: python 실습 : 계단 오르기 문제 연구자들이여 MATLAB에서 벗어나라!! 23
  • 24. 누구나 TensorFlow! J. Kang Ph.D. Reference : Scientific computing in python 24 Python for Data Analysis 1st Edition, 2013 O’Reilly Wes McKinney
  • 25. 누구나 TensorFlow! J. Kang Ph.D. Why Python for Scientific Computing ?  높은 생산성 & 개방성!  Script language + Concise Grammar  Easy to learn and produce  License-free +extensive open libraries: numpy, scipy, pandas, tensorflow… 25 helloWorld.java helloWorld.py public class Main { public static void main(String[] args){ System.out.println("hello world"); } } print ‘hello world’
  • 26. 누구나 TensorFlow! J. Kang Ph.D. Why Python for Scientific Computing ?  높은 생산성 & 개방성!  Script language + Concise Grammar  Easy to learn and produce  License-free +extensive open libraries: numpy, scipy, pandas, tensorflow…  호환성 & 통합성  Very good compatibility to other languages: cython, jython,…  For further your interest, visit this link. 26 MATLAB Python - MathWork (1984) - 공학시뮬레이션 - 기본엔진 + 툴박스 - 행렬 계산효율성 매우좋음 - 폐쇄적 - 제한적호환성 - 유료!! - 파이썬 소프트웨어 재단 (1991) - 범용성 / 간결한 문법/ 가독성 - 방대한 3rd party 라이브러리 - 개방적 + 호환성 + 이식성 good - 모든게 무료!!
  • 27. 누구나 TensorFlow! J. Kang Ph.D. - Interpreter - Programming language - Standard library - Efficient N-dimensional array data structure - Fast / flexible matrix&vector computing - Very good compatibility to C/C++ /Fortran - Basic pip packages for python scientific computing - Packages for machine learning extension Python Scientific Computing Ecosystem 27
  • 28. 누구나 TensorFlow! J. Kang Ph.D. Python Scientific Computing Ecosystem 28 Package name Description numpy Based N-dimensional array package scipy Fundamental library for scientific computing Ipython Enhanced python interactive console (like MATLAB command window) matplotlib Comprehensive 2D plotting scikit-learn Providing library of off-the-shelf machine learning algorithms (higher-level) tensorflow Providing library of low-level machine learning algorithm Pandas Data analysis framework: Easy data manipulation / importing /exporting
  • 29. 누구나 TensorFlow! J. Kang Ph.D. Python Scientific Computing Ecosystem 29 모든게 다 귀찮다면?
  • 30. 누구나 TensorFlow! J. Kang Ph.D. Python Scientific Computing Ecosystem 30 모든게 다 귀찮다면?  Anaconda! – 뱀이야기 인가요 ? VS ?
  • 31. 누구나 TensorFlow! J. Kang Ph.D. Python Scientific Computing Ecosystem 31 Platform name Description Python Interpreter + standard library Anaconda Interpreter + standard libraries +Most of the scientific computing libraries 모든게 다 귀찮다면?  Anaconda! – 아니요 -_-;; – Python + 관련 패키지 통합 distribution !! – For window users:Anaconda3 4.4 with python 3.6설치 • https://www.anaconda.com/download/#windows <
  • 32. 누구나 TensorFlow! J. Kang Ph.D. Python설치  우분투/ OSX: 기본적으로 설치되어 있음 – 이것을 “system 파이썬”이라고 가급적 다루지 않는 것이 좋음 – 파이썬 가상 환경을 구성하여 개발해야함 – pyenv + virtualenv : 파이썬 버전별 설치 / 패키지 관리 32 [이미지출처] https://www.extramile.io/blog/how-to-setup-multiple-python-versions-with-pyenv/
  • 33. 누구나 TensorFlow! J. Kang Ph.D. Python설치  우분투/ OSX: 기본적으로 설치되어 있음 – 이것을 “system 파이썬”이라고 가급적 다루지 않는 것이 좋음 – 파이썬 가상 환경을 구성하여 개발해야함 – pyenv + virtualenv : 파이썬 버전별 설치 / 패키지 관리 33 [이미지 출처] http://qiita.com/hedgehoCrow/items/0733c63c690450b14dcf
  • 34. 누구나 TensorFlow! J. Kang Ph.D. Python설치  우분투/ OSX: 기본적으로 설치되어 있음 – 이것을 “system 파이썬”이라고 가급적 다루지 않는 것이 좋음 – 파이썬 가상 환경을 구성하여 개발해야함 – pyenv + virtualenv : 파이썬 버전별 설치 / 패키지 관리 – autoenv : 폴터별 가상환경 구축 • 파이썬 설치 + 가상환경 설치 (OSX) : https://goo.gl/bE8nmS • 텐서플로 설치 (OSX): https://goo.gl/Vqpw5Q  Win10: 운영체제에 맞춰서 인스톨러를 다운받아서 설치 • https://www.python.org/downloads/windows/ • Win10에서는 python 3.5 이상만 Tensorflow와 호환됨 • 관리자 권한으로 실행! – 파이썬 설치 + 텐서플로 설치 (win10): https://goo.gl/GvybRz 34
  • 35. 누구나 TensorFlow! J. Kang Ph.D. PyCharm IDE 설치 JetBrain에서 제공하는 파이썬 개발툴 (IDE) – Git 지원 – Pip 패키지 관리 지원 – IPython console지원 – Debugger 지원 – Terminal 지원 (ubunto/OSX only)  Ubuntu /OSX/win 설치 – https://www.jetbrains.com/pycharm/download/#section=mac – 반드시 community version으로 설치할것 – 설치 경로에 한글이 없어야함! 35
  • 36. 누구나 TensorFlow! J. Kang Ph.D. LAB0: python 개발환경 구축 설치  목표: 파이썬을 다루기 위한 기본 개발 환경 설치  Ubuntu / OSX 사용자 – Pyenv / pyenv-virtualenv 설치 – 파이썬 개발을 위한 가상환경 만들어 보기 – Anaconda3 설치 – PyCharm 커뮤니티 버전 설치 – 가상환경 생성 후 Pip 명령어를 이용한 파이썬 패키지 설치확인 • $ pip install numpy scipy matplotlib pandas scikit-learn • $ pip list  Window 사용자 – anaconda3 설치 – pyCharm 커뮤니티 버전 설치 – Pycharm IDE에서 File  Settings  Project Interpreter 에서 anaconda3로 설정 36
  • 37. 누구나 TensorFlow! J. Kang Ph.D. LAB0: python 개발환경 구축 설치  더 자세하게는 아래 파일 참조 – 우분투: https://docs.google.com/document/d/1DXncq3t9_UezhtiD_1-yWAYqGsnvem8L2TdU2CpeQZc/ – OSX: https://docs.google.com/document/d/1unqQ8HziRJcZyPiRVX_gMg6eQh65tERM-jhNOIHe44M/ - Win10: - 파이썬 설치 + 텐서플로 설치 (win10): https://goo.gl/GvybRz 37
  • 38. 누구나 TensorFlow! J. Kang Ph.D. 1. Python 준비하기 1. python 2.7/ anaconda2 /pyCharm 설치 2. LAB0: python 개발 환경 구축 3. python, numpy / pandas.DataFrame기본 실습 4. LAB1: python 실습 : Random Walk 문제 38
  • 39. 누구나 TensorFlow! J. Kang Ph.D. GitHub Repository 모든 소스코드는 GitHub를 통해서 공유됩니다. – https://github.com/jwkanggist/EveryBodyTensorFlow 39
  • 40. 누구나 TensorFlow! J. Kang Ph.D. Python - Hello world 파이썬 기본 문법 – 일단 helloworld부터 찍고 보기 40 Ex1) helloworld.py $ vim helloworld.py print ‘Hello world’ # python2 print (‘Hello world!!’) # python3 $ python helloworld.py Hello world Hello world!!
  • 41. 누구나 TensorFlow! J. Kang Ph.D. Python- package Import 파이썬 기본 문법 – 파이썬 위대함 1: 생각할 수 있는 대부분의 API가 오픈소스로 존재한다. – 파이썬 위대함 2: pip + import의 조합이 그런 오픈소스API 사용이 매우 쉽다. 41 Ex2) Tensorflow pip 설치 후 import 하기 $ pip install tensorflow [Installing Tensorflow …] $ python >>> import tensorflow as tf
  • 42. 누구나 TensorFlow! J. Kang Ph.D. Python - package Import 파이썬 기본 문법 – 파이썬 위대함 1: 생각할 수 있는 대부분의 API가 오픈소스 패키지로 존재한다. – 파이썬 위대함 2: pip + import의 조합이 그런 오픈소스 패키지 사용이 매우 쉽게 한다. – 파이썬 위대함 3: 오픈 소스 패키지의 완성도가 매우 높다. 42 Ex3) pandas install 후 import 해서 사용 $ pip install numpy scipy pandas matplotlib [Installing…] >>> import numpy as np >>> import scipy as sp >>> import pandas as pd >>> import matplotlib.pyplot as plt
  • 43. 누구나 TensorFlow! J. Kang Ph.D. Python- List 파이썬 기본 문법 – 순서가 있는 값들의 나열 – 한가지 / 여러가지 타입으로 이루어진 리스트 구성가능 – 0부터 시작하는 인덱스로 브라우징 가능 43 Ex4) 리스트 관련 example >>> lst = ['a', 3.14, 55555, 'abcdef', ['a', 'b', 'c']] >>> lst ['a', 3.14, 55555, 'abcdef', ['a', 'b', 'c']] >>> lst = [3.14132323, 3535242, 'abc', "def", 'color'] >>> lst [3.14132323, 3535242, 'abc', 'def', 'color']
  • 44. 누구나 TensorFlow! J. Kang Ph.D. Python - List 파이썬 기본 문법 – 대입하는 경우 리스트의 복사가 아니고 참조함 – 다양한 멤버함수를 가지고 있음: append(), insert(),remove(), sort(), split() 44 Ex4) 리스트 관련 example >>> a= ['adfa','123','tda','114'] >>> a ['adfa', '123', 'tda', '114'] >>> b=a >>> b ['adfa', '123', 'tda', '114'] >>> b[0]='0' >>> a ['0', '123', 'tda', '114']
  • 45. 누구나 TensorFlow! J. Kang Ph.D. Python- For statement 파이썬 기본 문법 – 1) range()과 함께 사용 45 Ex5) examplefor.py $ vim examplefor.py #-*- coding: utf-8 -*- for i in range (0,5): print ‘ printing number: %s ‘ % i $ python examplefor.py printing number: 0 printing number: 1 printing number: 2 printing number: 3 printing number: 4
  • 46. 누구나 TensorFlow! J. Kang Ph.D. Python- For statement 파이썬 기본 문법 – 1) range()과 함께 사용 – 2) list와 함께 사용 46 Ex6) examplefor2.py $ vim examplefor2.py #-*- coding: utf-8 -*- namelist = [ ‘kim’,’park’,’lee’,’kang’] for name in namelist: print ‘ printing name: %s ‘ % name $ python examplefor2.py printing name: kim printing name: park printing name: lee printing name: kang
  • 47. 누구나 TensorFlow! J. Kang Ph.D. Python- If-elif-else statement 파이썬 기본 문법 – 다양한 부등호와 함께 사용: ==, !=, <, >… – is, not, and, or의 논리 연산 사용 47 Ex7-1) exampleif.py $ vim exampleif.py #-*- coding: utf-8 -*- number = 0 if number == 0: print ‘zero’ elif number == 1: print ‘one’ else: print ‘any’
  • 48. 누구나 TensorFlow! J. Kang Ph.D. Python - If-elif-else statement 파이썬 기본 문법 – 다양한 부등호와 함께 사용: ==, !=, <, >… – is, not, and, or의 논리 연산 사용 48 Ex7-2) exampleif2.py $ vim exampleif2.py #-*- coding: utf-8 -*- number = 0 number2 = 1 if (number == 0) and (number2 == 1): print ‘Both True!!’ elif (number == 0) or (number2 == 1): print ‘one of both is True’ else: print ‘All False’
  • 49. 누구나 TensorFlow! J. Kang Ph.D. Python - user-defined func 파이썬 기본 문법 – “def” 키워드를 가지고 정의할 수 있다. 49 Ex8) examplefunc.py $ vim examplefunc.py #-*- coding: utf-8 -*- def myFuncPrint (keyword, numOfPrint): for i in range(0,numOfPrint): print “ The %s-th printing of %s” % (i+1,keyword) myFuncPrint (‘JaewookKang’, 5) % python examplefunc.py The 1-th printing of JaewookKang The 2-th printing of JaewookKang The 3-th printing of JaewookKang The 4-th printing of JaewookKang The 5-th printing of JaewookKang
  • 50. 누구나 TensorFlow! J. Kang Ph.D. Numpy: Numerical Python  벡터&행렬 연산에 필요한 N차원 배열을 다루기 위한 도구 – 효율적인 N차원 배열 자료 구조: ndarray – 다양한 ndarray 기반 수학 함수 API – 간편한 메모리 to ndarray 인터페이스  Ndarray vs. List – 벡터&행렬 연산에는 ”ndarray”가 단언컨데 유리함! 50 ndarray List 메모리 사 용 특징 - 한 주소값으로 부터 연속적 으로 메모리에 elem값저장 Elem값이 이산적인 주소값에 저장 연산 특징 sequential한 elem값 연산에 유리 Elem 단위 연산에 유리 구현 Array list (C/C++ array) Linked list
  • 51. 누구나 TensorFlow! J. Kang Ph.D. Numpy: Numerical Python  Numpy에서 꼭 알아야 할것 – ndarray 생성 – ndarray 인덱싱 – ndarray 유니버설 함수 51
  • 52. 누구나 TensorFlow! J. Kang Ph.D. ndarray 생성  Practice1: List로 부터 생성 52 Ex9) ex_ndarray1.py $ python >>> import numpy as np >>> templist = [1,2,3,4,5,6] >>> templist [1,2,3,4,5,6] >>> nptemplist = np.array(templist) >>> nptemplist array ([1 ,2 ,3 ,4 ,5 ,6 ]) >>> whos Variable Type Data/Info --------------------------------- np module <module 'numpy' from ….. nptemplist ndarray 5: 5 elems, type `int64`, 40 bytessys….. templist list n=5…
  • 53. 누구나 TensorFlow! J. Kang Ph.D. ndarray 생성  Practice2: List로 부터 생성 + dtype설정 53 Ex10) ex_ndarray2.py $ python >>> import numpy as np >>> templist = [1,2,3,4,5,6] >>> templist [1,2,3,4,5,6] >>> nptemplist = np.array( templist, dtype = np.int8 ) >>> nptemplist array ([1 ,2 ,3 ,4 ,5 ,6 ]) >>> whos Variable Type Data/Info --------------------------------- np module <module 'numpy' from ….. nptemplist ndarray 5: 5 elems, type `int8`, 40 bytessys….. templist list n=5…
  • 54. 누구나 TensorFlow! J. Kang Ph.D. ndarray 생성  Practice3: all zeros/ones 벡터&행렬 생성 54 Ex11) ex_zeros.py $ python >>> import numpy as np >>>np.zeros(1) array([ 0.]) >>> np.zeros(2) array([ 0., 0.]) >>> np.zeros([2,1]) array([[ 0.], [ 0.]]) >>> np.zeros([2,2]) array([[ 0., 0.], [ 0., 0.]])
  • 55. 누구나 TensorFlow! J. Kang Ph.D. ndarray 생성  Practice3: all zeros/ones 벡터&행렬 생성 55 Ex12) ex_ones.py $ python >>> import numpy as np >>>np.ones(1) array([ 1.]) >>> np.ones(2) array([ 1., 1.]) >>> np.ones([2,1]) array([[ 1.], [ 1.]]) >>> np.ones([2,2]) array([[ 1., 1.], [ 1., 1.]])
  • 56. 누구나 TensorFlow! J. Kang Ph.D. ndarray 인덱싱  Practice4: ndarray 의 인덱싱은 참조를 사용한다. – 슬라이싱 기능: “:”를 가지고 인덱싱하는 것 – 리스트와의 중요한 차이점은 slice은 원본배열의 view라는 점 56 Ex13) ex_indexing.py >>> arr = np.arange(10) >>> arr array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]) >>>arr[5] 5 >>> arr[5:8] array([5, 6, 7]) >>> arr[5:8] = 12 >>> arr array([ 0, 1, 2, 3, 4, 12, 12, 12, 8, 9])
  • 57. 누구나 TensorFlow! J. Kang Ph.D. ndarray 인덱싱  Practice5: ndarray 의 인덱싱은 참조를 사용한다. – 슬라이싱 기능: “:”를 가지고 인덱싱하는 것 – 리스트와의 중요한 차이점은 slice은 원본배열의 view라는점 – ndarray의 복사복을 얻고싶다면 arr[5:8].copy()를 사용 57 Ex14) ex_slicing.py >>> arr_slice = arr[5:8] >>> arr_slice[1] = 12345 >>> arr array([ 0, 1, 2, 3, 4, 12, 12345, 12, 8, 9]) >>> arr_slice[:] = 128 >>> arr array([ 0, 1, 2, 3, 4, 128, 128, 128, 8, 9])
  • 58. 누구나 TensorFlow! J. Kang Ph.D. ndarray 유니버설 함수  Practice6: ndarray안에 있는 데이터 원소별로 연산을 수행하는 함수 58 함수 설명 abs, fabs 각 원소의 절대값을 구한다. 복소수가 아닌 경우 에는 빠른 연산을 위해 fabs를 사용한다. sqrt 각 원소의 제곱근을 계산한다. square 각 원소의 제곱을 계산한다. Log, log10, log2 각 원소의 지수 exp^x를 계산한다. ceil 각 원소의 소수자리를 올린다. floor 각 원소의 소수자리를 버린다. modf 각 원소의 몫과 나머지를 각각의 배열로 반환한 다. Isnan, isinf 각 원소의 nan/inf 상태를 불리안값을 가지고 확 인한다. Cos, cosh, sin, sinh, tan, tanh 각 원소의삼각/쌍곡 함수
  • 59. 누구나 TensorFlow! J. Kang Ph.D. ndarray 유니버설 함수  Practice6: ndarray안에 있는 데이터 원소별로 연산을 수행하는 함수 59 함수 설명 Add 두 ndarray를 원소단위로 덧셈한다. Substract 두 ndarray를 원소단위로 뺄셈한다. Multiply 두 ndarray를 원소단위로 나눗셈한다. Divide, floor_divide 첫 번째 배열의 원소에서 두번째 배열의 원소를 나눈다. Floor_divide는 몫만 취한다. Power 첫번째 배열의 원소에서 두번쨰 배열의 원소만 큼 제곱한다. Maximum, fmax 두중 큰값을 반환 fmax는 NaN은 무시한다. Minimum, fmin 두중 작은값을 반환 fmin은 NaN은 무시한다. Logical_and, logical_or, logical_xor 각각 두 원소 간의 논리연산 결과를 반환한다. Mod 첫번째 배열원소에 두번째 배열원소로 나눈 나 머지값을 반환한다.
  • 60. 누구나 TensorFlow! J. Kang Ph.D. LAB1: Random walk 문제  계단을 0층 부터 시작하여 같은 확률로 계단을 한칸 올라가거 나 내려갈수 있다.  시행횟수에 따른 계단 층수를 시뮬레이션 해보자 – 초기위치: position = 0 – 시행횟수: step = 10  random walk 값이 음수가 되는 값만 출력해보자  Numpy를 사용해서 구현해보자 – Naïve구현 • For문 IF문 사용 – Numpy API사용 구현 • np.where() • np.random.randint(2,size=1) • np.cumsum()  참고 github link: https://github.com/jwkanggist/EveryBodyTensorFlow/blob/master/lab1_randomwalk.py 60
  • 61. 누구나 TensorFlow! J. Kang Ph.D. 1. 머신러닝 가족에게 설명하기 - 머신러닝 이란? - 최근에 머신러닝이 각광받는 이유 - 머신러닝의 3대 요소 - 머신러닝의 종류 - 머신러닝에서의 Trade-off 61
  • 62. 누구나 TensorFlow! J. Kang Ph.D. Reference : Machine learning fundamental 62 Hands-On Machine Learning With Scikit-Learn & TensorFlow 2017 Aurelien Geron, Google O’Reilly 본 강의는 해당 교재를 참고했음을 사전에 알립니다.
  • 63. 누구나 TensorFlow! J. Kang Ph.D. What Machine Learning? 63 머신러닝은 무엇인가?
  • 64. 누구나 TensorFlow! J. Kang Ph.D. What Machine Learning? 64 머신러닝은 무엇인가? – 컴퓨터가 지능을 갖는 것? 인공지능? AlphaGo? – 데이터를 통해서 예측하는 것? – 컴퓨터에게 알려주는거?
  • 65. 누구나 TensorFlow! J. Kang Ph.D. What Machine Learning? 65 Definition (Machine Learning): Field of study that gives computers the ability to learn without being explicitly programmed. - Arthur Samuel, 1959 머신러닝은 무엇인가? – 컴퓨터가 지능을 갖는 것? 인공지능? AlphaGo? – 데이터를 통해서 예측하는 것? – 컴퓨터에게 알려주는거?
  • 66. 누구나 TensorFlow! J. Kang Ph.D. What Machine Learning? 66 머신러닝은 무엇인가? – 컴퓨터가 지능을 갖는 것? 인공지능? AlphaGo? – 데이터를 통해서 예측하는 것? – 컴퓨터에게 알려주는거? Definition (Machine Learning): A computer program is said to learn rom experience E with respect to some task T and some performance measure P, if its performance on T, measured by P, is improved with experience E. - Tom Mitchell, 1997
  • 67. 누구나 TensorFlow! J. Kang Ph.D. What Machine Learning? 67 머신러닝은 무엇인가? – 임의의 업무 생산성/정확성/능률 (P) 의 척도 대해서 데이터라는 경험 (E) 을 통해서 컴퓨터가 업무 (T) 를 볼수 있도록 훈련시키는 일 Definition (Machine Learning): A computer program is said to learn rom experience E with respect to some task T and some performance measure P, if its performance on T, measured by P, is improved with experience E. - Tom Mitchell, 1997
  • 68. 누구나 TensorFlow! J. Kang Ph.D. 머신러닝의 구성요소 머신러닝을 하기위해서 무엇이 필요한가? – 경험 (E): Training data Set – 업무 (T): System or model to be learned – 척도 (P): performance measure, accuracy 68
  • 69. 누구나 TensorFlow! J. Kang Ph.D. 머신러닝의 구성요소 머신러닝을 하기위해서 무엇이 필요한가? – 경험 (E): Training data Set – 업무 (T): System or model to be learned – 척도 (P): performance measure, accuracy 69 Training Step: T: Spam mail Filtering system (E):User flagged Spam list (T): Smap Filtering system (P): Filtering Accuracy Training Collecting Training DataSpam ✔ Spam ✔ Spam ✔
  • 70. 누구나 TensorFlow! J. Kang Ph.D. 머신러닝의 구성요소 머신러닝을 하기위해서 무엇이 필요한가? – 경험 (E): Training data Set – 업무 (T): System or model to be learned – 척도 (P): performance measure, accuracy 70 Tasking Step: T: Spam mail Filtering system Arbitrary Input SPAM Filtering (spam classification)
  • 71. 누구나 TensorFlow! J. Kang Ph.D. Why Machine Learning? Conventional approach – 단편적인 현상을 통해 프로그래머가 인지한 몇가지 rule를 가지고 문제를 해결 • 보편적인 rule 을 만들기 어려움 • 실제 문제의 해결을 보장하지 않음 • 결과물은 엔지니어의 경험에 매우 의존적임 71 Study the Problem Establish rules Evaluate Analyze errors Release!
  • 72. 누구나 TensorFlow! J. Kang Ph.D. Why Machine Learning? ML approach – 데이터로 부터 문제 해결을 위한 보편적인 rule을 찾는다. • Training data set에 대한 일반화 • 데이터에 의한 문제해결 72 Study the Problem Train ML algorithm Evaluate Analyze errors Release! Lots of Data
  • 73. 누구나 TensorFlow! J. Kang Ph.D. Why Machine Learning? ML approach – 데이터로 부터 문제 해결을 위한 rule을 자동으로 찾는다. • 머신러닝이 진정한 의미가 있기 위해서는… • 빅데이터가 있고 • 자동으로 시스템이 러닝될 수 있다. 73 Train ML algorithm Evaluate Solution Update Data Release! Lots of Data Can be automated
  • 74. 누구나 TensorFlow! J. Kang Ph.D. ML approach 특징 요약 – All from data!! • Larger data  Better systems • Simple but universal rule • Easy update rule given new data • Getting unrecognized insights about complex problems Why Machine Learning? 74 Inspect the solution Lots of Data Study the Problem Train ML algorithm Iterate If needed Understand the problem better Solution New Insight
  • 75. 누구나 TensorFlow! J. Kang Ph.D. Why Machine learning Now? 머신러닝 3요소 – 빅데이터: SmartDevices, IoT, sensor networks – 알고리즘: deep learning / reinforcement-learning – 컴퓨팅 파워: GPU, parallel / distributed computing 75
  • 76. 누구나 TensorFlow! J. Kang Ph.D. Why Machine learning Now? 머신러닝 3요소 – 빅데이터 >> 컴퓨팅 파워 > 알고리즘 • 품질 좋은/많은 량의 데이터만 있으면 머신러닝 시스템의 성능을 무조건 좋다. 76
  • 77. 누구나 TensorFlow! J. Kang Ph.D. Why Machine learning Now? 머신러닝 3요소 – 빅데이터 >> 컴퓨팅 파워 > 알고리즘 • 품질 좋은/많은 량의 데이터만 있으면 머신러닝 시스템의 성능을 무조건 좋다.  그럼 데이터만 있으면 엔지니어는 이제 필요없나요 ? – 아니요!: 위 세가지는 항상 모두 주어지지 않음  We need ”Domain Adaptation !!”  목표: 성능개선 + 러닝 시간 단축 + 데이터 용량 최소화 77
  • 78. 누구나 TensorFlow! J. Kang Ph.D. We Still Need ML Engineers! Domain Adaptation 1 – Feature Extraction – 데이터를 특징을 잘 뽑아서 데이터량을 줄인다 – Simplify data without losing too much information ! – Feature extraction을 잘하기 위해서는 도메인 지식이 중요 Domain Adaptation 2 – Learning Environment – 모바일에서는 컴퓨팅 파워와 데이터 저장소가 부족 – 긴 러닝 타임도 부담 – Google’s Approach in Mobile ML env. (utblink) • Pre-training model in cloud • Local fine-Tuning with private data in mobile APP • Run prediction engine in mobile APP 78 + Cloud ML
  • 79. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems  학습방식에 따라서 – Supervised – Unsupervised – Reinforcement  데이터 업데이트 방식에 따라서 – Batch-based learning – Online-based learning 79
  • 80. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Supervised learning – Training data set이 시스템의 입력과 출력의 pair 로 구성된 경우 • 여기서 출력을 label이라고 함 • 여기서 입력을 instance (또는 feature)라고 함 80 2 1 1 2 1 2 ? New instance Training Set Instance Label
  • 81. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Supervised learning – Training data set이 시스템의 입력과 출력의 pair 로 구성된 경우 – 컴퓨터가 러닝하는데 선생이 있어서 답(label)을 알려주는 경우 – 머신 러닝의 가장 보편적인 형태 81 An example: Spam filter revisited T: Spam mail Filtering system (E):User flagged Spam list (T): Smap Filtering system (P): Filtering Accuracy Training Collecting Training DataSpam ✔ Spam ✔ Spam ✔
  • 82. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Supervised learning – Regression – Classification Models in Supervised learning – Linear Models – Neural networks – SVM, RVM 82
  • 83. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Unsupervised learning – Training data set이 입력만 있는 경우 – 컴퓨터가 러닝하는데 선생님이 없는 경우 – 세상에 존재하는 대부분의 데이터는 label이 없다 83 Training Set
  • 84. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Unsupervised learning – Training data set이 입력만 있는 경우 – 컴퓨터가 러닝하는데 선생님이 없는 경우 – 세상에 존재하는 대부분의 데이터는 label이 없다 84 Training Set
  • 85. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Unsupervised learning – Clustering – Dimensionality reduction • The goal is to simplify the data without losing too much information – Feature extraction: • which is a kind of dimensionality reduction • Reducing computational& memory cost for ML • Making ML system efficient! • Domain knowledge is required 85
  • 86. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Semisupervised learning – Combination of supervised and unsupervised learning • 1) Supervised learning with labeled data • 2) Unsupervised learning with unlabeled data • 3) Self-labelling of unlabeled data using step1 and step2 • 4) re-training of the system 86 이미지 출처: https://www.researchgate.net/publication/277605013_Signal_ Processing_Approaches_to_Minimize_or_Suppress_Calibration _Time_in_Oscillatory_Activity-Based_Brain- Computer_Interfaces
  • 87. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Semisupervised learning – Training data set = labeled data + unlabeled data – Combination of supervised and unsupervised learning 87 feature1 Feature 1 Feature 2
  • 88. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Semisupervised learning – Training data set = labeled data + unlabeled data – Combination of supervised and unsupervised learning 88 Supervised learning with Labeled data feature1 Feature 1 Feature 2
  • 89. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Semisupervised learning – Training data set = labeled data + unlabeled data – Combination of supervised and unsupervised learning 89 Labeling unlabed data With trained classifier Feature 1 Feature 2
  • 90. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Semisupervised learning – Training data set = labeled data + unlabeled data – Combination of supervised and unsupervised learning 90 Re-training and classifier update Feature 1 Feature 2
  • 91. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Reinforcement learning – 컴퓨터가 시간에 따라서 보상을 통해서 최고의 행동전략을 환경으로 부터 스스로 배워가는 것 – 결과로 부터 스스로 학습법 91 [이미지 출처] https://www.analyticsvidhya.com/bl og/2016/12/getting-ready-for-ai- based-gaming-agents-overview-of- open-source-reinforcement- learning-platforms/
  • 92. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems MarI/O (2015) – 목적: 게임에 대한 연속적인 버튼선택 러닝 • https://www.youtube.com/watch?v=qv6UVOQ0F44 – 게임의 각 프레임 상황을 supervised DNN으로 모델링 • 입력: 프레임 화면 이미지 • 출력: 각 화면 이미지에 대한 버튼선택 (A,B,X,Y,R,L,up,down,right,left) – 강화학습 – 환경으로 부터 DNN 훈련 데이터를 스스로 만들어내는 과정 • 각 프레임의 환경을 “State”로 정의 (블록배치, enemy위치) • 현재 state의 Action (버튼 선택)에 따라 다음 state가 정해진다. • 각 State 에 대해서 Action (버튼 선택)에 따른 ”Reward” (Fitness) 를 피드백 – 살아있으면 + 1 – 버섯, 코인, 먹으면 + X – Enemy 에 접촉해서 데미지를 입으면 - Y • Reward가 높은 state의 action에 대한 확률이 높인다 • Reward는 과거 N-state에 대해서 피드백 된다. – 생성되는 DNN 훈련데이터는 sequential 데이터 이다. 92
  • 93. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Google DeepMind 벽돌깨기 (2016) – https://www.youtube.com/watch?v=V1eYniJ0Rnk – AI가 살아남는 것을 넘어서 편하게 점수를 따는 전략을 스스로 찾아냄 – AI가 스스로 행동전략을 진화시킨 첫번째 케이스로 알려짐 93
  • 94. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Batch learning – Training data set를 통째로 넣어서 한번에 시스템을 러닝하는 것 • 장점: simple / 주어진 데이터 안에서 안정적인 동작 • 단점: – 급격하게 변화하는 데이터 대처에 비효율 – Learning cost가 크다 » 계산량: 데이터가 크니깐 크다 » 메모리: training data를 항상 보관하고 있어야 한다. » 시간 : 데이터가 크니깐 러닝타임이 길다. 94
  • 95. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Online Learning – 시스템을 러닝한 후에도 instance data가 들어오면 online으로 시스템을 incrementally 업데이트 할수 있는 학습법 95 Evaluate Solution Lots of Data Train ML algorithm Run and Update Model Release! New Data New Data New Data
  • 96. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Online Learning – 시스템을 러닝한 후에도 instance data가 들어오면 online으로 시스템을 incrementally 업데이트 할수 있는 학습법 – 하드웨어의 계산부담을 줄이기위해서 batch learning을 online learning으로 쪼개서 할수도 있음 (실제로 다 그렇케 함) 96 Study the Problem Train online ML algorithm Analyze errors Evaluate Release! Lots of Data Chop into pieces
  • 97. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Online Learning – 장점: • 변화하는 데이터에 바로바로 대처 • 러닝 비용을 낮출 수 있다 • Training data를 들고 있지 않아도 된다. – 단점: 데이터의 변화에 너무 시스템이 민감해질 수 있다. 97
  • 98. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML Model selection – Underfitting – Overfitting Curse of dimensionality 98
  • 99. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML Model selection – 대상으로하는 데이터의 범주에 맞는 머신러닝 모델 선택이 중요하다! – 목적으로하는 데이터 범주에 대해서 99
  • 100. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML Model selection – 대상으로하는 데이터의 범주에 맞는 머신러닝 모델 선택이 중요하다! – 목적으로하는 데이터 범주에 대해서 • 설명을 잘못하는 모델  예측 오류값이 매우 크다 (Underfitting) 100 Training data Validation data
  • 101. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML Model selection – 대상으로하는 데이터의 범주에 맞는 머신러닝 모델 선택이 중요하다! – 목적으로하는 데이터 범주에 대해서 • 설명을 잘못하는 모델  예측 오류값이 매우 크다 (Underfitting) • 훈련데이터에 대해서만 작은 오류값을 출력하는 모델 (Overfitting) –  일반화된 예측결과를 제공 못함 101 Training data Validation data
  • 102. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML Model selection – 대상으로하는 데이터의 범주에 맞는 머신러닝 모델 선택이 중요하다! – 목적으로하는 데이터 범주에 대해서 • 설명을 잘못하는 모델  예측 오류값이 매우 크다 (Underfitting) • 훈련데이터에 대해서만 작은 오류값을 출력하는 모델 (Overfitting) –  일반화된 예측결과를 제공 못함 • 필요이상으로 복잡하지 않은 모델 102 Training data Validation data
  • 103. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML Model selection – 간단한 모델 • Good: – 1) 주어진 데이터 셋에 대해서 일반화 된 결과를 내놓는다. – 2) 작은 데이터 셋을 가지고 훈련이 가능하다. – 3) 작은 범위의 데이터 셋에 대해서 성능이 복잡한 모델 보다 좋다. • Bad : – 1) Underfitting: 다양한/넓은 범위의 데이터 셋에 대해서 설명 (모델링) 하지 못한다. – 복잡한 모델 • Good: – 1) 다양한/넓은 범위의 데이터 셋에 대해서 설명(모델링)이 가능하다. • Bad : – 1) 작은 범위의 데이터 셋에 대해서 성능이 간단한 모델에 비해서 열화된다. – 2) 훈련을 위해서 다양하고 큰 데이터 셋이 필요하다. – 3) Overfitting: 대상으로 하는 데이터 셋에 대해서 일반화 된 결과를 내 놓기 어렵다. 103
  • 104. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML Model selection 104 Given a certain size of data… Validation error
  • 105. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML The Curse of Dimensionality – 데이터의 차원이 증가할 수록 학습에 필요한 데이터의 개수를 기하급수적으로 늘어나는 문제 – 같은 비율의 공간을 모델링하기 위해서 필요한 데이터 량이 급속도록 증가 – Example: 공간의 20%를 채우기 위해서 필요한 데이터 수 • 0.2(1차원)  0.9(2차원)  1.74 (3차원) 105 [이미지 출처] http://www.visiondummy.com/2014/04/curse- dimensionality-affect-classification/ 1차원 데이터 0.2 = 0.2 2차원 데이터 0.2 = 0.45 * 0.45 3차원 데이터 0.2 = 0.58 * 0.58 * 0.58
  • 106. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML The Curse of Dimensionality – 저차원에서는 충분했던 데이터 양도 고차원이 되면 공간(학습 모델)을 설명하기에 부족해 질수 있음 • 모델 고차원화  모델설명을 위한 데이터 부족 Overfitting문제 106 [이미지 출처] http://www.visiondummy.com/2014/04/curse- dimensionality-affect-classification/
  • 107. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML The Curse of Dimensionality – 저차원에서는 충분했던 데이터 양도 고차원이 되면 공간(학습 모델)을 설명하기에 부족해 질수 있음 • 모델 고차원화  모델설명을 위한 데이터 부족 Overfitting문제 107 [이미지 출처] http://www.visiondummy.com/2014/04/curse- dimensionality-affect-classification/
  • 108. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML The Curse of Dimensionality – 저차원에서는 충분했던 데이터 양도 고차원이 되면 공간(학습모델)을 설명하기에 부족해 질수 있음 – 모델을 설명하기에 데이터가 부족해? 108
  • 109. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML The Curse of Dimensionality – 저차원에서는 충분했던 데이터 양도 고차원이 되면 공간(학습모델)을 설명하기에 부족해 질수 있음 – 모델을 설명하기에 데이터가 부족해? Overfitting문제 – 해결책 • 데이터 양 + 다양성 늘리기 • 중요한 특징만 뽑자  데이터차원 축소 (Dimensionality Reduction) – Feature Extraction – Feature Selection • 사전지식 이용  Regularziation 109
  • 110. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML Raw data vs Featured data 110 Raw data Featured Data No information loss  Discover Unrecognized patterns Some information loss  Degrade performance sometime Curse of dimensionality Dimensionality Reduction Higher computational cost  Slower learning time Lower computation cost  Faster learning time Large-scale storage is required Small-scale storage is fine
  • 111. 누구나 TensorFlow! J. Kang Ph.D. Trade-off in ML Big data vs. Small data 111 Big data Small Data No overfitting to training data Overfitting to training data is possible Working with complex models for difficult problems Working with simple models for easy problems Higher computational cost  Slower learning time Lower computation cost  Faster learning time Large-scale storage is required Small-scale storage is fine
  • 112. 누구나 TensorFlow! J. Kang Ph.D. 3. Tensorflow 준비하기 - 왜 TensorFlow인가? + TensorFlow 설치 - LAB2: Helloworld in TensorFlow - TensorFlow의 기본요소 - LAB3: TensorFlow 기본예제 line-fitting - ML training in TensorFlow - LAB4: TensorFlow 기본예제 Curve-fitting 이제야 준비 끝! 텐플 소개 시작…. 112
  • 113. 누구나 TensorFlow! J. Kang Ph.D. Reference : Machine learning fundamental 113 Hands-On Machine Learning With Scikit-Learn & TensorFlow 2017 Aurelien Geron, Google O’Reilly 본 강의는 해당 교재를 참고했음을 사전에 알립니다.
  • 114. 누구나 TensorFlow! J. Kang Ph.D. Reference: Machine Learning Crash Course (MLCC) 114 https://cloud.google.com/blog/big-data/ 본 강의는 구글에서 제공한 자료의 일부를 참고했음을 사전에 알립니다.
  • 115. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 요약 A open source software library for ML – https://www.tensorflow.org/ – ML 모델 프로토타이핑 용도 – 연산 환경 • 분산 훈련 환경 지원 • CPU/GPU/TPU + 모바일 환경 지원 – 코어 구현: C++, fast! – Front end: python, C++, Java – 현재 버전 r1.4 (2017 Nov) 115
  • 116. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 요약 A open source software library for ML – https://www.tensorflow.org/ – ML 모델 프로토타이밍 용도 – 연산 환경 • 분산 훈련 환경 지원 • CPU/GPU/TPU + 모바일 환경 지원 – 코어 구현: C++, fast! – Front end: python, C++ 116
  • 117. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 요약 A open source software library for ML – 2015 년 12월 이후 21,122 커밋수 (상당수가 외부) – 1000 명 이상의 기여자 117
  • 118. 누구나 TensorFlow! J. Kang Ph.D. Why TensorFlow ? 장/단점 (다른 ML프레임워크와의 비교) – 장점 • 간편한 front-end interface • 호환성 == 폭 넓은 OS지원 • 빠른 러닝 속도 (Torch 보다는 느림) • 구글 문서화 (Google!!) • 넓은 사용자 커뮤니티: 많은 third-party 라이브러리 및 오픈소스 예제 • 강력한 시각화 기능 – 단점 • 잦은 문법 변경 (현재 릴리즈 문법이 다음릴리즈에 변경 ㅋㅋ) • Define-by-Run 모델: 훈련 실행중에 변경 불가 • 세세한 모델링 / 훈련 설정이 초보자에게 어려움 118
  • 119. 누구나 TensorFlow! J. Kang Ph.D. Tensorflow 설치 (OSX, ubuntu) Easy: pip를 이용한 설치 119 Ubuntu 16.04: shell commands $ pyenv virtualenv 2.7.12 tensorflow #가상환경 설정 $ pyenv shell tensorflow (tensorflow) $ pip install numpy scipy matplotlib scikit-learn pandas (tensorflow) $ pip install –upgrade tensorflow==1.4.0 Collecting tensorflow==1.4.0 ….. (tnesorflow) $ pip list ..... tensorflow (1.3.0) .....
  • 120. 누구나 TensorFlow! J. Kang Ph.D. Tensorflow 설치 (win10) Easy: anaconda3 prompt + pip를 이용한 설치 – Win10에서는…. Python 3.5 이상만 tensorflow와 호환된다고 함ㅠ – Anaconda 4.4 with python 3.6설치 • https://www.anaconda.com/download/#windows – jwkang 가이드 문서 • https://goo.gl/GvybRz 120
  • 121. 누구나 TensorFlow! J. Kang Ph.D. Tensorflow 설치 (win10) Easy: anaconda prompt + pip +conda를 이용한 설치 – 관리자 권한으로 anaconda prompt 실행 121 Anaconda prompt in win10  $ python –m pip install --upgrade pip  $ pip install tensorflow
  • 122. 누구나 TensorFlow! J. Kang Ph.D. Tensorflow 설치 Adv: github에서 직접 소스 다운해서 설치 – 자신의 러닝머신에 커스터 마이즈해서 빌드 • CPU / GPU support • Python 버전 • CUDA 버전 – 러닝 속도 최적화 – 링크 참고 • http://startupphd.blogspot.kr/2017/06/git-source-tensorflow-r12-with-gpu.html 122
  • 123. 누구나 TensorFlow! J. Kang Ph.D. LAB2: helloWorld in Tensorflow Pip를 통해서 tensorflow를 설치하고 helloWorld를 찍어보자! – 일단 무작정 따라해 보자 – 파이참 project 생성후 project interpreter 설정 123
  • 124. 누구나 TensorFlow! J. Kang Ph.D. LAB2: helloWorld in Tensorflow Pip를 통해서 tensorflow를 설치하고 helloWorld를 찍어보자! 124 lab2_runHelloTensorflow.py (tensorflow) $ vim helloworld.py import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') sess = tf.Session() print ('[Lab2] %s' % sess.run(hello)) # Hello, TensorFlow! a = tf.constant(10) b = tf.constant(32) print ('[Lab2] a + b = %s' % sess.run(a+b)) # 42
  • 125. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 계산그래프 (Computational graph) – 정의: 연산노드와 텐서노드(Variable/Constant)로 구성된 그래프로 학습 모델을 묘사한다. 125 그림출처: https://medium.com/@camrongodbout/tensorflow- in-a-nutshell-part-one-basics-3f4403709c9d
  • 126. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 계산그래프 (Computational graph) – 정의: 연산노드와 텐서노드(Variable/Constant)로 구성된 그래프로 학습 모델을 묘사한다. 126 그림출처: https://medium.com/@camrongodbout/tensorflow- in-a-nutshell-part-one-basics-3f4403709c9d 연산노드 텐서노드텐서노드 텐서노드
  • 127. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 계산그래프 (Computational graph) – 텐플 (TensorFlow) 스크립트는 두부분으로 구성된다. • Part I) 계산 그래프 정의 하기 • Part II) 계산 그래프 평가 하기 127
  • 128. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 PART I) 계산그래프 정의하기 128 ex_runTFconstant.py #-*- coding: utf-8 -*- import tensorflow as tf import numpy as np g = tf.Graph() with g.as_default(): x = tf.constant(6,name="x_const")# 상수노드 1 y = tf.constant(14,name="y_const") # 상수 노드2 sum = tf.add(x,y,name="sum_xy")# 연산 노드
  • 129. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 PART I) 계산그래프 정의하기 – tf.constant()는 상수 Tensor입니다. 129 + x = 6 y = 14 x = tf.constant(6,name="x_const") y = tf.constant(14,name=”y_const") sum = tf.add(x,y,name="sum_xy")
  • 130. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 PART II) 계산그래프 평가하기 – 계산그래프를 평가하기 위해서는 tf.Session()을 열어야 한다. 130
  • 131. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 PART II) 계산그래프 평가하기 – 계산그래프를 평가하기 위해서는 tf.Session()을 열어야 한다. – 응? Session() 연다구? 131
  • 132. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 PART II) 계산그래프 평가하기 – 계산그래프를 평가하기 위해서는 tf.Session()을 열어야 한다. – 응? Session() 연다구? •  session()을 연다는 것은 • 1) Front-end interface(python)을 통해서 계산디바이스 (cpu든 gpu든 cloud computing이든)에 접속하고 • 2) 계산그래프 구조를 전달하여 평가준비를 시키는 것 – https://www.tensorflow.org/programmers_guide/graphs 132
  • 133. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 PART II) 계산그래프 평가하기 – 계산그래프를 평가하기 위해서는 tf.Session()을 열어야 한다. – 방법1: tf.Session().run() 메소드 • sess = tf.Session() • sess=tf.Session(graph=graph0) • sess.run(x) • sess.run(y) • sess.run(sum) 133
  • 134. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 PART II) 계산그래프 평가하기 – 계산그래프를 평가하기 위해서는 tf.Session()을 열어야 한다. – 방법2: with 키워드 이용하기 • Indent 안 블럭에서는 매번 run()을 호출하지 않아도 된다. • 블럭이 끝나면 자동으로 session이 종료된다. – sum.eval() • tf.constant()는 그래프 평가 중에 값이 변경될 수 없다. 134
  • 135. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 PART II) 계산그래프 평가하기 135 ex_runTFconstant.py #-*- coding: utf-8 -*- import tensorflow as tf import numpy as np g = tf.Graph() with g.as_default(): x = tf.constant(6,name="x_const") y = tf.constant(14,name="y_const") sum = tf.add(x,y,name="sum_xy") # 세션 블럭 시작 with tf.Session(graph=g) as sess: print ('sum.eval()=%d'%sum.eval()) print ('sess.run(sum)=%d'%sess.run(sum))
  • 136. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 PART II) 계산그래프 평가하기 136 ex_runTFconstant.py #-*- coding: utf-8 -*- import tensorflow as tf import numpy as np g = tf.Graph() with g.as_default(): x = tf.constant(6,name="x_const") y = tf.constant(14,name="y_const") sum = tf.add(x,y,name="sum_xy") # 세션 블럭 시작 (with g.as_default() 블록에 속하므로 g를 default graph로 취급) with tf.Session() as sess: print ('sum.eval()=%d'%sum.eval()) print ('sess.run(sum)=%d'%sess.run(sum))
  • 137. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 PART II) 계산그래프 평가하기 – tf.constant()는 그래프 평가중 값이 변경될 수 없다. 137 + x = 6 y = 14 x = tf.constant(6,name="x_const") y = tf.constant(14,name=”y_const") sum = tf.add(x,y,name="sum_xy") 6 14 20
  • 138. 누구나 TensorFlow! J. Kang Ph.D. Revisit LAB2 계산그래프 정의/평가 파트를 구분해보자 138 lab2_runHelloTensorflow.py (tensorflow) $ vim helloworld.py import tensorflow as tf hello = tf.constant('Hello, TensorFlow!') # graph construction sess = tf.Session() # graph에 대한 명시가 없으면 default graph사용 print ('[Lab2] %s' % sess.run(hello) ) # graph evaluation # Hello, TensorFlow! a = tf.constant(10) b = tf.constant(32) print ('[Lab2] a + b = %s' % sess.run(a+b)) # 42
  • 139. 누구나 TensorFlow! J. Kang Ph.D. LAB2.5 Matrix Multiplication Matrix multiplication Tensorflow로 해보기 – 1 by 2 vector 생성 [[2.,3.]] – 2 by 1 vector 생성 [[1.],[2.]] – tf.matmul(mtx1,mtx2) – 세션 생성 – 세션 실행 – 결과 출력 – 세션 종료 139
  • 140. 누구나 TensorFlow! J. Kang Ph.D. LAB2.5 Matrix Multiplication Matrix multiplication Tensorflow로 해보기 140 lab25_runTFmatmul.py (tensorflow) $ vim lab25_runTFmatmul.py import tensorflow as tf mtx1 = tf.constant([[2., 3.]]) # 1 by 2 vector 생성 mtx2 = tf.constant([[1.],[2.]]) # 2 by 1 vector 생성 product = tf.matmul(mtx1,mtx2) sess = tf.Session() eval_result = sess.run(product) print (‘# [TF result] eval_result = %s’ % eval_result) sess.close()
  • 141. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 tf.Variable() – tf.constant()와 는 다르게 그래프 평가 중 값이 변경될 수 있다. – 그래프 평가중 중간 결과값 저장에 사용 – 값을 할당하기 위해서는 tf.assign()을 사용한다. 141
  • 142. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 tf.Variable() 142 ex_runTFvariable.py import tensorflow as tf g = tf.Graph() with g.as_default(): state = tf.Variable(0, name="cnt") one = tf.constant(1) # 상수 노드 add_one = tf.add(state, one) # 연산 노드 cnt_update = tf.assign(state, add_one) # state에 연산결과를 대입 # 변수는 그래프가 올라간 뒤 ‘init’ 연산 실행으로 초기화 init_op = tf.global_variables_initializer() # 계산 그래프를 올리고 연산을 실행합니다. with tf.Session() as sess: sess.run(init_op) #변수를 사용하기 위해서 ‘init’ 연산을 실행 print(sess.run(state)) # ‘state’의 초기값 출력 # ‘state’를 갱신하는 연산 실행 후 ‘state’를 출력 for _ in range(3): sess.run(cnt_update) print(sess.run(state))
  • 143. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 tf.Variable() 143 + one = 1 State state = tf.Variable(0,name=”cnt” add_one = tf.add(state,one) 1 0,1,2,… x = tf.constant(1) cnt_update = tf.assign(state, add_one) 1,2,3,…
  • 144. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 tf.placeholder()와 data feeding – 계산 그래프 평가 실행중 그래프 입력에 훈련 데이터 값을 전달 할 수 있다. – 평가 실행중 같은 그래프 연산을 다른 입력값을 가지고 반복 수행할 수 있다. – Online-learning을 가능하게 한다. 144
  • 145. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Online Learning – 기억? 나죠? 145 Study the Problem Train online ML algorithm Analyze errors Evaluate Release! Lots of Data Chop into pieces
  • 146. 누구나 TensorFlow! J. Kang Ph.D. Types of ML Systems Online Learning – 기억? 나죠? 146 Study the Problem Train online ML algorithm Analyze errors Evaluate Release! Lots of Data Chop into pieces Data feeding!
  • 147. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow 기본요소 tf.placeholder()와 data feeding 147 ex_runTFfeed.py import tensorflow as tf in1 = tf.placeholder(tf.float32) in2 = tf.placeholder(tf.float32) mul_op = tf.multiply(in1, in2) with tf.Session() as sess: # 계산 그래프를 세션에 올리고 그 입력으로 아래를 그래프 내에서 할당 print(sess.run([mul_op], feed_dict={in1:[6.], in2:[14.]}))
  • 148. 누구나 TensorFlow! J. Kang Ph.D. TensorFlow API reference 모르는 API가 나오면 스스로 찾아보자! – https://www.tensorflow.org/api_docs/python/ 148
  • 149. 누구나 TensorFlow! J. Kang Ph.D. 3. Tensorflow 준비하기 - 왜 TensorFlow인가? + TensorFlow 설치 - LAB2: Helloworld in TensorFlow - TensorFlow의 기본요소 - LAB3: TensorFlow 기본예제, Line-fitting - 이제한번 해보자! 149
  • 150. 누구나 TensorFlow! J. Kang Ph.D. Data set의 종류 Training Set – For model training Validation Set – For overfitting preventing – Learning parameter adjustment • Learning_rate • Batch_size Test Set – For final performance evaluation Training : validation : test = 5:3:2 150
  • 151. 누구나 TensorFlow! J. Kang Ph.D. 머신러닝 훈련 단계  step I: 해결해야 할 문제 파악하기  step II: 데이터 수집 + 정제하기 + 관찰하기  step III: 훈련 모델 정하기 – Linear model ?, Neural network? – Types of Activation functions ? – Number of layers?  step IV: cost function 정하기 – 어떤 cost를 가지고 모델 파라미터를 훈련할 것인가? – MSE, MAE, cross-entropy,… 151
  • 152. 누구나 TensorFlow! J. Kang Ph.D. 머신러닝 훈련 단계  step V: 모델 파라미터 찾기위한 optimizer 정하기 – 어떤 solver로 최적화 문제를 풀것인가? – Gradient descent?, Conjugate gradient? Adam optimizer ?  step VI: 훈련 설정 정하기 – 데이터 feeding 설정 • training_size : 전체 training set 크기 • batch_size: 단일 minibatch processing에 들어갈 batch사이즈 • Batch 횟수 : total_batch = int(training_size / batch_size) – 최적화 Solver 설정 • Training_epoch : 같은 데이터 통한 훈련 반복횟수 • Learning_rate: 최적화 속도 opt solver의 단일스텝의 크기 152
  • 153. 누구나 TensorFlow! J. Kang Ph.D. Training epoch loop – Overfitting 방지용: validation set을 가지고 함께 평가 Total_batch loop – 모델 훈련용: training set을 minibatch로 쪼개서 훈련 153 Loop configuration for epoch in range(training_epochs): total_batch = int(training_size / batch_size) for i in range(total_batch): # minibatch training by optimizer here
  • 154. 누구나 TensorFlow! J. Kang Ph.D. 154 - 1) ML모델 수정 - Training set performance - 2) ML모델 수정 + 러닝 파라미터 조정 - Validation set performance - 2) 데이터 셋 추가 - Test set performance
  • 155. 누구나 TensorFlow! J. Kang Ph.D. LAB3: TensorFlow, Line-fitting 일단 무작정 따라해보자 ! – Ex line-fitting example • GitHub link – https://github.com/jwkanggist/EveryBodyTensorFlow/blob/master/lab3_runTFLineFitting.py • 입력 X, 출력 Y 155 Y X
  • 156. 누구나 TensorFlow! J. Kang Ph.D. ML training in Tensorflow  텐플에서 모델을 훈련을 위한 스크립트의 기본구성은 다음과 같다. – Step 1) 데이터셋 준비하기 – Step 2) 러닝 파라미터 설정하기 – Step 3) 계산 그래프 정의하기 – Step 4) 성능 측정 모델 정의하기 – Step 5) 모델 훈련시키기 – Step 6) 시각화 하기 156
  • 157. 누구나 TensorFlow! J. Kang Ph.D. ML training in Tensorflow Step I) 데이터 셋 (X,Y) 준비하기 ML 좋은 데이터 셋을 준비하는 것이 80% 이다!! X: feature, Y: label – 1) Outlier & Irregular 데이터 제거 • 빈칸, NaN – 2) Normalization of data set X • 데이터 크기(abs)가 [0,1] 범위 안에 들어오록 스케일링 • norm_X = abs( X ) / max_value_abs * sign(X) – 3) Standardization of data set X • 데이터의 분포가 zero-mean, unit-variance를 가지게 스케일링 • stand_X = ( X – mean(X) ) / std(X) 157
  • 158. 누구나 TensorFlow! J. Kang Ph.D. 158 lab3_runTFLineFitting.py # experiment data generation total_size = 5000 training_size = 4000 validation_size = 1000 xsize = 20 x_data = np.zeros([xsize, total_size]) a_true = 2 b_true = 0.5 for i in range(total_size): x_data[:,i] = np.linspace(0,10,xsize) noise_var = 1.0 noise = np.sqrt(noise_var) * np.random.randn(xsize,total_size) y_clean = a_true * x_data + b_true y_data = y_clean + noise # data segmentation x_training_data = x_data[:,0:training_size] y_training_data = y_data[:,0:training_size] x_validation_data = x_data[:,training_size:-1] y_validation_data = y_data[:,training_size:-1]
  • 159. 누구나 TensorFlow! J. Kang Ph.D. ML training in Tensorflow Step II) 러닝 파라미터 설정하기 – 1) training_epochs > 0 : 최적화 반복 학습 횟수 • 매 iteration 마다 같은 데이터셋 사용 – 2) learning_rate in (0,1] : model이 데이터로 부터 학습하는 속도를 결정한다. • learning_rate↑  학습속도 ↑, 발산가능성↑ – 3) batch_size 결정: • Training data가 batch_size 단위로 나누어 져서 총 total_batch = int(training_size / batch_size)회 학습이 수행됨 • 데이터 feeding loop가 도는 동안 cost는 누적 계산된다. 159
  • 160. 누구나 TensorFlow! J. Kang Ph.D. 160 lab3_runTFLineFitting.py # configure training parameters ===================================== learning_rate = 0.000001 training_epochs = 20 batch_size = 100 display_step = 1 total_batch = int(training_size/batch_size) #
  • 161. 누구나 TensorFlow! J. Kang Ph.D. ML training in Tensorflow Step III) 계산 그래프 정의하기 Ex) Linear model: pred_Y = a*x + b, MSE cost func. – 1) training data (X, Y) 를 feeding 하기위한 tf.placehoder Tensor 선언 – 2) model parameter (a, b)값 저장을 위한 tf.Variable Tensor 선언 – 3) 학습모델의 입출력 관계 설정 • linear model: y_pred = a * x + b – 4) Cost function 설정 • cost = tf.reduce_mean(tf.reduce_sum( tf.square(y - pred_y) , reduction_indices=1), name="mse") – 5) optimizer 설정 (GradientDescent) • optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) 161
  • 162. 누구나 TensorFlow! J. Kang Ph.D. 162 lab3_runTFLineFitting.py # computational TF graph construction ================================ x = tf.placeholder(tf.float32, [xsize,None]) y = tf.placeholder(tf.float32, [xsize,None]) # Set model weights which is calculated in the TF graph a = tf.Variable(0.) # initialization by 1 b = tf.Variable(0.) print ('TF graph nodes are defined') # Construct model pred_y = a * x + b # Minimize error using MSE function cost = tf.reduce_mean(tf.reduce_sum( tf.square(y - pred_y) , reduction_indices=1), name="mse") # Gradient Descent optimizer = tf.train.GradientDescentOptimizer(learning_rate).minimize(cost) print ('Functions in TF graph are ready')
  • 163. 누구나 TensorFlow! J. Kang Ph.D. ML training in Tensorflow Step IV) 성능 측정 모델 정의하기 – 학습결과에 대한 성능을 측정하기 위한 model을 정의 – 학습모델에 의한 예측값과 실제 데이터의 label값이 어느정도로 일치하는 측정한다. • 1) Classification: Miss-classification rate를 사용 – training set과 validation set의 성능을 나누어서 측정 – Bayesian theory 에 근거함 • 2) Regression: Mean squared error 사용 163
  • 164. 누구나 TensorFlow! J. Kang Ph.D. 164 lab3_runTFLineFitting.py ## Performance evaluation model ========================_y=========== # y : data output # pred_y: prediction output by model, a x + b correct_prediction = cost # Calculate error rate using data -------------- accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32)) error_rate_training = np.zeros(training_epochs) error_rate_validation = np.zeros(training_epochs)
  • 165. 누구나 TensorFlow! J. Kang Ph.D. ML training in Tensorflow  Step V) 모델 훈련시키기 – 1) 정의한 계산그래프를 tf.Session()에 올려서 계산 – 2) tf.Session() 안에서 variable사용을 위해서… • init = tf.global_variables_initializer() 정의 • tf.Session() 안에서 가장 먼저 실행한다. (sess.run(init) # this for variable use) – 3) tf.Sesson()안에서 두개의 for loop 로 구성된다. • Training epoch Loop: 최적화 반복 학습을 위한 loop • Total batch Loop: 데이터 feeding 를 위한 loop – 4) placeholder (x,y)에 training data가 feeding • 여기서 전체 데이터가 total_batch 번으로 나뉘어서 feeding된다. • 데이터 feeding loop가 도는 동안 cost는 누적 계산된다. 165
  • 166. 누구나 TensorFlow! J. Kang Ph.D. 166 lab3_runTFLineFitting.py # Launch the graph (execution) ======================================== # Initializing the variables init = tf.global_variables_initializer() ## -------------------- Learning iteration start -------------------- with tf.Session() as sess: sess.run(init) # this for variable use # Training cycle for epoch in range(training_epochs): # training_epoch loop avg_cost = 0. total_batch = int(training_size/batch_size) # Loop over all batches for i in range(total_batch): # total batch loop [ Total batch loop inside …] print("--------------------------------------------") print("Optimization Finished!")
  • 167. 누구나 TensorFlow! J. Kang Ph.D. 167 lab3_runTFLineFitting.py for i in range(total_batch): # total batch loop data_start_index = i * batch_size data_end_index = (i + 1) * batch_size # feed traing data -------------------------- batch_xs = x_training_data[:,data_start_index:data_end_index] batch_ys = y_training_data[:,data_start_index:data_end_index] #---------------------------------------------- # Run optimization op (backprop) and cost op (to get loss value) # feedign training data _, local_batch_cost = sess.run([optimizer, cost], feed_dict={x: batch_xs, y: batch_ys}) # Compute average loss avg_cost += local_batch_cost / total_batch # print ("At %d-th batch in %d-epoch, avg_cost = %f" % (i,epoch,avg_cost) ) # Display logs per epoch step if (epoch+1) % display_step == 0: print("Epoch:", '%04d' % (epoch+1), "cost=", "{:.9f}".format(avg_cost/batch_size)) batch_xs = x_training_data batch_ys = y_training_data error_rate_training[epoch] = accuracy.eval({x: batch_xs, y: batch_ys},session=sess)/training_size error_rate_validation[epoch] = accuracy.eval({x: x_validation_data, y:y_validation_data},session=sess)/validation_size print("Training set MSE:", error_rate_training[epoch]) print("Validation set MSE:", error_rate_validation[epoch])
  • 168. 누구나 TensorFlow! J. Kang Ph.D. ML training in Tensorflow Step VI) 시각화 하기 168
  • 169. 누구나 TensorFlow! J. Kang Ph.D. 169 lab3_runTFLineFitting.py pred_a = sess.run(a) pred_b = sess.run(b) ##------------------------------------------- # # training Result display print("Validation set Err rate:", accuracy.eval({x: x_validation_data, y: y_validation_data},session=sess)/validation_size) hfig1 = plt.figure(1,figsize=(10,10)) epoch_index = np.array([elem for elem in range(training_epochs)]) plt.plot(epoch_index,error_rate_training,label='Training data',color='r',marker='o') plt.plot(epoch_index,error_rate_validation,label='Validation data',color='b',marker='x') plt.legend() plt.title('MSE of prediction:') plt.xlabel('Iteration epoch') plt.ylabel('MSE') hfig2 = plt.figure(2,figsize=(10,10)) pred_y = pred_a * x_data[:,0] + pred_b plt.plot(x_validation_data[:,0],y_validation_data[:,0],label='noisy data',color='b',marker='*') plt.plot(x_validation_data[:,0], pred_y,label='prediction',color='r') plt.legend() plt.title('A line fitting example:') plt.xlabel('X data') plt.ylabel('Y data') plt.show()
  • 170. 누구나 TensorFlow! J. Kang Ph.D. ML training in Tensorflow Step VI) further 시각화 하기 – Tensorboard를 이용해 보자! – Tensorflow training 과정을 로그파일로 저장하고, 훈련이후에 localhosting을 이용해서 로그파일을 시각화 해주는 도구  주요기능 – 주요 훈련지표의 training step에 따른 트래킹 – 그래프의 variable 값의 분포 시각화 – 계산그래프 구조의 시각화 – 참고문서: https://docs.google.com/document/d/1BMZdIXp-3lUWYXaJcJZtcgpX0VAlDGRueZ7-bYht198/edit 170
  • 171. 누구나 TensorFlow! J. Kang Ph.D. End of Day1 Lecture Thank you –Day2 Lecture link here 171
  • 172. 누구나 TensorFlow! J. Kang Ph.D. Call for Contribution to EveryTF Group! jwkang@soundl.ly 로 메일 – 같이 집단 지성을 만들어가요! – 관심 분야! • GAN / VAE • RL • Mobile CNN • Etc. Applications 172
  • 173. 누구나 TensorFlow! J. Kang Ph.D. 모두연 MoT랩 소개 딥러닝을 활용하여 세상을 이롭게 할 IoT/Mobile App 개발에 대한 연구를 같이 해봐요!!  https://www.facebook.com/lab4all/posts/761099760749661  jwkang@soundl.ly 로 메일 Keywords: – Thin CNN Model – Model Pruning – Tensorflow + lite – Embedded Sys. (IoT) – Android Mobile/Things 173

Editor's Notes

  1. 안녕하세요 MATLAB 1일차 첫 시간을 시작하겠습니다
  2. 강의를 시작하기 전에 제 소개를 잠깐 드리면 저는 현재 정보통신과 박사과정에 재학중인 학생이고요 강재욱이라고 합니다 즉 여러분의 학교 선배가 입니다 저는 현재 김기선 교수님과 연구를 같이하고 있습니다 연구분야는 간단하게 얘기하면 선형 시스템의 저복잡도 역변환 알고리즘을 연구하고 있습니다 자세한 내용은 저의 홈페이지나 저희 연구실 홈페이지에서 보실수 있습니다. 강의내용에 대한 질문이나 기타 저희 연구에 관심이 있으신 분은 이메일로 연락주시면 자세히 설명해 드리도록 하겠습니다 또한 기타 도움이 필요하신 경우에 연락 주시기바랍니다
  3. 본 matlab 강의는 총 3일에 걸쳐서 3명의 강사가 진행합니다. 그 차례는 다음과 같습니다 따라서 저는 여러분 오늘 아침시간과 내일 아침시간을 함께 즐겁게 보내게 되겠습니다
  4. 본 matlab 강의는 총 3일에 걸쳐서 3명의 강사가 진행합니다. 그 차례는 다음과 같습니다 따라서 저는 여러분 오늘 아침시간과 내일 아침시간을 함께 즐겁게 보내게 되겠습니다
  5. 본 matlab 강의는 총 3일에 걸쳐서 3명의 강사가 진행합니다. 그 차례는 다음과 같습니다 따라서 저는 여러분 오늘 아침시간과 내일 아침시간을 함께 즐겁게 보내게 되겠습니다
  6. 먼저 메트랩 프로그래밍의 가장 일반적인 부분에 대해서 애기를 해보겠습니다 강의 중간에 질문이 있으시면 언제든지 손을 들고 말씀해 주세요 사실 맵틀랩도 하나의 프로그래밍 언어이기 때문에 그 기초는 다른 언어와 매우 흡사합니다 혹시 매트랩 프로그래밍에 경험이 있으신 분 얼마나 되나요? 아니면 씨언어? 잘하시는 분들은 좀 지루할 수도 있겠지만 간단하게 짚어보도록 하겠습니다.
  7. 저의 발표 자료와 강의 구성은 아타웨이 교수의 책을 참고로 하였습니다 책의 PDF파일을 제가 가지고 있습니다 관심있으신 분은 연락 주세요
  8. 여러분이 지난 2틀 동안 메스메티카를 공부한 걸로 압니다 Matlab는 메스메티카와는 다르게 신호처리 통게적 시뮬레이션 에 특화된 프로그래밍입니다 그 이유는 ….. 따라서 메스메티카와 비교했는때 계산에 장점을 가집니다. 반면에 심볼릭 연산 즉 수식을 유도하는 것 적분 미분 푸는일은 메스메티카가 더 잘합니다 용도에 따라서 두 프로그램을 자유자재로 사용하시면 여러분의 미래의 연구에 매우 강력한 도구가 될 것입니다.
  9. 여러분이 지난 2틀 동안 메스메티카를 공부한 걸로 압니다 Matlab는 메스메티카와는 다르게 신호처리 통게적 시뮬레이션 에 특화된 프로그래밍입니다 그 이유는 ….. 따라서 메스메티카와 비교했는때 계산에 장점을 가집니다. 반면에 심볼릭 연산 즉 수식을 유도하는 것 적분 미분 푸는일은 메스메티카가 더 잘합니다 용도에 따라서 두 프로그램을 자유자재로 사용하시면 여러분의 미래의 연구에 매우 강력한 도구가 될 것입니다.
  10. 먼저 매틀랩을 구성하는 두가지 종류의 파일에 대해서 얘기해 보겠습니다. 한가지는 스크립트 파일입니다 이 파일은 간단하게 말하면 우리가 실행하는 매트랩 명령어의 모음이라고 생각하시면 됩니다. 스트립트 파일을 실행 시키면 매트랩 컴파일러는 스크립트 파일의 가장 위에있는 명령부터 차레대로 수행합니다 다른 한가지는 함수파일입니다 함수파일은 두가지 가있는데 하나는 사용자 직접 정의 하는 함수가 있고 다른 하나는 매트랩에서 일반적으로 자주 사용되는 기능을 위해서 기본적으로 제공하는 함수가 있습니다 프로그래밍에서 이런한 함수의 집합을 라이브러리라고 하는데 매트랩은 수학연산을 위한 매우 강력하고 폭 넓은 라이브러리를 제공하기 때문에 강력합니다 본 강의에서는 다양한 스크립트 파일과 함수 파일이 나올텐데요 혼란을 피하기 위해서 함수 파일은 직선 박스 안에 표시하고 스크립트파일은 점선 박스 안에 표시하겠습니다.
  11. 먼저 매틀랩을 구성하는 두가지 종류의 파일에 대해서 얘기해 보겠습니다. 한가지는 스크립트 파일입니다 이 파일은 간단하게 말하면 우리가 실행하는 매트랩 명령어의 모음이라고 생각하시면 됩니다. 스트립트 파일을 실행 시키면 매트랩 컴파일러는 스크립트 파일의 가장 위에있는 명령부터 차레대로 수행합니다 다른 한가지는 함수파일입니다 함수파일은 두가지 가있는데 하나는 사용자 직접 정의 하는 함수가 있고 다른 하나는 매트랩에서 일반적으로 자주 사용되는 기능을 위해서 기본적으로 제공하는 함수가 있습니다 프로그래밍에서 이런한 함수의 집합을 라이브러리라고 하는데 매트랩은 수학연산을 위한 매우 강력하고 폭 넓은 라이브러리를 제공하기 때문에 강력합니다 본 강의에서는 다양한 스크립트 파일과 함수 파일이 나올텐데요 혼란을 피하기 위해서 함수 파일은 직선 박스 안에 표시하고 스크립트파일은 점선 박스 안에 표시하겠습니다.
  12. 먼저 매틀랩을 구성하는 두가지 종류의 파일에 대해서 얘기해 보겠습니다. 한가지는 스크립트 파일입니다 이 파일은 간단하게 말하면 우리가 실행하는 매트랩 명령어의 모음이라고 생각하시면 됩니다. 스트립트 파일을 실행 시키면 매트랩 컴파일러는 스크립트 파일의 가장 위에있는 명령부터 차레대로 수행합니다 다른 한가지는 함수파일입니다 함수파일은 두가지 가있는데 하나는 사용자 직접 정의 하는 함수가 있고 다른 하나는 매트랩에서 일반적으로 자주 사용되는 기능을 위해서 기본적으로 제공하는 함수가 있습니다 프로그래밍에서 이런한 함수의 집합을 라이브러리라고 하는데 매트랩은 수학연산을 위한 매우 강력하고 폭 넓은 라이브러리를 제공하기 때문에 강력합니다 본 강의에서는 다양한 스크립트 파일과 함수 파일이 나올텐데요 혼란을 피하기 위해서 함수 파일은 직선 박스 안에 표시하고 스크립트파일은 점선 박스 안에 표시하겠습니다.
  13. 먼저 매틀랩을 구성하는 두가지 종류의 파일에 대해서 얘기해 보겠습니다. 한가지는 스크립트 파일입니다 이 파일은 간단하게 말하면 우리가 실행하는 매트랩 명령어의 모음이라고 생각하시면 됩니다. 스트립트 파일을 실행 시키면 매트랩 컴파일러는 스크립트 파일의 가장 위에있는 명령부터 차레대로 수행합니다 다른 한가지는 함수파일입니다 함수파일은 두가지 가있는데 하나는 사용자 직접 정의 하는 함수가 있고 다른 하나는 매트랩에서 일반적으로 자주 사용되는 기능을 위해서 기본적으로 제공하는 함수가 있습니다 프로그래밍에서 이런한 함수의 집합을 라이브러리라고 하는데 매트랩은 수학연산을 위한 매우 강력하고 폭 넓은 라이브러리를 제공하기 때문에 강력합니다 본 강의에서는 다양한 스크립트 파일과 함수 파일이 나올텐데요 혼란을 피하기 위해서 함수 파일은 직선 박스 안에 표시하고 스크립트파일은 점선 박스 안에 표시하겠습니다.
  14. 먼저 메트랩 프로그래밍의 가장 일반적인 부분에 대해서 애기를 해보겠습니다 강의 중간에 질문이 있으시면 언제든지 손을 들고 말씀해 주세요 사실 맵틀랩도 하나의 프로그래밍 언어이기 때문에 그 기초는 다른 언어와 매우 흡사합니다 혹시 매트랩 프로그래밍에 경험이 있으신 분 얼마나 되나요? 아니면 씨언어? 잘하시는 분들은 좀 지루할 수도 있겠지만 간단하게 짚어보도록 하겠습니다.
  15. 크렇기 때문에 매틀랩 프로그램은 다양한 함수 파일과 스크립트 파일로 구성되겠죠 자 그럼 본격적으로 프로그래밍에 들어가보죠 프로그래밍 방식에는 여러가지가 있지만 매트랩 프로그래밍은 모듈러 프로그래밍 입니다 즉 전체의 작업을 여러 개의 작은 ……..모듈로 나누고 각 모듈을 함수로 구성하면서 그 함수를 스크립트에 모아서 실행시키는 거죠 알고리즘적으로 말하면 divide and conquer라고 도 하고요 Top-down프로그래밍 방식이라고도 부릅니다 여러분이 익숙한 씨언어로 견주어서 말하면 함수는 함수고 스크립트 파일은 메인함수에 해당됩니다
  16. 크렇기 때문에 매틀랩 프로그램은 다양한 함수 파일과 스크립트 파일로 구성되겠죠 자 그럼 본격적으로 프로그래밍에 들어가보죠 프로그래밍 방식에는 여러가지가 있지만 매트랩 프로그래밍은 모듈러 프로그래밍 입니다 즉 전체의 작업을 여러 개의 작은 ……..모듈로 나누고 각 모듈을 함수로 구성하면서 그 함수를 스크립트에 모아서 실행시키는 거죠 알고리즘적으로 말하면 divide and conquer라고 도 하고요 Top-down프로그래밍 방식이라고도 부릅니다 여러분이 익숙한 씨언어로 견주어서 말하면 함수는 함수고 스크립트 파일은 메인함수에 해당됩니다
  17. 사용자 함수정의를 연습해 보기 위해서 하나의 예를 들도록하겠습니다 반지름 값을 입력인자로 받아서 원의 원주와 넓이를 계산하는 함수 입니다 한번 어러분의 맵틀랩을 키고 타이핑 해보세요 그리고 파일 이름은 함수이름과 동일하게 저장하도록합니다 원주와 넓이를 계산공식은 간단하기 때문에 바디를 작성해 보세요
  18. 사용자 함수정의를 연습해 보기 위해서 하나의 예를 들도록하겠습니다 반지름 값을 입력인자로 받아서 원의 원주와 넓이를 계산하는 함수 입니다 한번 어러분의 맵틀랩을 키고 타이핑 해보세요 그리고 파일 이름은 함수이름과 동일하게 저장하도록합니다 원주와 넓이를 계산공식은 간단하기 때문에 바디를 작성해 보세요
  19. 사용자 함수정의를 연습해 보기 위해서 하나의 예를 들도록하겠습니다 반지름 값을 입력인자로 받아서 원의 원주와 넓이를 계산하는 함수 입니다 한번 어러분의 맵틀랩을 키고 타이핑 해보세요 그리고 파일 이름은 함수이름과 동일하게 저장하도록합니다 원주와 넓이를 계산공식은 간단하기 때문에 바디를 작성해 보세요
  20. 사용자 함수정의를 연습해 보기 위해서 하나의 예를 들도록하겠습니다 반지름 값을 입력인자로 받아서 원의 원주와 넓이를 계산하는 함수 입니다 한번 어러분의 맵틀랩을 키고 타이핑 해보세요 그리고 파일 이름은 함수이름과 동일하게 저장하도록합니다 원주와 넓이를 계산공식은 간단하기 때문에 바디를 작성해 보세요
  21. 사용자 함수정의를 연습해 보기 위해서 하나의 예를 들도록하겠습니다 반지름 값을 입력인자로 받아서 원의 원주와 넓이를 계산하는 함수 입니다 한번 어러분의 맵틀랩을 키고 타이핑 해보세요 그리고 파일 이름은 함수이름과 동일하게 저장하도록합니다 원주와 넓이를 계산공식은 간단하기 때문에 바디를 작성해 보세요
  22. 사용자 함수정의를 연습해 보기 위해서 하나의 예를 들도록하겠습니다 반지름 값을 입력인자로 받아서 원의 원주와 넓이를 계산하는 함수 입니다 한번 어러분의 맵틀랩을 키고 타이핑 해보세요 그리고 파일 이름은 함수이름과 동일하게 저장하도록합니다 원주와 넓이를 계산공식은 간단하기 때문에 바디를 작성해 보세요
  23. 사용자 함수정의를 연습해 보기 위해서 하나의 예를 들도록하겠습니다 반지름 값을 입력인자로 받아서 원의 원주와 넓이를 계산하는 함수 입니다 한번 어러분의 맵틀랩을 키고 타이핑 해보세요 그리고 파일 이름은 함수이름과 동일하게 저장하도록합니다 원주와 넓이를 계산공식은 간단하기 때문에 바디를 작성해 보세요
  24. 사용자 함수정의를 연습해 보기 위해서 하나의 예를 들도록하겠습니다 반지름 값을 입력인자로 받아서 원의 원주와 넓이를 계산하는 함수 입니다 한번 어러분의 맵틀랩을 키고 타이핑 해보세요 그리고 파일 이름은 함수이름과 동일하게 저장하도록합니다 원주와 넓이를 계산공식은 간단하기 때문에 바디를 작성해 보세요
  25. 먼저 매틀랩을 구성하는 두가지 종류의 파일에 대해서 얘기해 보겠습니다. 한가지는 스크립트 파일입니다 이 파일은 간단하게 말하면 우리가 실행하는 매트랩 명령어의 모음이라고 생각하시면 됩니다. 스트립트 파일을 실행 시키면 매트랩 컴파일러는 스크립트 파일의 가장 위에있는 명령부터 차레대로 수행합니다 다른 한가지는 함수파일입니다 함수파일은 두가지 가있는데 하나는 사용자 직접 정의 하는 함수가 있고 다른 하나는 매트랩에서 일반적으로 자주 사용되는 기능을 위해서 기본적으로 제공하는 함수가 있습니다 프로그래밍에서 이런한 함수의 집합을 라이브러리라고 하는데 매트랩은 수학연산을 위한 매우 강력하고 폭 넓은 라이브러리를 제공하기 때문에 강력합니다 본 강의에서는 다양한 스크립트 파일과 함수 파일이 나올텐데요 혼란을 피하기 위해서 함수 파일은 직선 박스 안에 표시하고 스크립트파일은 점선 박스 안에 표시하겠습니다.
  26. 먼저 메트랩 프로그래밍의 가장 일반적인 부분에 대해서 애기를 해보겠습니다 강의 중간에 질문이 있으시면 언제든지 손을 들고 말씀해 주세요 사실 맵틀랩도 하나의 프로그래밍 언어이기 때문에 그 기초는 다른 언어와 매우 흡사합니다 혹시 매트랩 프로그래밍에 경험이 있으신 분 얼마나 되나요? 아니면 씨언어? 잘하시는 분들은 좀 지루할 수도 있겠지만 간단하게 짚어보도록 하겠습니다.
  27. 저의 발표 자료와 강의 구성은 아타웨이 교수의 책을 참고로 하였습니다 책의 PDF파일을 제가 가지고 있습니다 관심있으신 분은 연락 주세요
  28. 먼저 메트랩 프로그래밍의 가장 일반적인 부분에 대해서 애기를 해보겠습니다 강의 중간에 질문이 있으시면 언제든지 손을 들고 말씀해 주세요 사실 맵틀랩도 하나의 프로그래밍 언어이기 때문에 그 기초는 다른 언어와 매우 흡사합니다 혹시 매트랩 프로그래밍에 경험이 있으신 분 얼마나 되나요? 아니면 씨언어? 잘하시는 분들은 좀 지루할 수도 있겠지만 간단하게 짚어보도록 하겠습니다.