You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未使用tf.get_variable却报AttributeError的TensorFlow问题求助

问题

执行TensorFlow代码构建模板图时触发AttributeError: module 'tensorflow' has no attribute 'get_variable'错误,但报错行并未直接使用tf.get_variable函数。

执行代码:

# Build template graph.
with tf.compat.v1.variable_scope(self.scope, reuse=tf.compat.v1.AUTO_REUSE):
    assert tf.compat.v1.get_variable_scope().name == self.scope
    with absolute_name_scope(self.scope): # ignore surrounding name_scope
        with tf.control_dependencies(None): # ignore surrounding control_dependencies
            tf.compat.v1.disable_eager_execution()
            self.input_templates = [tf.compat.v1.placeholder(tf.float32, name=name) for name in self.input_names]
            out_expr = self._build_func(*self.input_templates, is_template_graph=True, **self.static_kwargs)

错误栈信息:

File "models/pggan_tf_official/tfutil.py", line 478, in _init_graph
    out_expr = self._build_func(*self.input_templates, is_template_graph=True, **self.static_kwargs)
  File "<string>", line 175, in G_paper
AttributeError: module 'tensorflow' has no attribute 'get_variable'

尝试删除tf.compat.v1.disable_eager_execution()后,又出现RuntimeError: tf.placeholder() is not compatible with eager execution.错误,需要解决方法。

解决方法
  • 问题根源在G_paper函数内部:它调用了tf.get_variable,但TensorFlow 2.x的原生tf命名空间已移除该API,需替换为tf.compat.v1.get_variable。
  • 调整tf.compat.v1.disable_eager_execution()的位置:必须把它移到脚本最开头(导入TensorFlow之后立即执行),不能放在图构建的代码块里——这个函数要在所有TensorFlow操作运行前调用才会生效。
  • 统一兼容层使用:检查G_paper里的所有代码,将所有TF1.x风格的API(比如变量定义、图操作)都替换为tf.compat.v1下的版本,确保整个Graph模式的代码链路一致。
  • 简化写法备选:如果代码大量依赖TF1.x语法,可以直接这样导入TensorFlow:
    import tensorflow.compat.v1 as tf
    tf.disable_eager_execution()
    
    后续代码里直接用tf即可调用TF1.x的API,不用每次加compat.v1前缀。

内容的提问来源于stack exchange,提问作者Zodiac

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 09:50:30