machine-learning - 如何使预先存在的 tensorflow variable_scope应用于操作?

标签 machine-learning tensorflow deep-learning

以下内容按预期工作:

import tensorflow as tf
with tf.variable_scope('layer123'):
    v = tf.get_variable('v', [], initializer=tf.constant_initializer(3., tf.float32))
    w = v * 2

print(v.name)    # Prints layer123/v:0
print(w.name)    # Prints layer123/mul:0

但是,当我尝试以下操作时:

with tf.variable_scope('layer123'):
    v = tf.get_variable('v', [], initializer=tf.constant_initializer(3., tf.float32))

# There might be some code here (perhaps even a different function), but not necessarily

with tf.variable_scope('layer123'):
    w = v * 2

print(v.name)    # Prints layer123/v:0
print(w.name)    # Prints layer123_1/mul:0

此处,变量 w 位于自动命名为 layer123_1 的新 variable_scope 中。我该如何防止这种行为?正如预期的那样,在第二个 with 语句中设置 reuse=True 没有帮助。

我想要 w.name == 'layer123/mul:0',特别是当乘法运算没有在变量 v 之后立即定义(即不退出作用域)时 已定义。

谢谢!

最佳答案

您可以通过重用作用域对象来做到这一点。例如,

with tf.variable_scope('layer123') as scope:
    v = tf.get_variable('v', [], initializer=tf.constant_initializer(3., tf.float32))
with tf.variable_scope(scope):
    w = v * 2

有关详细信息,请参阅documentation on sharing variables .

关于machine-learning - 如何使预先存在的 tensorflow variable_scope应用于操作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41024383/

相关文章:

python - scikit-learn SelectPercentile TFIDF 数据特征缩减

python - TF-IDF 如何生成机器学习特征?和词袋有什么不同?

tensorflow - 检查 Tensorflow 是否在 GPU 上运行

python - ValueError : Error when checking input: expected conv2d_1_input to have shape (224, 224, 1) 但得到形状为 (224, 224, 8) 的数组

machine-learning - CNN 中部分连接卷积层

python - 如何在Jupyter Notebook中建立大数据量的机器学习模型?

statistics - 使用 PCA 降维后对数据进行聚类

python - 索引错误: too many indices for array

python - 内核大小不能大于实际输入大小

machine-learning - tensorflow 中embedding_rnn_seq2seq模型中的output_projection参数是什么?