본문 바로가기
Tensorflow

9. Tensorflow 시작하기 - Session

by 대소니 2016. 10. 25.


Tensorflow에서 실제 실행되는 환경인 Session을 구성하는 다양한 방법이 있습니다.

이번에는 이러한 Session을 생성하는 것을 알아보겠습니다.


Session은 operation 객체를 실행하고, tensor 객체를 평가하기 위한 환경을 제공하는 객체입니다.



지금까지 다루었던 기본적인 Session은 tf.Session()을 이용해서 객체를 생성하고 사용하는 방법이였습니다.

그리고 모든 연산과 수행이 완료가 되면 close()를 이용해서 Session 객체를 닫아주어야 합니다.


import tensorflow as tf

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
z = tf.mul(x, y)

sess = tf.Session()
print(sess.run(z, feed_dict={x: [[3.,3.],[3.,3.]], y: [[5.,5.],[5.,5.]]}))

sess.close()



또 다른 방법으로는 with 구문을 사용하는 것입니다.

이 구문을 사용하면 session 객체를 close()를 명시하지 않아도 자동으로 구문이 완료되면 종료가 됩니다.


import tensorflow as tf

x = tf.placeholder(tf.float32, shape=(2, 2))
y = tf.placeholder(tf.float32, shape=(2, 2))
z = tf.mul(x, y)

with tf.Session() as sess:
print(sess.run(z, feed_dict={x: [[3., 3.], [3., 3.]], y: [[5., 5.], [5., 5.]]}))



다음은 with 구문을 사용해서 session 을 열고, device를 통해서 cpu 혹은 gpu를 사용할 수 있는 방법입니다.

저는 cpu만 가능한 환경이기에 gpu로 셋팅을 하면 장치를 찾지 못했다는 오류가 발생하게 됩니다.

import tensorflow as tf

with tf.Session() as sess:
with tf.device("/cpu:0"):
#with tf.device("/gpu:0"):
x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
z = tf.mul(x, y)
print(sess.run(z, feed_dict={x: [[3., 3.], [3., 3.]], y: [[5., 5.], [5., 5.]]}))



또 다른 방법은 InteractiveSession()을 사용해서 좀더 넓은 범위의 로직을 처리할 수 있습니다.

조금 다른 점은 run() 함수를 사용하는 것이 아니라 eval() 함수를 사용해야 합니다.


그리고 모든 session이 종료되는 시점에서 close()를 호출해서 세션을 닫아주어야 합니다.


import tensorflow as tf

sess = tf.InteractiveSession()

x = tf.placeholder(tf.float32)
y = tf.placeholder(tf.float32)
z = tf.mul(x, y)

print(z.eval(feed_dict={x: [[3., 3.], [3., 3.]], y: [[5., 5.], [5., 5.]] }))

sess.close()





댓글