【问题标题】:ValueError: Variable mlp-fc/weights does not exist, or was not created with tf.get_variable()ValueError: 变量 mlp-fc/weights 不存在,或者不是用 tf.get_variable() 创建的
【发布时间】:2018-08-28 19:38:03
【问题描述】:

我使用 TensorFlow 实现了具有一个隐藏层的多层感知器 (MLP),并在调用该函数时出现以下错误。任何帮助将不胜感激。

def MLP(x, option, dropout=1, prefix ='', num_outputs=1, reuse=None):
      weights = tf.random_uniform_initializer(-0.001, 0.001)
      biases = tf.constant_initializer(0.001, dtype=tf.float32)

      fc1 = tf.contrib.layers.fully_connected(tf.nn.dropout(x, keep_prob=dropout),
                       num_outputs=option.num_outputs, 
                       biases_initializer=biases,
                       weights_initializer = weights, 
                       activation_fn=tf.nn.relu, 
                       scope=prefix + 'fc', 
                       reuse=reuse)
      logits = tf.contrib.layers.linear(tf.nn.dropout(fc1, keep_prob=dropout),
                       num_outputs=num_outputs,
                       biases_initializer=biases,
                       weights_initializer = weights,
                       scope=prefix + 'l',
                       reuse=reuse)

return logits

logits = MLP(x, option, dropout=dp, prefix='mlp-', reuse=True)

ValueError:变量 mlp-fc/weights 不存在,或者不是使用 tf.get_variable() 创建的。您的意思是在 VarScope 中设置 reuse=tf.AUTO_REUSE 吗?

我尝试初始化权重并设置 weights_initializer 但仍然遇到同样的错误。

【问题讨论】:

    标签: python tensorflow neural-network


    【解决方案1】:

    该错误是因为您尝试重用名为 'mlp-fc/weights' 的权重,而该权重不存在。

    同样的错误也可能适用于您的 tf.contrib.layers.linear

    为了重用,您首先必须定义它们。

    但是,如果您不想重用任何可变权重,您可以简单地从 tf.contrib.layers 这两种方法中删除 reuse= True .fully_connectedtf.contrib.layers.linear

    编辑

    您可以使用类似于以下代码的内容。

    with tf.variable_scope("mlp-fc"):
        #add a new variable to the graph
        var=tf.get_variable("weights",shape)
    

    您可以关注本文至https://jasdeep06.github.io/posts/variable-sharing-in-tensorflow/,了解更多重用

    希望这会有所帮助。

    【讨论】:

    • 谢谢,Nipun。我尝试初始化权重并设置 weights_initializer 但仍然遇到相同的错误。你能帮忙定义它们吗?我想重复使用权重。
    猜你喜欢
    • 1970-01-01
    • 2017-08-28
    • 2018-05-26
    • 1970-01-01
    • 1970-01-01
    • 2019-04-02
    • 2018-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多