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

1.报错代码:

import tensorflow as tf

#实现一个加法运算运算
a = tf.constant(1.0)
b = tf.constant(1.0)
sum1 = tf.add(a,b)

with tf.Session() as sess:
    print(sess.run(sum1))#2.0

2.运行报错:

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

3.报错原因:

用的是tensorflow 2.0 及以上版本

 

查看tensorflow1.12+ 和 2.0之间的函数对照表,发现版本之间还是有很大区别的

  

4. 解决方法:

方法一:

    将原来的tf.Session()修改为

tf.compat.v1.Session()

方法二:

其他代码都不动,导包时修改为:

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

5.附上tensorflow 1.12+ 和 tensorflow 2.0 之间的函数区别

https://docs.google.com/spreadsheets/d/1FLFJLzg7WNP6JHODX5q8BDgptKafq_slHpnHVbJIteQ/edit#gid=0 

发布了128 篇原创文章 · 获赞 95 · 访问量 35万+

猜你喜欢

转载自blog.csdn.net/qq_36853469/article/details/103625263