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