# YOLO v3 demo webcam 돌려보기 for ubuntu 18.04


# YOLO란 무엇인가

- 는 웹사이트 읽어보시면 자세히 나와있습니다: https://pjreddie.com/darknet/yolo/

- 요약: YOLO가 나오기 전까지의 CNN은 사진을 여러조각(kernel or filter size)으로 그리고 그것들이 겹치게(stride) 하는 알고리즘이였다면, YOLO는 stride를 없애는(You Only Look Once) 전략으로 만들어진 알고리즘.



# 진행단계

- darknet 소스 다운로드

    - https://github.com/pjreddie/darknet


- CUDA 빌드환경 구성

    - Nvidia용 Additional driver 추가

    - CUDA toolkit 설치


- OpenCV 빌드환경 구성

    - OpenCV 설치


- darknet 빌드

- darknet 실행




0. 준비물

- Nvidia CUDA 지원 그래픽카드

- OpenCV

- webcam: ubuntu 호환되는 제품(ubuntu 내에 cheese 앱 실행여부로 확인가능)

- ubuntu(18.04): 이 데모가 ubuntu에서 진행되었기 때문.



1. darknet 소스 다운로드

- 적절한 위치에서

- $ git clone https://github.com/pjreddie/darknet.git



2. CUDA 빌드환경 구성

2.1. Nvidia용 Additional driver 추가

- Software & Updates > Additional Drivers > 드라이버 선택

  (YOLO 빌드가 안되는 낮은 버전이 있으니 주의)


2.2. CUDA toolkit 설치

- 설치가이드: https://developer.nvidia.com/cuda-downloads

    - 운영체제와 버전에 따라 설치

    - Tensorflow Object Detection에서는 CUDA 9.0을 지원하는데 CUDA 10.0 설치하면 호환에 어려움이 있을것.


2.3. ubuntu 내에서의 실행환경구성

- path와 기타 설정들을 알아서 해줌.

- $ sudo apt install nvidia-cuda-toolkit



3. OpenCV 빌드환경 구성

- 설치가이드: https://docs.opencv.org/3.4.1/d2/de6/tutorial_py_setup_in_ubuntu.html

- $ sudo apt-get install python-opencv



4. darknet 빌드 및 실행

4.1. Makefile 수정

    - $ vi Makefile

    - GPU=1

    - OPENCV=1

    - :wq

    - $ make


4.2. darknet 실행

- data출처(?) / hyperparameter 설정값 / weight 순서로 지정

- 실행을 위한 설정들이 cfg 파일 안에 있으니 해당 디렉토리를 참조


- $ ./darknet detector demo cfg/coco.data cfg/yolov3.cfg yolov3.weights

  OR 메모리 부족이라고 나오는 경우 tiny 버전으로...

- $ ./darknet detector demo cfg/coco.data cfg/yolov3-tiny.cfg yolov3-tiny.weights

'Machine Learning' 카테고리의 다른 글

Activation functions  (0) 2017.11.30
Wrap-up "Machine learning" by Andrew Ng  (0) 2017.10.13
Binomial Logistic Regression/Classification  (0) 2017.07.10
Linear Regression  (0) 2017.07.07

"시즌 RL - Deep Reinforcement Learning" Wrap-up

학습을 마치며 전반적 강의내용에 대한 정리를 해본다.

Reinforcement의 뜻은(강화학습이지만) "어떻게 하면 좋은선택을 꾸준히 할 수 있을까?"를 목표로 최적화해 나아가는 과정으로 이해된다.

개인적으로 이 강의가 상당히 어렵고 난해하게 느껴졌는데

아마도 Supervised learning의 상식을 가지고 Reinforcement learning분야를 해결해 나아간다는 것이

어떻게 보면 진짜로 잘 될까? 이게 왜 되는거지? 왜 꼭 이렇게 하는거지? 라는 의문이 생겨서 학습을 방해한 것 같다.



몇가지 인상깊은 특징을 나열해보면

- 강의내용은 사실 많은 내용을 함축하고 있는것으로 보인다.

  왜 그렇게 접근하는가를 찾으려다 보면 다른 이론을 알아야만 풀리는 것들이 많다.

- Q-table 방식:

  다음 Action을 정할때 기대하는 가장 큰값을 찾는 논리에 있어서 최적경로 알고리즘과 유사한 부분이 있다.

  하지만, 최적경로 탐색은 path간의 weight이 이미 계산되어 있으나,

  RL에서는 탐험을 통해 이 최적경로를 찾아내는 과정 또한 포함되어 있다.

  이 때문에 탐험으로 찾아진 Q-table은 절대적인 weight도 아니고 최적이라고 판단하기 어렵다.

- Q-Network 방식:

  Q-table 방식과 비교될 수 없는 확실히 다른 것인데 이 점을 빨리 깨닫지 못해서 시간을 허비했다.

- 학습을 위해 일정구간을 저장하고, 그 자료를 샘플링해서, next Q를 더해 학습하는 방법이 DQN의 핵심으로 판단된다.



# Wrap-up

1. Frozen Lake World(OpenAI GYM)


2. Q-function

    a. Deterministic: Q-table(Q-learning)

    b. Stochastic: Q-Network

        diverges due to:

        - Correlations between samples

        - Non-stationary Target


3. Exploit VS Exploration

    a. E-greedy

    b. Decay E-greedy

    c. Add random noise


4. DQN: Deep Q-Network

    a. solutions

        1) Go Deep

        2) Capture and Replay

            - 일정구간을 저장했다가 저장된 구간을 랜덤으로 골라 학습

            - Correlations between samples 을 해결

        3) Separate networks

            - 학습하는 동안 next Q를 구할때는 학습을 반영하지 않는 별도의 DQN(target)을 사용함

            - Non-stationary Target 을 해결

    b. DQN 2013

    c. DQN 2015




Reference:

- http://hunkim.github.io/ml/

# Activation functions

여러종류의 Activation function이 존재하고 각각의 미분법이 존재하며

아래 4개의 function에 대해서 알아보기로 한다.

1. Sigmoid

2. tanh

3. ReLU

4. Leaky ReLU



1. Sigmoid

1) definition: 

 

2) derivatives:

 



2. tanh

1) definition:

 

2) derivatives:


 


3. ReLU

 

1) definition:

 

2) derivatives:

 

 



4. Leaky ReLU

 

1) definition:

 

2) derivatives:

Wrap-up "Machine learning" by Andrew Ng

I attended a online course, "Machine learning" by Andrew Ng that held in Coursera.org by Stanford Univ. Online.

I started this course to find more background theories about "Tensorflow".

However, it makes me be more interested in "Machine learning" and more curious about "Deep learning".



# Some impressive things in the course

- The professor explains the detailed algorithms with many examples.

   If I didn't understood an algorithm, I just waited and kept seeing the examples. The examples helped me understand.

- He explains the mathematical approaches of the algorithms.

   So I had to stop the video and tried to the mathematical approaches by myself.

   It took more times than I planned.

- The exercises are so difficult to make vectorized codes.

   But I think it is the most important point to imagine inner algorithms of "Tensorflow".

   I needed to practice matrix calculations in Octave to imagine vectorized codes.

- He knows the machine learning algorithm and system are difficult to understand and he said he also had felt them difficult when he learn.

   This words encouraged me.



# Wrap-up

1. Supervised Learning

    a. Linear regression

    b. Logistic regression

    c. Neural networks

    d. SVMs(Support Vector Machine)


2. Unsupervised Learning

    a. K-means

    b. PCA(Principle Component Analysis)

    c. Anomaly detection


3. Special applications / special topics

    a. Recommender systems

    b. Large scale machine learning


4. Advice on building a machine learning system

    a. Bias / Variance

    b. Regularization

    c. Deciding what to work on next

        - Evaluation of learning algoritms

        - Learning curves

        - Error analysis

        - Ceiling analysis

'Machine Learning' 카테고리의 다른 글

YOLO v3 demo webcam 돌려보기 for ubuntu(18.04)  (0) 2018.10.03
Activation functions  (0) 2017.11.30
Binomial Logistic Regression/Classification  (0) 2017.07.10
Linear Regression  (0) 2017.07.07

"시즌 1 - 딥러닝의 기본" Wrap-up

학습을 마치며 전반적 수업내용에 대한 정리를 해본다.

이 강의을 들으면서 더 깊이있는 지식이 필요하여 Coursera의 "Machine Learning" - Andrew Ng 강의을 들었고 더 잘 이해할 수 있었다.

하지만 딥러닝부분에서는 배경지식이 없어서 CNN, RNN등 에 대한 깊이있는 공부를 위해서 다른 강의를 수강해야 할 것 같다.



몇가지 인상깊은 특징을 나열해보자면

- 이 강의는 15분 내외의 짧은 동영상 강의로 되어있고

- 머신러닝이나 딥러닝의  개념설명과 TensorFlow로 구현하는 방법을 알려준다.

- 하지만 머신러닝이 빠진 타이틀에서 유추할 수 있듯이 딥러닝에 초점이 되어있다.

- TensorFlow가 많은 기능들을 지원하다보니 이론적인 이해가 덜 되어도 실습에는 무리가 없다.

- 이론적인 부분에 있어서는 생략되는 부분이 있다보니 후반부로 갈 수록 왜 그렇게 생각하고 나아가는지에 대한 공감이 어려웠다.



# Wrap-up

1. Machine learning

    a. Supervised

    b. Unsupervised


2. Linear regression

    a. hypothesis

    b. cost function

    c. Minimize cost

        - Gradient descent Algorithm

        - Convex function이 되어야 한다.

    d. Multivariable


3. Logistic regression/classification

    a. Sigmoid

    b. cost function

    c. Minimize cost

    d. Multinomial classification

    e. Softmax

    f. One-hot encoding

    g. Cross-Entropy


4. 머신러닝 관련 용어정리와 tip

    a. learning late

        - 너무 크면 Overshooting 경향

        - 너무 작으면 local minimum 경향

    b. Standardization

    c. Overfitting

    d. Regularization

    e. training / validation / test set

    f. MNIST dataset


5. Neural Networks

    a. Neural net and Activation function

    b. XOR problem

    c. forward propagation

    d. back propagation

        - 초기화를 잘 해야된다.(ex - RBM: Restricted Boatman Machine)

        - vanishing gradient problem: ReLU로 해결

    e. ReLU(Rectified Linear Unit)

        - 다른함수:  Sigmoid, Leaky ReLU, tanh, Maxout, ELU

    f. dropout

    e. ensemble


6. CNN(Convolutional Neural Networks)

    c. Convolution Layer

        - filter

        - stride

    d. Pooling Layer

        - Max pooling


7. RNN(Recurrent Neural Networks)

    a. sequence data

    b. hidden size

    c. batch size



Reference:

- http://hunkim.github.io/ml/

Binomial Logistic Regression/Classification


           X1, X2, ..., Xn

+ Linear Regression

+                Sigmoid

-------------------------

=>                  0 or 1


Logistic Classification에서 왜 Linear Regression + sigmoid를 쓰는지를 제가 이해하는 개념대로 설명합니다.

다른 이론과 차이가 있다면 아마도 그 이론이 맞고 제 이해는 틀릴 가능성이 높습니다.

이상한 점이 있다면 보충하거나 수정하겠습니다.


1. Binomial Logistic Classification을 한다는 것

classification을 한다는 것은 어떤 data들을 A group, B group, C group, ... N group으로 분류를 하는 것인데

Binomial Logistic은 이를 단순하게 모든 것은 A group, B group 으로만 분류된다고 한정하여 집중한다.

이분법적, 흑백논리.. 그런 개념이므로 Not A group == B group으로 볼수도 있고 0, 1 / True, False라는 개념으로도 이해할 수 있다.




Classification                  

Binomial Classification



2. A gourp, B group을 0, 1로 각각 생각한다.

x_data = [-3, -2, -1, 1, 2, 3]

y_data = [1, 1, 1, 0, 0, 0]

이러한 data가 있고 이를 그래프로 표현하려고 하면 X-Y 축를 그려야 한다.


    





3. Sigmoid 함수를 사용하는 이유 => 0, 1로 표현하기 위해

위의 데이터를 통해서 Y를 예측하는 그래프를 그린다면 0, 1로 결과가 나올 수 있는 Linear regression + sigmoid 함수를 이용해서 다음과 같이 추정 그래프를 그릴 수 있다.



# 빨간색 : Linear regression + sigmoid 함수 적용 예측값

# 파란색 : Linear regression 함수의 예측값 


빨간색 그래프는 X축 [-1, 1] 사이를 기준으로 실제값과 유사한(예측가능한) 그래프를 그려준다.

파란색 선의 의미는 어떤 접점을 기준으로 나누고 있지만 그 의미가 분명하지 않다.

하지만 파란색이 Y축 1에 가까운지 0에 가까운지 라는 조건으로 바라본다면 그 그래프는 빨간색과 같을 것이다.

이것이 sigmoid를 가설에 포함하여 사용하는 이유이다.

즉, sigmoid를 통해서 Y축 0과 1로 (그래서 결론은 A Group에 속합니다./ 속하지 않습니다.)예측의 결론을 낼 수 있다.



4. Linear Regression 방식을 사용하는 이유 => 다른것 써도된다. 관계가 Linear하다고 가정하는 접근이였다.

여기까지 왔다면 sigmoid에 의해 어차피 0, 1 두가지로 나누어 지는데 굳이 Linear Regression 방식이 필요한 것인가 생각이 들 것이다.

(X끼리 더하든 곱셈을 하거나 하는 그런 관계도 있을 수 있겠는데 말이다.)

그 이유는 X1, X2 두가지 변수에 대한 예측을 할때를 살펴보면 이해가 된다.


x_data = [[1, 2], [2, 3], [3, 1], [4, 3], [5, 3], [6, 2]]

y_data = [[0], [0], [0], [1], [1], [1]]


의 data가 있을때

우선 X1과 X2의 관계 그리고 Y값 표시를 그려보자.


우리는 Y의 데이터가 검정과 빨강을 구분하는 기준이 된다는 것을 알았고 이제 Y를 예측하는 값을 그래프로 나타내면

알아보기 힘들지만 여러번의 학습을 거쳐 전반적으로 실제Y값과 추정값이 비슷한 위치로 가고 있다고 보여진다.

100 times trained

 ==>10000 times trained

시각적으로 평면 X, Y축에서 A와 B 그룹을 나눠주는 선을 긋는 것이 이해하기 쉬우므로 X1, X2에 대한 관계에 이를 표현해보자.



관계를 sigmoid 함수 0, 1일 때의 방정식으로 구하기에는 어려운 점이 있어서



Linear Regression 공식으로 구해본다.

1) Y=0 일때


2) Y=1 일때


이러한 관계식을 X1 - X2  그래프에 표시하면 다음과 같다.

1000 times trained 

10000 times trained


파란색이 학습된 경계선이며 학습을 조금 시켰을때는 검정색과 빨간색의 그 경계선이 모호했지만

학습을 많이 함에 따라서 구분짓는 경계선이 얇아지고 더 분명하게 되었다.

(기울기는 Random값에서 출발하여 다를 수 있다.)


Linear Regression 방법을 유지하는 이유는

- Gradient Descent로 cost를 계산할 수 있고

- 이처럼 관계를 계산하거나 구분하는 선을 그리는데 장점이 있다고 생각한다.



Reference:

- http://hunkim.github.io/ml/


'Machine Learning' 카테고리의 다른 글

YOLO v3 demo webcam 돌려보기 for ubuntu(18.04)  (0) 2018.10.03
Activation functions  (0) 2017.11.30
Wrap-up "Machine learning" by Andrew Ng  (0) 2017.10.13
Linear Regression  (0) 2017.07.07

Linear Regression



1. Linear한 관계(1차 방정식=직선)일 것이라고 가정하고 기계적으로 귀납적 추론을 하게 하는 방법

- X -> Y로 변화하는 관계에 대해서

 

 라는 가설을 세워 접근하는 것이다.

 물론 1차방정식을 알고 있다면 W는 기울기이고 b는 이 그래프의 수직이동 관계이다.


- X가 여러개라도

 라는 관계가 성립한다고 보는것



2. 기계적으로 귀납적 추론을 하게 하는 방법

- X, Y 자료가 있고 가설의 그래프(1차 방정식 그래프 = 직선)를 그렸을때 가설과 실제값의 차이를 보인다면

  그 차이를 최소화 할 수 있는 그래프를 찾도록 하는 것이다.

- 여기서 최소값을 찾는다는 것은 그래프의 기울기 W와 그래프의 수직이동 b 의 값을 적절히 하게 하여

  가설이 실제값에 가장 유사한 조건이 되도록 하는 것이다.



3. 최적의 조건을 찾게 하는 방법

- 가설과 실제값의 차의 제곱의 평균을 한 것을 cost 함수라고 정의하고 이 값을 최저로 만든다.

  

- 이 cost 공식을 쓸때 cost의 추이는 다음과 아래와 유사한 2차 방정식 곡선을 그리며

  0에 가장 가까운 지점을 찾아가게 되는데

  이 때 경사도를 구하여 0에 가까운 지점을 찾아가는 방법을 Gradient Descent Algorithm이라고 한다.


Reference:

- http://hunkim.github.io/ml/

- https://ko.wikipedia.org/wiki/%EC%84%A0%ED%98%95_%ED%9A%8C%EA%B7%80

  

   

TensorFlow 예제 따라하기(lab 3)


Linear Regression: H(x) = Wx + b 계속...


1. W에 따른 cost의 추이를 그래프로 표현하기

# TensorFlow 불러오기

import tensorflow as tf


# Matplotlib 불러오기

import matplotlib

Matplotlib backend 설정

matplotlib.use('TkAgg')

import matplotlib.pyplot as plt


X = [1, 2, 3]

Y = [1, 2, 3]


W = tf.placeholder(tf.float32)


# H(x) = Wx

hypothesis = X * W


# Cost: 1/m * ∑(H(x) - y)^2

cost = tf.reduce_mean(tf.square(hypothesis - Y))


# Session 생성

sess = tf.Session()


# Global variable 초기화

sess.run(tf.global_variables_initializer())

W_val = []

cost_val = []


# -3 ~ 5 까지 W(기울기)를 0.1씩 바꿔보면서 W에 따른 cost 값을 구한다

for i in range(-30, 50):

    feed_W = i * 0.1

    curr_cost, curr_W = sess.run([cost, W], feed_dict={W: feed_W})

    W_val.append(curr_W)

    cost_val.append(curr_cost)


# matplotlib으로 표현하기

plt.plot(W_val, cost_val)

plt.show()

- 결과:


2. GradientDescentOptimizer를 직접 구현하기

  Before


  # Gradient Descent Magic

 optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)

 train = optimizer.minimize(cost)


  After

# Gradient Descent 구현

# 한번 학습을 반영하는 비율
learning_rate = 0.1

# Cost의 미분(cost의 기울기)
gradient = tf.reduce_mean((W * X - Y) * X)

# 학습된 W(linear 함수의 기울기)를 반영
descent = W - learning_rate * gradient
train = W.assign(descent)




3. W값을 지정하여 학습시키기

 Before


 # W 초기 랜덤값 적용

 W = tf.Variable(tf.random_normal([1]), name="weight") 


 After


 # W 초기값을 지정하여 수행


 # W = tf.Variable(5.0)

 W = tf.Variable(-3.0)




4. Gradient 값 수정하기

 Before


  # Gradient Descent Magic

 optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)

 train = optimizer.minimize(cost)


 After

 # Gradient 계산값 구하여 수동 적용


 gvs = optimizer.compute_gradients(cost)

 # TODO: gvs 수정

 train = optimizer.apply_gradients(gvs)




# gradient를 계산한 값 구해서 적용하기(compute_gradient, apply_gradient)

# Loading TensorFlow
import tensorflow as tf

x_data = [1, 2, 3]
y_data = [1, 2, 3]

# W = tf.Variable(5.0)
W = tf.Variable(-3.0)
X = tf.placeholder(tf.float32)
Y = tf.placeholder(tf.float32)

# H(x) = Wx
hypothesis = X * W

# Cost: 1/m * ∑(H(x) - y)^2
cost = tf.reduce_mean(tf.square(hypothesis - Y))
gradient = tf.reduce_mean(((W * X - Y) * X) * 2)

# Gradient Descent Magic
optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.1)

# Gradient 계산값 구하여 수동 적용
# train = optimizer.minimize(cost)
gvs = optimizer.compute_gradients(cost)
# TODO: gvs 수정
train = optimizer.apply_gradients(gvs)

# Session 생성
sess = tf.Session()

# Global variable 초기화
sess.run(tf.global_variables_initializer())

for step in range(10):
print(step, sess.run([gradient, W, gvs], feed_dict={X: x_data, Y: y_data}))
sess.run(train, feed_dict={X: x_data, Y: y_data})

'''
Result
0 [-37.333332, -3.0, [(-37.333336, -3.0)]]
1 [-2.4888866, 0.73333359, [(-2.4888866, 0.73333359)]]
2 [-0.1659257, 0.98222226, [(-0.16592571, 0.98222226)]]
3 [-0.011061668, 0.99881482, [(-0.011061668, 0.99881482)]]
4 [-0.00073742867, 0.99992096, [(-0.00073742867, 0.99992096)]]
5 [-4.9630802e-05, 0.9999947, [(-4.9630802e-05, 0.9999947)]]
6 [-3.0994415e-06, 0.99999964, [(-3.0994415e-06, 0.99999964)]]
7 [-6.7551929e-07, 0.99999994, [(-6.7551935e-07, 0.99999994)]]
8 [0.0, 1.0, [(0.0, 1.0)]]
9 [0.0, 1.0, [(0.0, 1.0)]]
'''



# 여기의 모든 소스는 github에... -> https://github.com/ndukwon/learning_TensorFlow



Reference

- https://www.youtube.com/watch?v=Y0EF9VqRuEA&feature=youtu.be

'Machine Learning > TensorFlow' 카테고리의 다른 글

TensorFlow 예제 따라하기(lab 1 ~ 2)  (0) 2017.06.12
TensorFlow의 시작과 설치  (0) 2017.06.07

TensorFlow 예제 따라하기


1. TensorFlow 실행 및 버전 체크

# virtualenv에서 Python3 실행

$ source ~tf_py_3/bin/activate

(tf_py_3) $ python

Python 3.6.0 (v3.6.0:41df79263a11, Dec 22 2016, 17:23:13) 

[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin

Type "help", "copyright", "credits" or "license" for more information.

>>> 


# TensorFlow 실행

>>> import tensorflow as tf


# Version 확인

>>> tf.__version__

'1.1.0'

>>>



2. TensorFlow로 "Hello TensorFlow!" 찍기

# 상수의  Default node 선언

>>> hellotensorflow = tf.constant("Hello TensorFlow!")


# Session을 생성

>>> sess = tf.Session()


# Python Print 명령으로 출력

>>> print(sess.run(hellotensorflow))

b'Hello, TensorFlow'


# Session 닫기

>>> sess.close()

- Session을 여는 이유: Session은 계산(Operation) / 평가(Evaluate)을 할 수 있는 객체이다.

- b 라는 문자가 찍히는 이유: Byte 문자형이라는 표현임



3. TensorFlow로 3.0 + 4.0 계산해보기(이후 Pycharm  editor 사용)

node1 = tf.constant(3.0, tf.float32)

node2 = tf.constant(4.0) # 암시적으로 tf.float32으로 설정된다

node3 = tf.add(node1, node2)


# Tensor 객체의 정보를 찍는다.

print("node1=", node1, "node2=", node2)

print("node3=", node3)

# node1= Tensor("Const_1:0", shape=(), dtype=float32) node2= Tensor("Const_2:0", shape=(), dtype=float32)

# node3= Tensor("Add:0", shape=(), dtype=float32)


sess = tf.Session()

print("sess.run([node1, node2])=", sess.run([node1, node2]))

print("sess.run(node3)=", sess.run(node3))

sess.close()

# sess.run([node1, node2])= [3.0, 4.0]

# sess.run(node3)= 7.0



4. 3번을 실행시 값 대입하도록 변경

a = tf.placeholder(tf.float32)

b = tf.placeholder(tf.float32)

adder_node = a + b # tf.add(a, b) 와 같다


sess = tf.Session()

print(sess.run(adder_node, feed_dict={a: 3, b: 4.5}))

print(sess.run(adder_node, feed_dict={a: [1, 3], b: [2, 4]}))

sess.close()

# 7.5

# [ 3. 7.]



5. Linear Regression: H(x) = Wx + b

# TensorFlow 실행

import tensorflow as tf


# train 값 사전 정의

x_train = [1, 2, 3]

y_train = [1, 2, 3]


# 가설: H(x) = Wx + b

W = tf.Variable(tf.random_normal([1]), name='weight')

b = tf.Variable(tf.random_normal([1]), name='bias')

hypothesis = x_train * W + b


# Cost: 1/m * H(x)

cost = tf.reduce_mean(tf.square(hypothesis - y_train))

optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)

train = optimizer.minimize(cost)


sess = tf.Session()

sess.run(tf.global_variables_initializer())


for step in range(2001):

    sess.run(train)

    if step % 20 == 0:

        print(step, sess.run(cost), sess.run(W), sess.run(b))



6. 5번의 학습 데이터를 실행시 대입하도록 변경

# TensorFlow 실행

import tensorflow as tf


# train 할 값 나중에 정의

# shape=[None] : 여러개가 될 수 도 있다.

X = tf.placeholder(tf.float32, shape=[None])

Y = tf.placeholder(tf.float32, shape=[None])


# 가설: H(x) = Wx + b

W = tf.Variable(tf.random_normal([1]), name='weight')

b = tf.Variable(tf.random_normal([1]), name='bias')

hypothesis = X * W + b


# Cost: 1/m * H(x)

cost = tf.reduce_mean(tf.square(hypothesis - Y))


optimizer = tf.train.GradientDescentOptimizer(learning_rate=0.01)

train = optimizer.minimize(cost)


sess = tf.Session()

sess.run(tf.global_variables_initializer())


for step in range(2001):

    cost_val, W_val, b_val, _ = sess.run([cost, W, b, train], feed_dict={X: [1, 2, 3], Y: [1, 2, 3]})

    if step % 20 == 0:

        print(step, cost_val, W_val, b_val)



# 여기의 모든 소스는 github에... -> https://github.com/ndukwon/learning_TensorFlow



Reference

- https://www.youtube.com/watch?v=-57Ne86Ia8w&feature=youtu.be

- https://www.youtube.com/watch?v=mQGwjrStQgg&feature=youtu.be

- https://www.tensorflow.org/api_docs/python/tf/Session

'Machine Learning > TensorFlow' 카테고리의 다른 글

TensorFlow 예제 따라하기(lab 3)  (0) 2017.06.20
TensorFlow의 시작과 설치  (0) 2017.06.07

TensorFlow의 시작과 설치


1. TensorFlow란 무엇인가

- 머신러닝 라이브러리(오픈소스)

- 공식사이트: https://www.tensorflow.org/


2. TensorFlow를 위해 알아두어야 할 것

- TensorFlow는 CPU / GPU 버전 두개가 있고 말 그대로 CPU / GPU를 사용하는데 GPU는 NVIDIA CUDA GPU만 가능하다.

- Python을 독립적으로 동작시킬 가상화 Container 설치

- 가상화 환경에 Python 설치

- 가상화 환경에 TensorFlow 설치


2-1. 가상화(독립) 환경 설치(Mac OS 기준)

- 이유: Python은 R언어와 유사하게 라이브러리를 설치하고 로드한다고 한다. 이렇게 설치되고 로드된 라이브러리들이 서로 영향을 끼칠 수 있다고 하니 분리해야 한다.

- TensorFlow에서 지원하는 가상화 수단:

  1) virtualenv: TensorFlow에서 추천하는 수단. Python의 공식 가상화 Container이다.

  2) "native" pip: pip="Python Package Index" 라는 뜻이고 Mac에는 기본적으로 Python이 설치되어 있다. 이를 native라고 칭하고 있으며 이를 바로 사용한다면 가상화 환경을 설치하는 의미가 없겠다.

  3) Docker: virtualenv와 유사하지만 TensorFlow 가 완전히 설치된 이미지를 설치해야 해서 용량이 크고 mac에서는 CPU 버전 이미지만 있는 단점이 있다.

  4) Anaconda: 커뮤니티 버전은 있으나 공식적인 지원은 하지 않고 있다.



이 정도만 알면 이제 공식사이트를 읽으며 설치를 해도 무리가 없을 것이니 따라서 설치해보자.



필자는 2-1에서 mac 의 환경이고 virtualenv를 선택했다.


2-1. virtualenv 설치

$ sudo easy_install pip
$ sudo pip install --upgrade


2-2. 가상화 환경에 Python 설치

// Python 2.7

$ virtualenv --system-site-packages tf_py_2.7

$ source ~/tf_py_2.7/bin/activate

(tf_py_2.7) $


// Python 3.x

$ virtualenv --system-site-packages -p python3 tf_py_3

$ source ~/tf_py_3/bin/activate

(tf_py_3) $

- virtualenv의 방식은 원하는 Python 가상화 환경을 가져오는 것이고 tf_py_2.7 / tf_py_3 는 폴더명이다.

  폴더 안에서 관리된다고 보면 되고 폴더를 삭제하는것도 이 환경을 삭제하는 방법이다.

- 가상화tool을 이용하는 것은 명령어 앞에 접두어 virtualenv가 온다고 보면 되며 실행하는동안 앞에 폴더명이 나온다.


2-3. 가상화 환경에 TensorFlow 설치

// Python 2.7

(tf_py_2.7) $ pip install --upgrade tensorflow


// Python 3.x

(tf_py_3) $ pip3 install --upgrade tensorflow


 끝.



Reference

- https://www.tensorflow.org/install/install_mac

- http://hunkim.github.io/ml/

'Machine Learning > TensorFlow' 카테고리의 다른 글

TensorFlow 예제 따라하기(lab 3)  (0) 2017.06.20
TensorFlow 예제 따라하기(lab 1 ~ 2)  (0) 2017.06.12

+ Recent posts