【问题标题】:Tensorflow - softmax returning only 0 and 1Tensorflow - softmax 仅返回 0 和 1
【发布时间】:2018-10-15 05:22:04
【问题描述】:

我正在使用 TensorFlow 训练 CNN,但我的损失没有得到改善;我注意到 tf.nn.softmax() 正在返回一个只有 0 和 1 的张量,而不是我期望的分布。 Here's the repo,我认为这是我无法训练网络但我不知道如何解决的原因。

【问题讨论】:

    标签: python tensorflow neural-network softmax cross-entropy


    【解决方案1】:

    查看神经网络下的第二个框:

    # output layer
    with tf.variable_scope('output_lay') as scope:
        weights = weight_variable([4096, CLASSES])
        bias = bias_variable([CLASSES], 0.)
        activation = tf.nn.relu(tf.matmul(out, weights)+bias, name=scope.name)
        out = tf.nn.softmax(activation)
    return tf.reshape(out, [-1, CLASSES])
    

    注意:ReLu 激活仅用于隐藏层而非输出层。

    然后你在你的 train 函数中把它喂给交叉熵

    logits=AlexNet(x_tr)
    
    # loss function
    cross_entropy = -tf.reduce_sum(tf.squeeze(y_tr)*tf.log(tf.clip_by_value(tf.squeeze(logits),1e-10,1.0)))
    loss = tf.reduce_mean(cross_entropy)
    

    再次访问cross entropy

    C= −1/n * (∑[y*ln(a)+(1−y)*ln(1−a)])

    在哪里a = sigmoid(W(x)+b),所以我建议:

    with tf.variable_scope('output_lay') as scope:
        weights = weight_variable([4096, CLASSES])
        bias = bias_variable([CLASSES], 0.)
        return tf.matmul(out, weights)+bias
    

    为简单起见,只需使用内置的 softmax 函数:

    logits=AlexNet(x_tr)
    
    cross_entropy = tf.nn.softmax_cross_entropy_with_logits(labels=ground_truth_input, logits=logits)
    loss = tf.reduce_mean(cross_entropy)
    

    tf.nn.softmax_cross_entropy_with_logits 接受W(x)+b 并高效计算交叉熵。

    【讨论】:

    • 我认为您对输出层中的 ReLu 的看法是正确的,我尝试使用 tf.nn.softmax_cross_entropy_with_logits,但我得到了 nan 的损失。如果我用我自己的方式来计算,那么softmax只给0或1的问题仍然存在
    • @AlessandroGaballo 是你的ground_truth_input One-hot 编码?
    • 是的,在decode() 方法中,我使用label = tf.one_hot(label, 10)
    • 在这种情况下,只需将原始 W(x)+b 输入到 tf.nn.softmax(它在内部负责将 sigmoid 应用于 W(x)+b),看看是否有帮助。 This 可能会有所帮助。
    • 正如我所提到的,如果我输出 tf.nn.softmax() 并手动计算交叉熵,我会在预测中得到所有 0 和 1,如果我使用 tf.nn.softmax_cross_entropy_with_logits() 来计算损失,我会得到南在这两种情况下,损失都没有改善
    猜你喜欢
    • 1970-01-01
    • 2016-03-22
    • 2018-09-27
    • 1970-01-01
    • 2016-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-05
    相关资源
    最近更新 更多