此彼之间白夜幻想 2022-04-25 11:48 采纳率: 100%
浏览 134
已结题

TensorFlow2.8 tf.compat.v1.get_variable没有重用已经创建的变量

问题遇到的现象和发生背景

tf.compat.v1.get_variable没有重用已经创建的变量,而是将已经创建的变量进行数值更新。

问题相关代码,请勿粘贴截图

def foo():
with tf.compat.v1.variable_scope("foo", reuse=tf.compat.v1.AUTO_REUSE):
v = tf.compat.v1.get_variable("v", [1])
return v

v1 = foo() # Creates v.
v2 = foo() # Gets the same, existing v.
assert v1 == v2


运行结果及报错内容
---------------------------------------------------------------------------
AssertionError                            Traceback (most recent call last)
D:\Temp/ipykernel_12096/3386910621.py in <module>
      6 v1 = foo()  # Creates v.
      7 v2 = foo()  # Gets the same, existing v.
----> 8 assert v1 == v2

AssertionError: 


我的解答思路和尝试过的方法

查看了v1,与,v2的数据后发现
<tf.Variable 'foo/v:0' shape=(1,) dtype=float32, numpy=array([-1.6809169], dtype=float32)>
<tf.Variable 'foo/v:0' shape=(1,) dtype=float32, numpy=array([-0.75641733], dtype=float32)>
两者之间只是数据发生了变化

我想要达到的结果

希望assert 函数不会报错

  • 写回答

1条回答 默认 最新

  • 不会长胖的斜杠 新星创作者: 后端开发技术领域 2022-04-25 11:59
    关注

    assert v1 is v2
    你可以改成这样

    本回答被专家选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

问题事件

  • 系统已结题 5月22日
  • 专家已采纳回答 5月14日
  • 修改了问题 4月25日
  • 创建了问题 4月25日