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

+ Recent posts