Tensorflow softmax_cross_entropy_with_logits 与 tf.reduce_mean(-tf.reduce_sum(y*tf.log(yhat), reduction_indices = 1)) 的比较

我正在跟随此处的一个多层感知器示例:https://github.com/aymericdamien/TensorFlow-Examples,但我对tf.nn.softmax_cross_entropy_with_logits函数感到困惑,以及它与tf.nn.relureduce_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%,所以显然不仅仅是“数值不稳定性”对吗?

完整示例请见:https://github.com/aymericdamien/TensorFlow-Examples/blob/master/examples/3_NeuralNetworks/multilayer_perceptron.py


回答:

我做了一些快速的研究。我在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

Related Posts

使用LSTM在Python中预测未来值

这段代码可以预测指定股票的当前日期之前的值,但不能预测…

如何在gensim的word2vec模型中查找双词组的相似性

我有一个word2vec模型,假设我使用的是googl…

dask_xgboost.predict 可以工作但无法显示 – 数据必须是一维的

我试图使用 XGBoost 创建模型。 看起来我成功地…

ML Tuning – Cross Validation in Spark

我在https://spark.apache.org/…

如何在React JS中使用fetch从REST API获取预测

我正在开发一个应用程序,其中Flask REST AP…

如何分析ML.NET中多类分类预测得分数组?

我在ML.NET中创建了一个多类分类项目。该项目可以对…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注