解决在kaggle等在线平台运行报错module ‘tensorflow’ has no attribute ‘InteractiveSession’
学习tensorflow,除了本地安装一个外,更喜欢去在线平台玩,特别是kaggle这种带有数据集的。看书仿照下面的例子,没想到运行出错了。
# 进入一个交互式 TensorFlow 会话.
import tensorflow as tf
sess = tf.InteractiveSession()
x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])
# 使用初始化器 initializer op 的 run() 方法初始化 'x'
x.initializer.run()
# 增加一个减法 sub op, 从 'x' 减去 'a'. 运行减法 op, 输出结果
sub = tf.subtract(x, a)
print(sub.eval())
运行报下面错误:
--------------------------------------------------------------------------- AttributeError Traceback (most recent call last) /tmp/ipykernel_33/152899263.py in <module>
2 import tensorflow as tf
3 ---->
4 sess = tf.InteractiveSession()
5 #tf.compat.v1.disable_eager_execution()
6 #sess = tf.compat.v1.InteractiveSession()
AttributeError: module 'tensorflow' has no attribute 'InteractiveSession'
由于版本问题,要用下面的语句替代
使用 sess = tf.compat.v1.InteractiveSession()
解决了这个问题,又出现新的问题:
AttributeError: ‘NoneType’ object has no attribute ‘run’ ,
这需要在sess之前添加tf.compat.v1.disable_eager_execution()
新的完整代码如下:
# 进入一个交互式 TensorFlow 会话.
import tensorflow as tf
tf.compat.v1.disable_eager_execution()
sess = tf.compat.v1.InteractiveSession()
x = tf.Variable([1.0, 2.0])
a = tf.constant([3.0, 3.0])
# 使用初始化器 initializer op 的 run() 方法初始化 'x'
x.initializer.run()
# 增加一个减法 sub op, 从 'x' 减去 'a'. 运行减法 op, 输出结果
sub = tf.subtract(x, a)
print(sub.eval())