【error】最全tensorflow没有‘global_variables_initializer‘、‘Session‘、‘concrib’,2.0版本排错问题

这篇博客主要介绍了如何解决在升级到Tensorflow 2.0后遇到的几个常见错误,如全局变量初始化、Session、AdamOptimizer等问题。错误产生的原因是Tensorflow 2.0移除了一些旧特性。解决方案包括降级到1.14版本或者使用tf.compat.v1模块。此外,对于贡献包(contrib)的移除,建议使用tf.keras替代。同时,对于变量重用问题,需要设置默认图或者使用tf.reset_default_graph()。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

报错

  • 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()
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值