我正在跟随此处的一个多层感知器示例:https://github.com/aymericdamien/TensorFlow-Examples,但我对tf.nn.softmax_cross_entropy_with_logits
函数感到困惑,以及它与tf.nn.relu
和reduce_sum
的关系。假设我声明了一个网络如下:
x = tf.placeholder('float',[None,24**2])
y = tf.placeholder('float',[None,10])
w1 = tf.Variable(random_normal([24**2,12]))
w2 = tf.Variable(random_normal([12,10]))
h = tf.nn.relu(tf.matmul(x,w1))
yhat= tf.matmul(h, w2)
''' 成本函数'''
cost = tf.reduce_mean(tf.nn.softmax_corss_entropy_with_logits(logits=yhat, labels=y))
上面这段不应该与下面的代码相同吗:
x = tf.placeholder('float',[None,24**2])
y = tf.placeholder('float',[None,10])
w1 = tf.Variable(random_normal([24**2,12]))
w2 = tf.Variable(random_normal([12,10]))
h = tf.nn.relu(tf.matmul(x,w1))
yhat= tf.nn.softmax(tf.matmul(h, w2))
''' 成本函数'''
cost = tf.reduce_mean(-tf.reduce_sum(y*tf.log(yhat),reduction_indices=1))
但是当我使用第一种构造方法进行训练时,我的准确率大约是95%
,第二种方法的准确率只有1%
,所以显然不仅仅是“数值不稳定性”对吗?
回答:
我做了一些快速的研究。我在multilayer_peceptron.py
文件的第62行上面添加了这一行,并在第87行打印了它
cost_v2 = tf.reduce_mean(-tf.reduce_sum(y*tf.log(tf.nn.softmax(pred)),1))
在第一个批次中,它显示为nan
,因为pred
在经过softmax处理后实际上包含了相当多的零。我猜测交叉熵会忽略这些零,并基于这个链接继续进行求和:https://datascience.stackexchange.com/questions/9302/the-cross-entropy-error-function-in-neural-networks