1. Introduction to Python and TensorFlow
Sang Jun Lee
(Ph.D. candidate, POSTECH)
EECE695J 딥러닝 기초 및 활용 – LECTURE 1
2. 2
▣ 딥러닝의 활용
▣ 인공지능 알고리즘을 구성하기 위해서는?
Introduction
Engineering
background
AI Algorithms+
3. 3
▣ Stock prediction (example)
Introduction
어떤 데이터를 어떻게 사용?
주식 가격, 거래량 등
데이터에 대한 preprocessing
(normalization)
문제의 구성?
• 주식 가격의 상승/하락을 예측하는 classification?
• 주식 가격을 예측하는 regression?
• 일(day) 단위 예측? 년(year) 단위 예측?
Objective: earn money!
고민해야 할 문제들..
4. 4
▣ 전자전기공학특론 (딥러닝 기초 및 활용)
▲ EECE695J, fall semester 2017
▲ Thursday 14:00-15:30
▣ Objective
▲ 딥러닝에 대한 기본 개념 및 기계학습 배경지식 습득
▲ Python 기반의 TensorFlow 프로그래밍 학습 및 딥러닝을 활용한 데이터 기반 알고리즘 구성 연습
Introduction
5. 5
Date Description
Lecture 1 2017. 8. 24
Basics of Python and TensorFlow
Python: Environment setting, basic manipulations
TensorFlow: tensor, data flow graph, session
Lecture 2 2017. 9. 7
Supervised learning
Linear regression and logistic regression: formulation, cost function, multivariable case
Optimization (gradient descent)
(HW1) Implementation of linear regression
Lecture 3 2017. 9. 14
Unsupervised learning
K-means and graph-cut method, spectral clustering
Implementation of k-means algorithm using TensorFlow
Lecture 4 2017. 9. 21
Introduction to neural networks
Basic structure of neural networks: linear transformation, activation functions
Implementation of neural network in Python and TensorFlow
(HW2) Implementation of a neural network for data classification
Lecture 5 2017. 9. 28
Optimizations and regularization of a neural network
Backpropagation
Stochastic gradient descent, Adam optimization method
Regularization via modification of cost function, drop-out algorithm, ensemble method
Lecture 6 2017. 10. 12
Convolutional neural network 1
Components and architecture of convolutional neural networks: convolutional layer, pooling layer
Convolutional neural networks for image classification
(HW3) Implementation of a convolutional neural network for classification of MNIST dataset
Lecture 7 2017. 10. 17
Convolutional neural network 2
Architectures of deep convolutional neural networks, Transfer learning
Lecture 8 2017. 10. 26 Basics of recurrent neural network and its implementation
Schedule
6. 6
▣ Anaconda
▲ 파이썬(프로그래밍 언어) 외에 Numpy, Scipy, Pandas 등의 패키지들을 포함하는 과학용 배포판
▲ Installation: https://www.continuum.io/downloads
Environment setting
9. 9
▣ Python 코딩 블럭 들여쓰기 (Indentation)
▲ 코딩 블럭의 시작: 콜론(:)을 사용
▲ 내부의 코딩블럭을 동일한 공백 사용 (일반적으로 4개의 공백의 들여쓰기 사용)
▲ 중간에 잘못된 공백이 들어가면 ‘IndentationError: unexpected indent’의 에러 발생
▲ 일반적으로 에디터가 자동 정렬 기능 제공
▣ 세미콜론(;)의 사용
▲ 파이썬에서는 구문뒤에 세미콜론(;)을 붙이지 않아도 됨
▲ 그러나 한 줄 에 여러 구문 작성시 세미콜론(;)을 이용하여 구분
Python
# 파이썬의 특징
10. 10
▣ 라이브러리 사용
▲ 라이브러리: 자주 사용되는 기능들을 함수로 구현하여 묶어놓은 패키지
▲ Anaconda가 Numpy, Scipy, Matplotlib 등의 유용한 라이브러리 포함
▲ Import [library name] 의 구문을 이용하여 사용
▲ 예를 들어,
표준 라이브러리 중 하나인 math에 있는 sqrt() 함수를 사용하기 위해서는
Import math 실행 후, math.sqrt() 함수 호출
▲ 내가 필요로 하는 기능이 어떤 라이브러리에 어떤 함수로 구현되어 있는지 아는 것이 필요
▣ 주석(comment)
▲ ‘#’의 기호 사용
Python
# 파이썬의 특징
11. 11
▣ 컬렉션
▲ Python에서는 여러 요소들을 가지는 집합(컬렉션)을 표현하기 위하여 아래와 같은 형태의 컬렉션 기능을 제공
▲ List
• 동적배열(Dynamic array)로서 자유롭게 확장 및 변경 가능
• Mutable 데이터 타입의 요소들로 이루어진 컬렉션
▲ Tuple
• 새로운 요소를 추가하거나 갱신, 삭제 불가능
• Immutable 데이터 타입의 요소들로 구성
▲ Dictionary
• 키(key) – 값(value) 의 쌍을 용소로 가지는 컬렉션
• Key는 immutable, value는 mutable
▲ Set
• 중복이 없는 요소들 (unique elements)로만 구성
• 내부적 요소들을 순서대로 저장하지 않으며, 순서에 의존하는 기능은 사용 불가
Python
# 파이썬의 특징
12. 12
▣ 리스트 (List)
▲ 여러 요소를 가지는 집합(컬렉션)으로 새로운 요소를 추가하거나 갱신, 삭제가 가능
▲ 동적배열(Dynamic Array)로서 자유롭게 확장 가능
▲ 리스트의 요소들은 square bracket([])으로 둘러쌓여 컬렉션을 표현
▲ 각 요소들은 다른 data type으로 구성이 가능하며, 컴마(,)로 구분
▣ 리스트 인덱싱(indexing)
▲ 인덱싱: 특정한 요소 선택
▲ 첫 번째 요소는 list[0], 두 번째 요소는 list[1]
▲ 요소의 인덱스에 음수 사용 가능 list[-1]는 마지막 요소를 의미
▲ 다중 리스트에서의 인덱싱
Python
# 리스트 자료형
[0] [1] [2] [3] [4] [5] [6] (=[-1]) [0]
[0] [1] [2]
13. 13
▣ 리스트 연산자
▲ 더하기(+): 2개의 리스트를 합치는 기능
▲ 반복하기(*)
▣ 리스트 관련 함수
▲ Append: 리스트에 요소 추가
▲ Index: 특정 요소의 위치 반환
Python
# 리스트 자료형
15. 15
▣ 문자열 관련 함수
▲ str.join([리스트]) : 문자열 리스트의 결합
▲ str.split(str) : 하나의 문자열을 separator를 기준으로 분리
Python
# 문자열 자료형
Separator
Separator
16. 16
▣ if 문
▲ 기본구조: 콜론(:)과 들여쓰기(indentation)
Python
# 조건문
17. 17
▣ for 문
▲ 구문:
for 요소 in 리스트
▲ range 함수
▲ for문 예시
▲ break 과 continue
• break: 반복문 안에서 루프를 빠져나올 때 사용
• continue: 루프 블럭의 나머지 부분을 실행하지 않고 다음 루프로 갈 때 사용
Python
# 반복문
18. 18
▣ 함수의 구조 (def)
▲ 반복적으로 사용되는 코드블럭을 함수로 정의하여 사용
▲ 예시: 덧셈 함수
▣ 입력 인수
▲ Default parameter: 입력 인수 초깃값 미리 설정
▲ Named parameter
Python
# 함수
19. 19
▣ 파이썬의 활용
▲ 원하는 기능이 어떤 함수로 정의되어 있으며, 어떤 라이브러리에 있는 함수를 활용하는 것이 효과적인지 아는 것이 중요
▣ NumPy
▲ 다차원 배열 객체 및 수학적인 연산을 수행하는 함수 제공
▲ Vector 및 matrix의 효율적인 연산에 유용
▲ Import numpy as np
Python
# 파이썬 패키지
• 리스트를 이용하여 numpy 배열을 초기화 가능
• 대괄호로 각 요소에 접근
20. 20
▣ NumPy
▲ [np array name].[function] 의 구문으로 NumPy 가 제공하는 함수 실행
Python
# 파이썬 패키지
21. 21
▣ SciPy
▲ 선형대수, 신호 및 영상처리, 최적화 등 다양한 종류의 과학용 알고리즘 제공 및 NumPy의 기능 보완
▲ 영상 데이터의 입출력 및 처리에 주로 사용
Python
# 파이썬 패키지
23. 23
▣ IPython (jupyter notebook)
▲ Interactive computing for Python
▲ 웹 기반의 대화형 프로그래밍 환경 지원
▲ 코딩 및 문서화를 한 화면에서 가능
▲ Cell 단위의 구현 및 실행
Python
# IPython
24. 24
▣ IPython (jupyter notebook)
▲ Interactive computing for Python
▲ 웹 기반의 대화형 프로그래밍 환경 지원
▲ 코딩 및 문서화를 한 화면에서 가능
▲ Cell 단위의 구현 및 실행 가능
Python
# IPython
25. 25
▣ Jupyter notebook 설치 및 실행
▲ 설치: command window에서 “pip install jupyter”
▲ 실행: command window의 원하는 폴더에서 “jupyter notebook”
▲ cd [folder path] : command window에서 원하는 폴더로의 이동
Python
# IPython
28. 28
▣ Jupyter notebook 단축키
▲ 핵심 단축키
• a/b : 위/아래에 셀 추가
• ctrl + enther : 현재 셀 실행(run)
• dd 혹은 x : 셀 삭제
Python
# IPython
Edit mode 단축키 Command mode 단축키
29. 29
▣ Markdown mode 단축키
▲ Document 작성 (코드에 대한 설명)
▲ 수학 수식 표현 가능
Python
# IPython
30. 30
▲ Open source software library for numerical computation using data flow graphs
▲ Originally developed by Google Brain Team to conduct machine learning and deep neural networks research
▲ General enough to be applicable in a wide variety of other domain as well
TensorFlow
# TensorFlow란?
알고리즘을 표현하는 부분과 알고리즘 실행하는 부분을 분리
Data Flow Graph Session
31. 31
TensorFlow
# TensorFlow에서 중요한 세 가지
Tensor
Multi-dimensional numerical array
Data Flow Graph
구성하는 시스템을 표현 (알고리즘 구성)
Session
Graph(알고리즘)의 실행
32. 32
TensorFlow
# Data flow graph
▣ Node(operation)와 edge(connection)로 구성
▣ TensorFlow separates definition of computations from their execution
▣ 알고리즘의 구성
1. Assemble a graph
2. Use a session to execute operations in the graph
33. 33
TensorFlow
# Data flow graph
Reference: CS20SI - lecture 1. Overview of Tensorflow (http://web.stanford.edu/class/cs20si/syllabus.html)
34. 34
TensorFlow
# Data flow graph
Reference: CS20SI - lecture 1. Overview of Tensorflow (http://web.stanford.edu/class/cs20si/syllabus.html)
49. 49
1. Data preparation
2. Create place holder
3. Create variables for weight and bias
4. Construct a model to predict Y
5. Define a loss function and optimization method
6. Initialize variables
7. Train the model
8. Output the value of w and b
TensorFlow
# TensorFlow implementation for linear regression
51. 51
TensorFlow
# TensorFlow example: linear regression
Reference: CS20SI - lecture 2. Operations (http://web.stanford.edu/class/cs20si/syllabus.html)
TensorFlow를 활용하여 간단한 linear regression 문제 풀어보기
52. 52
“본 강의 자료는 아래와 같은 자료들을 참고하여 구성하였습니다.”
▲ Environment setting
• [Python 강의] Anaconda, Jupyter를 이용한 파이썬 개발환경 구축 / http://temp123.tistory.com/17
• [Tensorflow] windows 에 Tensorflow 설치하기 - CUDA GPU / http://dwfox.tistory.com/85
• 윈도우즈에 아나콘다, 텐서플로우 설치하기 / https://tensorflow.blog/%EC%9C%88%EB%8F%84%EC%9A%B0%EC%A6%88%EC%97%90-
%EC%95%84%EB%82%98%EC%BD%98%EB%8B%A4-%ED%85%90%EC%84%9C%ED%94%8C%EB%A1%9C%EC%9A%B0-
%EC%84%A4%EC%B9%98%ED%95%98%EA%B8%B0/
▲ Python
• 예제로 배우는 Python 프로그래밍 / http://pythonstudy.xyz/python/article/1-Python-%EC%86%8C%EA%B0%9C
• 파이썬 Python 코딩 블록 들여쓰기(Identation) 알아보기 / http://mainia.tistory.com/5161
• 점프 투 파이썬 / https://wikidocs.net/book/1
• Python Numpy Tutorial / http://aikorea.org/cs231n/python-numpy-tutorial/#numpy
• 파이썬 강좌 / http://blog.eairship.kr/276
• 파이썬기초 파이썬 다중설치부터 Jupyter를 이용한 프로그래밍 (이태영) / https://www.slideshare.net/TaeYoungLee1/2016317-jupyter
▲ TensorFlow
• Reference: CS20SI - lecture 1. Overview of Tensorflow (http://web.stanford.edu/class/cs20si/syllabus.html)
• Reference: CS20SI - lecture 2. Operations (http://web.stanford.edu/class/cs20si/syllabus.html)
Reference