调用tf.softmax_cross_entropy_with_logits函数出错解决

来源:互联网 发布:c语言学生管理系统6.0 编辑:程序博客网 时间:2024/06/05 12:43

运行一个程序时提示出错如下:

Traceback (most recent call last):
  File "/MNIST/softmax.py", line 12, in <module>
    cross_entropy2=tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(logits, y_))#dont forget tf.reduce_sum()!!
  File "C:\python35\lib\site-packages\tensorflow\python\ops\nn_ops.py", line 1578, in softmax_cross_entropy_with_logits
    labels, logits)
  File "C:\python35\lib\site-packages\tensorflow\python\ops\nn_ops.py", line 1533, in _ensure_xent_args
    "named arguments (labels=..., logits=..., ...)" % name)
ValueError: Only call `softmax_cross_entropy_with_logits` with named arguments (labels=..., logits=..., ...)


原来这个函数,不能按以前的方式进行调用了,只能使用命名参数的方式来调用。原来是这样的:

tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(y, y_))

因此修改需要成这样:

tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_))


例子完整代码如下:

#python 3.5.3      #2017-03-09 蔡军生  http://blog.csdn.net/caimouse    #import tensorflow as tf    #our NN's output  logits = tf.constant([[1.0,2.0,3.0],[1.0,2.0,3.0],[1.0,2.0,3.0]])#step1:do softmax  y = tf.nn.softmax(logits)#true label  y_ = tf.constant([[0.0,0.0,1.0],[0.0,0.0,1.0],[0.0,0.0,1.0]])  #step2:do cross_entropy  cross_entropy = -tf.reduce_sum(y_*tf.log(y))  #do cross_entropy just one step  cross_entropy2 = tf.reduce_sum(tf.nn.softmax_cross_entropy_with_logits(logits=logits, labels=y_))  with tf.Session() as sess:      softmax=sess.run(y)      c_e = sess.run(cross_entropy)      c_e2 = sess.run(cross_entropy2)      print("step1:softmax result=")      print(softmax)      print("step2:cross_entropy result=")      print(c_e)      print("Function(softmax_cross_entropy_with_logits) result=")      print(c_e2)  

输出结果:

step1:softmax result=
[[ 0.09003057  0.24472848  0.66524094]
 [ 0.09003057  0.24472848  0.66524094]
 [ 0.09003057  0.24472848  0.66524094]]
step2:cross_entropy result=
1.22282
Function(softmax_cross_entropy_with_logits) result=
1.22282


1. TensorFlow入门基本教程

http://edu.csdn.net/course/detail/4369

2. C++标准模板库从入门到精通 

http://edu.csdn.net/course/detail/3324

3.跟老菜鸟学C++

http://edu.csdn.net/course/detail/2901

4. 跟老菜鸟学python

http://edu.csdn.net/course/detail/2592

5. 在VC2015里学会使用tinyxml库

http://edu.csdn.net/course/detail/2590

6. 在Windows下SVN的版本管理与实战 

 http://edu.csdn.net/course/detail/2579

7.Visual Studio 2015开发C++程序的基本使用 

http://edu.csdn.net/course/detail/2570

8.在VC2015里使用protobuf协议

http://edu.csdn.net/course/detail/2582

9.在VC2015里学会使用MySQL数据库

http://edu.csdn.net/course/detail/2672


3 0