Skip to main content
 首页 » 编程设计

python之ValueError : Variable mlp-fc/weights does not exist, 或不是用 tf.get_variable() 创建的

2024年09月07日7EasonJim

我使用 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 但仍然出现相同的错误。

请您参考如下方法:

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

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

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

但是,如果您不想重用任何可变权重,您可以简单地从这两种方法中删除reuse= True,tf.contrib.layers .fully_connected 和 tf.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/了解有关重用的更多信息。

希望这对您有所帮助。