AI/Ai code Error

파이썬 텐서플로우 에러해결 :: AttributeError: module 'tensorflow' has no attribute 'Session' / RuntimeError: The Session graph is empty. Add operations to the graph before calling run().

s_y_130 2021. 4. 7. 15:55

모두를 위한 딥러닝 첫 강의부터 에러...;;

 

tensorflow부터 다시 공부하는 차원에서 강의 첫 코드를 작성했는데 에러 발생...

아래 코드를 실행하면 다음과 같은 오류가 발생함.

 

# Create a constant op
# This op is added as a node to the default graph
hello = tf.constant("Hello, TensorFlow!")
 
# seart a TF session
sess = tf.Session()
 
# run the op and set result
print(sess.run(hello))
cs

 

 

구글링 결과 tf.Sesstion()의 경우 tensorflow 버전 1.x.x 에서 사용하는 표현 방식...

(본인은 tensorflow version '2.4.1')

 

tensorflow 버전 확인 코드는 다음과 같다.

 

import tensorflow as tf
tf.__version__
cs

 

텐서플로우 버전 2.0.0에서는 Session을 정의하고 run 해주는 과정이 생략되었다.

그래서 굳이 print를 하고 싶으면 아래와 같이 진행하면 된다.

 

# Create a constant op
# This op is added as a node to the default graph
hello = tf.constant("Hello, TensorFlow!")
 
tf.print(hello)
cs

 

Hello, TensorFlow!

 

또 Session()을 사용하는 방법은 존재한다. 

tf.compat.v1.Session()를 사용하면 가능하긴 한다. 그래서 위의 코드에 적용을 해보니...

 

# Create a constant op
# This op is added as a node to the default graph
hello = tf.constant("Hello, TensorFlow!")
 
# seart a TF session
sess =  tf.compat.v1.Session() 
 
# run the op and set result
asd = sess.run(hello)
print(asd)
cs

 

다음과 같은 오류가 발생. 오류에 Add operation이라는 말이 있길래 다른 예제로 진행을 해봤다.

 

with tf.compat.v1.Session() as sess:
    h = tf.constant("Hello")
    w = tf.constant("World!")
    hw = h + w
    ans = sess.run(hw)
    print(ans)
cs
b'HelloWorld!'

 

또 다른 방법으로는 

 

tf.compat.v1.disable_eager_execution()

 

위 코드를 import 과정에서 미리 호출하고 하는 과정도 존재함.

 

정확한 이유는 나중에 좀 더 공부해보는 걸로....