【问题标题】:Tensorflow tf.get_variable() by indexTensorFlow tf.get_variable() 按索引
【发布时间】:2017-01-26 19:10:08
【问题描述】:

下午好。 我继续研究tensorflow,现在卡在重用变量“W”的问题上 这是代码 sn-p:http://pastebin.com/VZETt2ud

我想避免硬编码并从恢复的模型中获取值(而不是 10 - get_value() 等)。 我在这里阅读了几个线程,但在任何地方都只需要整个变量。但是,我不明白如何正确获取,例如,从这里获取 784 号:

W = tf.Variable(tf.zeros([784, 10]), name = "W")

我试过了:

idx = tf.constant([0])
temp_var = tf.get_variable("W") 
size_1 = tf.gather(temp_var, idx)

这种方法给了我这个错误: “必须完全定义新变量 (W) 的形状,但它是未知的。”

(再一次,我避免硬编码,不能写像[数字,数字]这样的形状)

我更改了变量的范围,认为它与范围有关,添加以下行:

with tf.variable_scope("my"):

with tf.variable_scope("my"):
tf.get_variable_scope().reuse_variables()

但是犯了这个错误: “ValueError:变量 my/W 不存在,或者不是使用 tf.get_variable() 创建的。您的意思是在 VarScope 中设置重用=None 吗?” 设置reuse=None后,我还是有同样的问题。

你会这么好心并建议我如何在这段代码中按索引获取值吗?

【问题讨论】:

    标签: python tensorflow neural-network data-science


    【解决方案1】:

    您也需要使用 get_variable 创建变量以进行首次访问。对于后面的你需要设置reuse=True。 像下面这样的东西应该可以工作:

    W = tf.get_variable("W", initializer=tf.zeros([784, 10], dtype=YOUR_DTYPE)
    ...
    temp_var = tf.get_variable("W", reuse=True)
    tf.gather(...)
    

    【讨论】:

    • 谢谢。不能简单地将reuse=True 添加到变量中:) 我将它添加到范围,这是代码:pastebin.com/8c24XatB 但现在我得到了错误 ValueError: Shapes must be equal rank, but are 2 and 1 From merging shape 0 with other形状。对于具有输入形状的“ones/shape”(操作:“Pack”):[1,10]、[10]。我知道这是因为我在 idx 方面的努力,但我什至没有丝毫改变通过索引获取数字 784 的操作而不破坏代码以匹配输入形状的操作。
    猜你喜欢
    • 2021-10-03
    • 2018-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-10
    • 2016-11-06
    • 2019-01-21
    相关资源
    最近更新 更多