问题产生的原因:无法执行sess.run()的原因是tensorflow版本不同导致的,tensorflow版本2.0无法兼容版本1.0.
原代码:
import tensorflow as tf
a = tf.convert_to_tensor([1,2,3])
b = tf.convert_to_tensor([2,3,4])
stack_ab = tf.stack([a,b])
a1 = tf.expand_dims(a,axis=0)
b1 = tf.expand_dims(b,axis=0)
concat_ab = tf.concat([a1,b1],axis=0)
with tf.Session() as sess:
print(sess.run(stack_ab))
print(sess.run(concat_ab))
报错:
AttributeError Traceback (most recent call last)
<ipython-input-1-e38456eff5e2> in <module>
9 concat_ab = tf.concat([a1,b1],axis=0)
10
---> 11 with tf.Session() as sess:
12 print(sess.run(stack_ab))
13 print(sess.run(concat_ab))
AttributeError: module 'tensorflow' has no attribute 'Session'
解决方法:
代码修改
(1)加入tf.compat.v1.disable_eager_execution() #保证sess.run()能够正常运行
(2)tf.Session() 改为tf.compat.v1.Session()#版本2.0的函数
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
a = tf.convert_to_tensor([1,2,3])
b = tf.convert_to_tensor([2,3,4])
stack_ab = tf.stack([a,b])
a1 = tf.expand_dims(a,axis=0)
b1 = tf.expand_dims(b,axis=0)
concat_ab = tf.concat([a1,b1],axis=0)
with tf.compat.v1.Session() as sess:
print(sess.run(stack_ab))
print(sess.run(concat_ab))
运行结果:
[[1 2 3]
[2 3 4]]
[[1 2 3]
[2 3 4]]