[TensorFlow] Usage of tf.nn.softmax_cross_entropy_with_logits

[TensorFlow] Usage of tf.nn.softmax_cross_entropy_with_logits

When calculating loss, the most common sentence is tf.nn.softmax_cross_entropy_with_logits, so how does it do it?

First of all, make it clear that loss is the cost value, that is, the value we want to minimize

tf.nn.softmax_cross_entropy_with_logits(logits, labels, name=None)

Remove the name parameter to specify the name of the operation, a total of two parameters related to the method

第一个参数logits:就是神经网络最后一层的输出,如果有batch的话,它的大小就是[batchsize,num_classes],单样本的话,大小就是num_classes

第二个参数labels:实际的标签,大小同上

 

具体的执行流程大概分为两步:

第一步是先对网络最后一层的输出做一个softmax,这一步通常是求取输出属于某一类的概率,对于单样本而言,输出就是一个num_classes大小的向量([Y1,Y2,Y3...]其中Y1,Y2,Y3...分别代表了是属于该类的概率)

softmax的公式是:

至于为什么是用的这个公式?这里不介绍了,涉及到比较多的理论证明

 

第二步是softmax的输出向量[Y1,Y2,Y3...]和样本的实际标签做一个交叉熵,公式如下:


其中指代实际的标签中第i个的值(用mnist数据举例,如果是3,那么标签是[0,0,0,1,0,0,0,0,0,0],除了第4个值为1,其他全为0)

就是softmax的输出向量[Y1,Y2,Y3...]中,第i个元素的值

显而易见,预测越准确,结果的值越小(别忘了前面还有负号),最后求一个平均,得到我们想要的loss

注意!!!这个函数的返回值并不是一个数,而是一个向量,如果要求交叉熵,我们要再做一步tf.reduce_sum操作,就是对向量里面所有元素求和,最后才得到,如果求loss,则要做一步tf.reduce_mean操作,对向量求均值!

 

理论讲完了,上代码

 

[python] view plain copy
  1. import tensorflow as tf  
  2.   
  3. #our NN's output  
  4. logits=tf.constant([[1.0,2.0,3.0],[1.0,2.0,3.0],[1.0,2.0,3.0]])  
  5. #step1:do softmax  
  6. y=tf.nn.softmax(logits)  
  7. #true label  
  8. y_=tf.constant([[0.0,0.0,1.0],[0.0,0.0,1.0],[0.0,0.0,1.0]])  
  9. #step2:do cross_entropy  
  10. cross_entropy = -tf.reduce_sum(y_*tf.log(y))  
  11. #do cross_entropy just one step  
  12. cross_entropy2=tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(logits, y_))#dont forget tf.reduce_sum()!!  
  13.   
  14. with tf.Session() as sess:  
  15.     softmax=sess.run(y)  
  16.     c_e = sess.run(cross_entropy)  
  17.     c_e2 = sess.run(cross_entropy2)  
  18.     print("step1:softmax result=")  
  19.     print(softmax)  
  20.     print("step2:cross_entropy result=")  
  21.     print (c_e)  
  22.     print("Function(softmax_cross_entropy_with_logits) result=")  
  23.     print(c_e2)  


The output is:

 

[python] view plain copy
  1. step1:softmax result=  
  2. [[ 0.09003057  0.24472848  0.66524094]  
  3.  [ 0.09003057  0.24472848  0.66524094]  
  4.  [ 0.09003057  0.24472848  0.66524094]]  
  5. step2:cross_entropy result=  
  6. 1.22282  
  7. Function(softmax_cross_entropy_with_logits) result=  
  8. 1.2228  

Finally, you can try whether e^1/(e^1+e^2+e^3) is 0.09003057, and find that it is the same! ! This also proves我们的输出是符合公式逻辑的

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325301105&siteId=291194637