报错
-
module ‘tensorflow’ has no attribute ‘global_variables_initializer’
-
AttributeError: module ‘tensorflow’ has no attribute ‘Session’
-
module ‘tensorflow_core._api.v2.train’ has no attribute ‘AdamOptimizer’
-
RuntimeError: The Session graph is empty. Add operations to the graph
before calling run() -
AttributeError: module ‘tensorflow’ has no attribute ‘contrib’
-
Variable W1 already exists, disallowed. Did you mean to set
reuse=True or reuse=tf.AUTO_REUSE in VarScope?
解释
由于版本问题,tensorflow的2.0版本砍掉了一些功能,两种方法解决
方法
方法一:换库
- 查看自己的tensorflow版本,打开终端窗口cmd,输入
python
回车
import tensorflow as tf
tf.__version__
- 卸载
pip uninstall tensorflow
- 安装
pip install tensorflow==1.14
如果换了还不管用,就在用下面的方法:
方法二:各种操作
- 针对报错:has no attribute ‘global_variables_initializer’…‘Session’…
将所有tf.global_variables_initializer()
、ts.Session()
改为:
tf.compat.v1.global_variables_initializer()
tf.compat.v1.Session()
tf.compat.v1.train.GradientDescentOptimizer
tf.compat.v1.train.AdamOptimizer
就是在tf和你要调用的库之间加上.compat.v1.
.
- 针对报错
The Session graph is empty. Add operations to the graph before calling run()
是因为使用了.compat.v1.
解决办法就是在使用调用.compat.v1.
的语句前加上下面语句(就是在代码调用tf库之后输入下面这一句,可以解决大多数问题)。
tf.compat.v1.disable_eager_execution()
- 针对AttributeError: module ‘tensorflow’ has no attribute ‘contrib’
tensorflow2.1中tf.contrib.layers.xavier_initializer()
将tf.contrib.layers.xavier_initializer()
替换为:
tf.keras.initializers.glorot_normal()
- 针对Variable W1 already exists, disallowed. Did you mean to set
reuse=True or reuse=tf.AUTO_REUSE in VarScope?
原因:运行两次就会报这样的错误
解决:在运行前加上一句(如果版本是2.0以上用tf.reset_default_graph()
)
tf.compat.v1.reset_default_graph()