【问题标题】:Tensor Flow all predictions are 0TensorFlow 所有的预测都是 0
【发布时间】:2016-06-26 02:44:35
【问题描述】:

我正在为 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)

【问题讨论】:

    标签: python machine-learning tensorflow prediction


    【解决方案1】:

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

    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 也是不错的想法,这些可能是获得合理准确度的必要步骤。

    【讨论】:

    • @rrao 我采纳了你的两个建议,但仍然没有运气:/ 我做了一些调试,似乎在我的训练步骤之后,权重都是 NaN,这会扰乱未来的计算。您是否知道在运行训练步骤后可能导致权重变为 NaN 的原因是什么?
    • 我尝试的第一件事:/没有运气。我不知道这是什么。会不会是数据?我所拥有的是 allTrainingArray 中具有 22 个不同属性的 283 行玩家,并且匹配的是具有 [0,0,0,0,1] (或任何这些位置中的 1 个)的 283 个玩家,表明他是哪种玩家.我查看了 TF 示例来制作我的数据数组,所以我认为这不会有问题。
    • @ShyamKotak,如果你能提供你的行和标签的样本,将会有很大帮助,否则 mrry 的答案似乎对我有用
    【解决方案2】:

    我认为您在计算损失时遇到了问题。如果您添加 biases 向量,它也可能对您的结果有所帮助。

    你应该试试这个:

    W = tf.Variable(tf.zeros([22, 5])) # can try better initialization methods
    b = tf.Variable(tf.zeros([5])) # can try better initialization methods
    y = tf.matmul(x, W) + b
    
    loss = tf.reduce_mean(
       tf.nn.softmax_cross_entropy_with_logits(y, y_)
    )
    
    train_step = tf.train.GradientDescentOptimizer(0.5).minimize(loss)
    

    如果您想查看tf.nn.softmax_cross_entropy_with_logits

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-30
      • 1970-01-01
      相关资源
      最近更新 更多