Skip to main content
 首页 » 编程设计

python之Tensorflow所有预测都是0

2025年05月04日26duanxz

我正在为 TensorFlow 运行以下代码,所有概率都是 NaN,所有预测都是 0。但是,准确性有效。我不知道如何调试它。感谢您提供任何帮助。

x = tf.placeholder("float", shape=[None, 22]) 
W = tf.Variable(tf.zeros([22, 5])) 
 
y = tf.nn.softmax(tf.matmul(x, W)) 
y_ = tf.placeholder(tf.float32, [None, 5]) 
 
cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1])) 
#cross_entropy = -tf.reduce_sum(tf_softmax_correct*tf.log(tf_softmax  + 1e-50)) 
train_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy) 
init = tf.initialize_all_variables() 
 
sess = tf.Session() 
sess.run(init) 
 
for i in range(100): 
    batch_xs, batch_ys = random.sample(allTrainingArray,100), random.sample(allTrainingSkillsArray,100) 
    sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys}) 
 
#test on itself 
correct_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1)) 
accuracy = tf.reduce_mean(tf.cast(correct_prediction, "float")) 
print "accuracy", sess.run(accuracy, feed_dict={x: batch_xs, y_: batch_ys}) 
 
probabilities = y 
print "probabilities", probabilities.eval(feed_dict={x: allTrainingArray}, session=sess) 
 
prediction=tf.argmax(y,1) 
print "predictions", prediction.eval(feed_dict={x: allTrainingArray}, session = sess) 

请您参考如下方法:

问题源于您代码中的这一行:

W = tf.Variable(tf.zeros([22, 5])) 

在定义神经网络时,将权重初始化为零是一个常见的错误。 This article解释其背后的原因(非常近似,所有神经元将具有相同的值,因此网络不会学习)。相反,您应该将权重初始化为小的随机数,典型的方案是使用 tf.truncated_normal()标准偏差与输入单元的数量成反比:

W = tf.Variable(tf.truncated_normal([22, 5], stddev=1./22.)) 

rrao's suggestions添加偏置项,并切换到数值更稳定的 tf.nn.softmax_cross_entropy_with_logits()损失函数的 op 也是个好主意,这些可能是获得合理准确度的必要步骤。