马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有账号?立即注册
×
AttributeError: module 'tensorflow' has no attribute 'variable_scope' 报错的原因是,tf.variable_scope 在 TensorFlow 2.x 中已经被移除,而它是 TensorFlow 1.x 的一种构建静态图的特性。在 TensorFlow 2.x 中,可以通过 tf.name_scope 或者直接使用函数和 Keras API 来替换。
办理方法(最推荐方法3)
方法 1:替换 tf.variable_scope 为 tf.name_scope
假如 variable_scope 仅用于组织变量命名(常见用法),可以直接替换为 tf.name_scope,比方:
原代码:
- with tf.variable_scope(scope):
- # your code
复制代码 修改后代码:
- with tf.name_scope(scope):
- # your code
复制代码 方法 2:使用 TensorFlow 2.x 风格的 Keras API
假如代码涉及创建模子层和变量,可以直接使用 tf.keras.layers 构建模子。比方:
原代码:
- with tf.variable_scope(scope):
- hidden_layer = tf.layers.dense(input_tensor, units=num_units, activation=tf.nn.relu)
复制代码 修改后代码:
- hidden_layer = tf.keras.layers.Dense(units=num_units, activation='relu', name=scope)(input_tensor)
复制代码 方法 3:降级到 TensorFlow 1.x (最推荐的方法,一般可以一次成功!!!)
假如不想对代码做大规模改动,可以选择降级到 TensorFlow 1.x 运行代码。以下是步调:
- 安装 TensorFlow 1.x:
- pip install tensorflow==1.15
复制代码 - 创建一个单独的 Python 环境(推荐),确保不会影响其他项目。
方法 4:通过兼容模式运行 TensorFlow 1.x 代码
TensorFlow 2.x 提供了 tf.compat.v1 模块,可以运行大部分 TensorFlow 1.x 的代码。必要在程序开头添加以下代码:
- import tensorflow.compat.v1 as tf
- tf.disable_v2_behavior()
复制代码 然后无需修改 variable_scope 代码即可运行。
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。
|