qq_34644971
qq_34644971
采纳率37.5%
2018-12-05 11:22

tensorflow当中的loss里面的logits可不可以是placeholder

我使用tensorflow实现手写数字识别,我希望softmax_cross_entropy_with_logits里面的logits先用一个placeholder表示,然后在计算的时候再通过计算出的值再传给placeholder,但是会报错ValueError: No gradients provided for any variable, check your graph for ops that do not support gradients。我知道直接把logits那里改成outputs就可以了,但是如果我一定要用logits的结果先是一个placeholder,我应该怎么解决呢。

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data
mnist = input_data.read_data_sets("/home/as/下载/resnet-152_mnist-master/mnist_dataset", one_hot=True)

from tensorflow.contrib.layers import fully_connected

x = tf.placeholder(dtype=tf.float32,shape=[None,784])
y = tf.placeholder(dtype=tf.float32,shape=[None,1])

hidden1 = fully_connected(x,100,activation_fn=tf.nn.elu,
                         weights_initializer=tf.random_normal_initializer())

hidden2 = fully_connected(hidden1,200,activation_fn=tf.nn.elu,
                         weights_initializer=tf.random_normal_initializer())
hidden3 = fully_connected(hidden2,200,activation_fn=tf.nn.elu,
                         weights_initializer=tf.random_normal_initializer())


outputs = fully_connected(hidden3,10,activation_fn=None,
                         weights_initializer=tf.random_normal_initializer())




a = tf.placeholder(tf.float32,[None,10])


loss = tf.nn.softmax_cross_entropy_with_logits(labels=y,logits=a)
reduce_mean_loss = tf.reduce_mean(loss)

equal_result = tf.equal(tf.argmax(outputs,1),tf.argmax(y,1))
cast_result = tf.cast(equal_result,dtype=tf.float32)
accuracy = tf.reduce_mean(cast_result)

train_op = tf.train.AdamOptimizer(0.001).minimize(reduce_mean_loss)

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())
    for i in range(30000):
        xs,ys = mnist.train.next_batch(128)
        result = outputs.eval(feed_dict={x:xs})
        sess.run(train_op,feed_dict={a:result,y:ys})
        print(i)
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

2条回答

  • W_LAILAI Janton Wang 2年前

    为什么要占位,a = tf.placeholder(tf.float32,[None,10])
    输入才会使用占位,logits是网络输出!

    点赞 评论 复制链接分享
  • weixin_29444181 哈喽大海豚 3年前

    可以是placeholder

    点赞 评论 复制链接分享

相关推荐