python - 如何获取特定名称范围下的 tensorflow 变量?

标签 python tensorflow

假设我们想要获取 tensorflow 变量的值,我们可以在 session 下运行它。

假设a = tf.Variable(...)

然后可以使用sess.run(a)获取它的值

但是如果有两个名称相同但名称范围不同的变量,如何获取各个变量的值?

with tf.name_scope("x"):
      a = tf.Variable(...)
with tf.name_scope("y"):
      a = tf.Variable(...)

那么如何分别获取x下的ay下的a的值呢? 如果我执行 sess.run(a),我将在 name_scope y (最近的一个)下获得值

最佳答案

您可以查看变量的名称并通过范围/名称获取它们:

with tf.variable_scope("x"):
    a = tf.get_variable('a', initializer=1)

with tf.variable_scope("y"):
    a = tf.get_variable('a', initializer=2)

with tf.Session() as s:
    s.run(tf.global_variables_initializer())
    [print(var.op.name) for var in tf.global_variables()]
    res = s.run(['x/a:0', 'y/a:0'])
    print(res)

返回:

x/a
y/a
[1, 2]

关于python - 如何获取特定名称范围下的 tensorflow 变量?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48119449/

相关文章:

python - 为什么分布式 TensorFlow 玩具示例需要太长时间?

python - 在 Python 中计算具有特定值的图像的每个像素的有效方法?

python - mysql-python 停止工作

tensorflow - 在多类分类上从 tensorflow 2.3.1 降级到 tensorflow 1.14 或 1.15 时,由于过度拟合而导致精度性能下降

python - 具有稀疏数据的 tensorflow 训练

python - 卸载 Ubuntu 18.04 中具有多个 python 版本的所有 Python 包

python - 如果用户没有用户名或其他内容,返回给 django admin 的内容

python - 带有表单的 django ListView

Python:引用内部生成列表的列表理解

tensorflow - TensowFlow GradientDescentOptimizer 在这个例子中做了什么?