【问题标题】:Binary Classification NN with Softmax Output Layer Predicting Incorrectly具有 Softmax 输出层的二元分类 NN 预测不正确
【发布时间】:2019-06-11 01:28:59
【问题描述】:

快速总结:

  1. 当我在其输出层上没有激活函数并使用softmax_cross_entropy_with_logits_v2 损失函数运行我的网络时,它的预测值都是负数,并且不像我的一个热门输出类(只有 0 或 1),它不对我没有意义。在我看来,让网络本身的输出概率总和为 1 是有意义的,但我不确定如何在不使用 softmax 作为输出层的激活函数的情况下实现这一点。

已经回答:

  1. 当我使用 softmax 作为我的输出类并使用 cost = tf.reduce_mean(-tf.reduce_sum(y * tf.cast(tf.log(prediction), tf.float32), [1])) 作为我的损失函数(如附加问题中所引用的)时,我的网络输出所有 [nan, nan] 预测
  2. 当我在输出层上尝试 softmax 和 softmax_cross_entropy_with_logits_v2 损失函数时,我所有的预测都是相同的 [0, 1] 或 [1, 0]。

加长版:

我的数据格式为:

我有以下模型,它尝试使用维度 2 的输出节点执行二进制分类。

def neural_network_model(data):

hidden_1_layer = {'weights': tf.Variable(tf.random_normal([n_features, n_nodes_hl1])),
                'biases': tf.Variable(tf.random_normal([n_nodes_hl1]))}
hidden_2_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                'biases': tf.Variable(tf.random_normal([n_nodes_hl2]))}
hidden_3_layer = {'weights': tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
                'biases': tf.Variable(tf.random_normal([n_nodes_hl3]))}
output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
                'biases':tf.Variable(tf.random_normal([n_classes]))}

l1 = tf.add(tf.matmul(data, hidden_1_layer['weights']), hidden_1_layer['biases'])
l1 = tf.nn.relu(l1)

l2 = tf.add(tf.matmul(l1, hidden_2_layer['weights']), hidden_2_layer['biases'])
l2 = tf.nn.relu(l2)

l3 = tf.add(tf.matmul(l2, hidden_3_layer['weights']), hidden_3_layer['biases'])
l3 = tf.nn.relu(l3)
# output shape -- [batch_size, 2]
# example output = [[0.63, 0.37], 
#                   [0.43, 0.57]]
output = tf.add(tf.matmul(l3, output_layer['weights']), output_layer['biases'])
softmax_output = tf.nn.softmax(output)

return softmax_output, output

我使用以下函数对其进行训练:

def train_neural_network(x):

softmax_prediction, regular_prediction = neural_network_model(x)

cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=softmax_prediction, labels=y))
# cost = tf.reduce_mean(-tf.reduce_sum(y * tf.cast(tf.log(prediction), tf.float32), [1]))
optimizer = tf.train.AdamOptimizer(learning_rate=0.001).minimize(cost)

per_epoch_correct = tf.equal(tf.argmax(softmax_prediction, 1), tf.argmax(y, 1))
accuracy = tf.reduce_mean(tf.cast(per_epoch_correct, tf.float32))

hm_epochs = 5000
with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    pred = []
    for epoch in range(hm_epochs):
        acc = 0
        epoch_loss = 0
        i = 0
        while i < len(X_train)-9:
            start_index = i
            end_index = i + batch_size

            batch_x = np.array(X_train[start_index:end_index])
            batch_y = np.array(y_train[start_index:end_index])

            _ , c, acc, pred = sess.run([optimizer, cost, accuracy, softmax_prediction], feed_dict={x: batch_x, y:batch_y})
            epoch_loss += c
            i += batch_size
        print(pred[0])
        print('Epoch {} completed out of {} loss: {:.9f} accuracy: {:.9f}'.format(epoch+1, hm_epochs, epoch_loss, acc))

    # get accuracy

    correct = tf.equal(tf.argmax(softmax_prediction, 1), tf.argmax(y, 1))
    final_accuracy = tf.reduce_mean(tf.cast(correct, tf.float32))
    print('Accuracy:', final_accuracy.eval({x:X_test, y:y_test})) 

所以基本上,当我在其输出层上没有激活函数并使用softmax_cross_entropy_with_logits_v2 损失函数运行它时,我的网络“工作”(我认为?)。但是,当我查看它的预测值时,它们都是负数,并且不像我的一个热门输出类(只有 0 或 1),这对我来说没有意义。

此外,我正在查看question 关于使用 softmax 函数的正确方法,并且使用 softmax 作为我的输出层的激活函数似乎是有意义的。这是因为我有 2 个输出类,因此我的网络可以输出每个类总和为 1 的概率。但是,当我使用 softmax 作为我的输出类和 cost = tf.reduce_mean(-tf.reduce_sum(y * tf.cast(tf.log(prediction), tf.float32), [1])) 作为我的损失函数时(如所附问题中所引用) ,我的网络输出所有 [nan, nan] 预测。当我在输出层上尝试 softmax 和 softmax_cross_entropy_with_logits_v2 损失函数时,我所有的预测都是相同的 [0, 1] 或 [1, 0]。我尝试遵循 this question 中的建议,但我的带有 softmax 输出的网络仍然只输出所有 [0, 1] 或 [1, 0] 的预测。

总的来说,我不确定如何进行,我认为我一定误解了这个网络的结构。任何帮助将不胜感激。

【问题讨论】:

    标签: python tensorflow machine-learning deep-learning classification


    【解决方案1】:

    当您使用 cross_entropy_with_logits_v2 时,通过 logit 很重要。在应用 softmax 之前,它被称为 logit to previous value。 应该是这样的:

    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=regular_prediction, labels=y))
    

    该函数执行 softmax,然后执行 cross_entropy。之所以如此,是因为如果它们在反向传播中单独应用,您可能会出现数值不稳定。但同时应用时,它在反向传播中得到了简化,变得 100% 稳定。

    编辑: cross_entropy_with_logits_v2 是执行以下 cross_entropy (softmax (x), y) 的层。 问题是在向后这种 cross_entropy 和 softmax 的组合在数值上是不稳定的。这就是你得到nans的原因。当两者结合时,通过以下方式进行简化:https://deepnotes.io/softmax-crossentropy

    如果你应用一个然后另一个,tensorflow 将无法简化。

    【讨论】:

    • 我在上面描述的第一种情况下尝试了这个,我的输出都是负数,不像我的一个热门输出类(只有 0 或 1),这对我来说没有意义。此外,为什么先应用softmax,然后再应用其他一些损失函数(而不是同时应用两者)会导致整个模型无法工作?
    • 我改写了我上面的“简短摘要”以提高清晰度——之前的措辞很糟糕
    • 我已经更新了答案。在您的情况下,您正在执行以下操作: Cross_entropy(softmax(softmax(x)))
    • 这是有道理的。我仍然很困惑为什么我的网络输出都是非常小的负数,彼此非常接近,并且不像我的一个热门输出类。此外,让网络本身输出概率总和为 1 不是更有意义吗?如果不使用 softmax 作为输出层的激活函数,如何实现这一点?
    • 通常情况下,所做的是将没有激活的最后一层发送到 cross_entropy_with_logits_v2 并与 softmax 并行。学习使用第一个并预测第二个。
    猜你喜欢
    • 2020-03-12
    • 2021-04-23
    • 1970-01-01
    • 2023-03-15
    • 2020-07-20
    • 1970-01-01
    • 2021-12-04
    • 1970-01-01
    • 2019-01-27
    相关资源
    最近更新 更多