tf.compat.v1.variable_scope 报错,如何解决?

问题: tf.compat.v1.variable_scope 报错 module 'tensorflow' has no attribute 'variable_scope'

毕设卡住了qwq
源代码是tensorflow1的,但是Google cola只能用2,把源代码“tf.variable_scope”改成“tf.compat.v1.variable_scope”还是报错

img

import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
需要屏蔽掉v2版本方法,不知道你添加了没。

引用自tensorflow2报错AttributeError: module ‘tensorflow‘ has no attribute ‘variable_scope‘

不知道你这个问题是否已经解决, 如果还没有解决的话:
  • 这篇博客: tensorflow 变量及命名空间 tf.Variable() vs tf.get_variable() & tf.name_scope() vs tf.variable_scope()中的 1.4 tf.variable_scope() 部分也许能够解决你的问题, 你可以仔细阅读以下内容或者直接跳转源博客中阅读:
    def __init__(
        self,
        name_or_scope: Any,
        default_name: Any = None,
        values: Any = None,
        initializer: Any = None,
        regularizer: Any = None,
        caching_device: Any = None,
        partitioner: Any = None,
        custom_getter: Any = None,
        reuse: Any = None,
        dtype: Any = None,
        use_resource: Any = None,
        constraint: Any = None,
        auxiliary_name_scope: bool = True
    ) -> Any
    

    初始化上下文管理器。
    Params:

    • name_or_scopestring or VariableScope: 要打开的 scope;
    • default_name – 如果参数 name_or_scopeNone, 则启用默认名;
    • values – 要传递给 op 函数的张量参数列表(不清楚);
    • reuseTrue, None, or tf.AUTO_REUSE
      • 如果为 True,该 scope 及其 sub-scope(reuse=None)开启 reuse 模式,get_variable(name='v') 将获取已有的 name == v 的变量;
      • 如果为 tf.AUTO_REUSEget_variable(name='v') 创建新变量 if v 不存在 esle 获取已有变量 v
      • 如果为 None,则继承其 parent-scope 的 reuse flag;

    Returns:
    A scope that can be captured and reused. 可以作为参数传递给 tf.variable_scope()

    例子

    with tf.variable_scope('vs') as scope:
    	a = tf.get_variable(name='a', shape=[2, 3], initializer=tf.random_uniform_initializer(0.0, 1.0))
    print(a)  # <tf.Variable 'vs/a:0' shape=(2, 3) dtype=float32_ref>
    with tf.variable_scope(scope, reuse=True):  # 需要指明 reuse
    	b = tf.get_variable(name='a')
    print(a is b)  # True
    

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^