Tensorflow:sess.run([x])不起作用,但是sess.run([y])使用相同的feed_dict

时间:2019-06-03 15:25:50

标签: python tensorflow

我正在学习Tensorboard,并且正在遵循this tutorial.

中的代码

下面是我的代码:

import tensorflow as tf
LOGDIR = "/tmp/mnist_tutorial/"
mnist = tf.contrib.learn.datasets.mnist.read_data_sets(train_dir=LOGDIR + "data", one_hot=True)

def conv_layer(input, size_in, size_out, name="conv"):
    with tf.name_scope(name):
        w = tf.Variable(tf.zeros([5, 5, size_in, size_out]))
        b = tf.Variable(tf.zeros([size_out]))
        conv = tf.nn.conv2d(input, w, strides=[1, 1, 1, 1], padding="SAME")
        act = tf.nn.relu(conv + b)
        tf.summary.histogram("weights", w)
        tf.summary.histogram("biases", b)
        tf.summary.histogram("activations", act)
        return act


def fc_layer(input, size_in, size_out, name="fc"):
    with tf.name_scope(name):
        w = tf.Variable(tf.zeros([size_in, size_out]))
        b = tf.Variable(tf.zeros([size_out]))
        act = tf.nn.relu(tf.matmul(input, w)+b)
        tf.summary.histogram("weights", w)
        tf.summary.histogram("biases", b)
        tf.summary.histogram("activations", act)
        return act

x = tf.placeholder(tf.float32, shape=[None, 784], name='x')
x_image = tf.reshape(x, [-1, 28, 28, 1])
tf.summary.image('input', x_image, 3)

y = tf.placeholder(tf.float32, shape=[None, 10], name='labels')

conv1 = conv_layer(x_image, 1, 32, name='conv1')
pool1 = tf.nn.max_pool(conv1, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME")

conv2 = conv_layer(pool1, 32, 64, name='conv2')
pool2 = tf.nn.max_pool(conv2, ksize=[1,2,2,1], strides=[1,2,2,1], padding="SAME")
flattened = tf.reshape(pool2, [-1, 7*7*64])

fc1 = fc_layer(flattened, 7*7*64, 1024, name='fc1')
logits = fc_layer(fc1, 1024, 10, name='fc2')

with tf.name_scope('xent'):
    xent = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits_v2(logits=logits, labels=y))
    tf.summary.scalar('cross_entropy', xent)

with tf.name_scope('train'):
    train_step = tf.train.AdamOptimizer(1e-4).minimize(xent)

with tf.name_scope('accruacy'):
    correct_prediction = tf.equal(tf.argmax(logits,1), tf.argmax(y, 1))
    accuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))
    tf.summary.scalar('accruacy', accuracy)

summ = tf.summary.merge_all()

with tf.Session() as sess:
    sess.run(tf.global_variables_initializer())

    # writer =tf.summary.FileWriter("tmp/mnist_demo/1")
    # writer.add_graph(sess.graph)
    # writer.close()

    for i in range(20):
        batch = mnist.train.next_batch(100)

        # Occasionally report back the accruacy

        if i%2 == 0:
            [train_accruacy] = sess.run([accuracy], feed_dict={x:batch[0], y:batch[1]}) # works
#             [s, train_accruacy] = sess.run([summ, accuracy], feed_dict={x:batch[0], y:batch[1]}) #error!
            print("step %d, training accruacy %g" % (i, train_accruacy))

    sess.run(train_step, feed_dict={x:batch[0],y:batch[1]})

使用此行时遇到错误:

[s, train_accruacy] = sess.run([summ, accuracy], feed_dict={x:batch[0], y:batch[1]}) #error!

这是我收到的错误消息:

You must feed a value for placeholder tensor 'x' with dtype float and shape [?,784] [[{{node x}} = Placeholder[dtype=DT_FLOAT, shape=[?,784], _device="/job:localhost/replica:0/task:0/device:CPU:0"]()]]

据我了解,我输入的张量的形状不正确(x,784)。

但是,我不明白为什么[train_accruacy] = sess.run([accuracy], feed_dict={x:batch[0], y:batch[1]}) # works。毕竟,我将相同的内容输入相同的占位符变量,这些变量接受相同形状的张量。

除非我完全误解,否则sess.run([argument], feed_dict=...)的第一个参数描述要返回的张量。我看不到它如何影响我输入的数据的形状。

此外:该模型应该有错误。

对于那些感兴趣的人,完整的代码是here

返回数据类型是否也不同? tf.summary.merge_all()返回一个字符串张量,但是我怀疑那是导致问题的原因。

我似乎无法在线找到有关此问题的任何文档。这应该发生吗?

1 个答案:

答案 0 :(得分:0)

我将回答我自己的问题:

Input First number : 1, second number: 11, third number: 3 Output 1 cubed is 1 4 cubed is 64 7 cubed is 343 10 cubed is 1000 有效,并添加到tf.reset_default_graph()之前。

如果不想使用def conv_layer()

结果证明我在同一会话中输入了2个张量,而这个张量流是不允许的。

tf.reset_default_graph()

上面的代码不起作用。。事实证明,由于某些原因,for i in range(20): batch = mnist.train.next_batch(100) sess.run(train_step, feed_dict={x:batch[0],y:batch[1]}) # Occasionally report back the accruacy if i%2 == 0: [train_accruacy] = sess.run([accuracy], feed_dict={x:batch[0], y:batch[1]}) # works # [s, train_accruacy] = sess.run([summ, accuracy], feed_dict={x:batch[0], y:batch[1]}) #error! print("step %d, training accruacy %g" % (i, train_accruacy)) 下面的第一行代码可以很好地输入张量i%2,但是,当它注释掉该行并将其替换为第二行时,似乎tensorflow不会“冲洗” batch[0]占位符变量,因此将两个单独的张量馈入输入(来自单独的{{1 }})事件。

此代码有效:

x

这里的张量是分别输入的,一切运行正常。

如果有人可以让我知道为什么会这样,或者这是一个错误,我会很高兴。