갈루아의 반서재

이하 실습에 사용된 교재는 다음과 같다. 

실전! 딥러닝
국내도서
저자 : 오타 미쯔히사,수도 코다이 ,쿠로사와 타쿠마 ,오다 다이스케 / 손민규역
출판 : 위키북스 2019.02.15
상세보기

 

아나콘다, 텐서플로, 케라스, 주피터 등읭 설치는 이미 완료된 것은 가정하고 진행한다. 딥러닝에 관심이 있다면, 이미 이에 대한 설치는 완료되었을 거라고 봐도 무방할 듯하다. 아니면 본 블로그에서 검색해도 관련해서 다룬 포스팅들이 있으니 참조한다.

 

주피터 노트북으로 실습을 할 예정이니 이를 위해 가상환경으로 들어가 주피터를 실행한다.

(quintic) fossa@fossa:~$ jupyter lab --no-browser --port=8888 --ip=0.0.0.0

웹브라우저에서 다음과 같이 입력하여 로컬에서 GCP 에 설치된 노트북을 구동한다. 

http://**.***.*.***:8888/lab

새로운 노트북을 생성한 후 실습에 앞서 먼저 tensorflow 가 설치되어 있는지 확인해보자. 2.x 버전이 설치되어 있음을 알 수 있다.

import tensorflow as tf
tf.__version__

'2.2.0'

 

교재 3.1 (p.52)에서 전달하고자하는 내용은 텐서플로의 계산 절차와 데이터 플로우 그래프에 대한 것이다. 텐서플로는 일단 어떤 계산을 할 것인지부터 정의한 후, 한꺼번에 계산을 하게 되는데, 이를 보여주기 위해 두 가지 예제를 들고 있다. 하지만 예제대로 실행을 하면 다음과 같은 에러가 발생한다.

import tensorflow as tf

a = tf.constant(1, name='a')
b = tf.constant(1, name='b')
c = a+b

with tf.Session() as sess:
    print(sess.run(c))
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-2-516c2dfc104a> in <module>
      5 c = a+b
      6 
----> 7 with tf.Session() as sess:
      8     print(sess.run(c))

AttributeError: module 'tensorflow' has no attribute 'Session'

교재의 텐서플로는 1.x 버전이며, 여기서 실습한 환경은 2.x 버전이기 때문이다. 아래 링크에서도 확인할 수 있듯이 2.x 환경에서 1.x 와 같이 실행하고 싶다면 다음과 같이 하면 된다.

stackoverflow.com/questions/55142951/tensorflow-2-0-attributeerror-module-tensorflow-has-no-attribute-session/55143329#55143329

 

Tensorflow 2.0 - AttributeError: module 'tensorflow' has no attribute 'Session'

When I am executing the command sess = tf.Session() in Tensorflow 2.0 environment, I am getting an error message as below: Traceback (most recent call last): File "", line 1,...

stackoverflow.com

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

a = tf.constant(1, name='a')
b = tf.constant(1, name='b')
c = a+b

with tf.Session() as sess:
    print(sess.run(c))
WARNING:tensorflow:From /home/fossa/anaconda3/envs/quintic/lib/python3.8/site-packages/tensorflow/python/compat/v2_compat.py:96: disable_resource_variables (from tensorflow.python.ops.variable_scope) is deprecated and will be removed in a future version.
Instructions for updating:
non-resource variables are not supported in the long term
2

아래와 같이 c 를 출력해보면 수치가 아닌 c 는 텐서(Tensor) 라는 형의 인스턴스임을 알 수 있듯이, 여기서 실제 계산을 수행하는 부분은 c = a+b 가 아니라 sess.run(c) 이다. 

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()

a = tf.constant(1, name='a') 
b = tf.constant(1, name='b') 
c = a+b 

print(c)

Tensor("add_1:0", shape=(), dtype=int32)

 

데이터 플로우 그래프란 데이터의 흐름을 그래프로 표현한 것으로, 여기서 그래프란 네트워크 그 자체라고 생각하면 된다.

 

상수 (a, b) 및 조작 (덧셈) -> 노드

각각의 관계 -> 엣지

 

데이터 플로우 그래프의 정의 표시를 통해 위의 내용을 확인해보자. 

graph = tf.get_default_graph()
print(graph.as_graph_def())

결과를 보면 a, b, 그리고 add 가 노드로 되어 있음을 알 수 있다.

node {
  name: "a"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 1
      }
    }
  }
}
node {
  name: "b"
  op: "Const"
  attr {
    key: "dtype"
    value {
      type: DT_INT32
    }
  }
  attr {
    key: "value"
    value {
      tensor {
        dtype: DT_INT32
        tensor_shape {
        }
        int_val: 1
      }
    }
  }
}
node {
  name: "add"
  op: "AddV2"
  input: "a"
  input: "b"
  attr {
    key: "T"
    value {
      type: DT_INT32
    }
  }
}
versions {
  producer: 175
}