건프의 소소한 개발이야기

[Python - Tensorflow] Tensorflow 시작하기 (2) 본문

개발 이야기/Machine Learning 이야기

[Python - Tensorflow] Tensorflow 시작하기 (2)

건강한프로그래머 2016. 6. 6. 17:39

안녕하세요, 건프입니다.


Python 언어 기반의 Macine Learning Platform 인 Tensorflow 를 공부하고 있었습니다.


전 포스팅에서는 상수선언과 변수선언, 랜덤 벡터 및 매트릭스 만드는 기본적인 방법과


Tensorflow 가 가지고 있는 Session() 의 존재 의미 등을 확인하였습니다.



이번에는 본격적으로 Linear Regression 방식을 이용한 예측함수 추출 구현에 앞서 알아야 할 몇가지를 짚어봅니다.


1. placeholder


1
2
3
4
5
6
7
8
import tensorflow as tf
 
x = tf.placeholder("float", [2, 3])
y = tf.ones([2, 3], "float")
result = tf.add(x, y)
 
with tf.Session() as sess:
    print sess.run(result, feed_dict={x:[[1,2,3], [4, 5,6]]})



보시면, tensor 를 만들때, 현재 무엇이 들어갈지는 모르겠는데, 이 만큼의 크기를 같는 매트릭스, 혹은 벡터가 있을 것이고, 계산을 하는 당시에 

feed_dict 를 넘겨주면서, 계산을 시키는 방법이라는 것을 알 수 있습니다.


선 공간만들기 -> 후 데이터 삽입


이것이 placeholder 입니다. 어떻게 활용되는지는 뒤에서 확인해 봅니다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import tensorflow as tf
 
# placeholder example #1
x = tf.placeholder("float", [2, 3])
y = tf.ones([2, 3], "float")
result = tf.add(x, y)
 
with tf.Session() as sess:
    print "placeholder example #1"
    print sess.run(result, feed_dict={x:[[1,2,3], [4, 5,6]]})
 
# placeholder example #2
 
x = tf.placeholder("float", [2,3])
y = tf.placeholder("float", [2,3])
result = tf.add(x,y)
 
with tf.Session() as sess:
    print "placeholder example #2"
    print sess.run(result, feed_dict={x:[[1,2,3], [4,5,6]], y:[[3,4,5], [6,7,8]]})





연산하는 tensor 모두 placeholder 로 공간을 확보한뒤, feed_dict 로 둘다 설정해 주는 방법은 위와 같습니다.


2. '*' operation (매트릭스 곱하기 연산)


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
import tensorflow as tf
import numpy as np
 
x = [1,2,3]
# case 1 : '*' operation on python
prod1 = 2*x
print "prod1", prod1
 
# case 2 : '*' operation on np.array()
prod2 = 2*np.array([1,2,3])
print "prod2", prod2
 
# case 3 : '*' operation on tensorflow
prod3 = tf.constant(2)*x + tf.constant(5)
with tf.Session() as sess:
    print "prod3", sess.run(prod3)



파이썬에서 그대로 곱하기 연산을 벡터에 적용하면, 위와 같이 그 크기를 클론하여 연장합니다.


만약 내부의 값들을 키우고 싶다면 numpy 의 array 함수를 이용하던가, tensor 에서 적용하면 됩니다.


이것이 tensorflow 를 하면서 numpy 를 필수적으로 사용하는 이유 중 하나입니다.



3. Matrix Mean (평균) 구하기


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
import tensorflow as tf
import numpy as np
 
np_array = np.array([[1,2], [3,4], [5,6]])
 
# mean operation using numpy
print "np.mean..."
print "rowwise mean :", np.mean(np_array,1)
print "columwise mean :", np.mean(np_array,0)
print "total mean : ", np.mean(np_array)
 
# mean operation using tensorflow
mean1 = tf.reduce_mean(np_array, 1)
mean2 = tf.reduce_mean(np_array, 0)
mean3 = tf.reduce_mean(np_array)
 
with tf.Session() as sess:
    print "tf.reduce_mean..."
    print "rowwise mean :", sess.run(mean1)
    print "columwise mean :", sess.run(mean2)
    print "total mean :", sess.run(mean3)
 
c = np.array([[1., 2], [3., 4], [5., 6]])
mean1 = tf.reduce_mean(c, 1)
mean2 = tf.reduce_mean(c, 0)
mean3 = tf.reduce_mean(c)
 
with tf.Session() as sess:
    print "float data operation.."
    print "rowwise mean :", sess.run(mean1)
    print "columwise mean :", sess.run(mean2)
    print "total mean :", sess.run(mean3)
 
c = [[1.,2], [3.,4], [5.,6]]
mean1 = tf.reduce_mean(c, 1)
mean2 = tf.reduce_mean(c, 0)
mean3 = tf.reduce_mean(c)
 
with tf.Session() as sess:
    print "no use np.array.."
    print "rowwise mean :", sess.run(mean1)
    print "columwise mean :", sess.run(mean2)
    print "total mean :", sess.run(mean3)



이 예제가 의미하는 바는, numpy 에서 제공하는 mean 함수의 기능과 인자는

tensorflow 에서 제공하는 평균함수 : reduce_mean 의 기능과 인자와 완벽하게 동일하다.


또한 reduce_mean 안의 인자로는 numpy 의 array 를 넘길 수 있으며

numpy 를 쓰지않고, 직접 [] 를 이용해서 만들어 계산했을 때와 계산 결과는 같다.


다만 int 연산 중에는 float 화를 자동으로 해주지 않기 때문에 ( python version 2.7.* 버전입니다.)

소수점 계산이 필요하다면, 값 중 하나를 강제로 3. 이런식으로 float 화 시켜주면 된다는 것 입니다.



자 그러면 이제 본격적인 Linear Regression 방식을 이용한 예측함수 추출을 시도해볼 차례입니다.


고맙습니다 :)