Tensorflow MNIST 评估预测

Tensor Flow MNIST Evaluating predictions

我正在研究这个tutorial,我在下面的代码中发现:在评估预测时,他运行准确度,它运行正确的变量,而正确的变量又运行预测,它将再次用随机数重新初始化权重并重建神经网络模型。这怎么对?我错过了什么?

def neural_network_model(data):
    hidden_1_layer = {'weights':tf.Variable(tf.random_normal([784, n_nodes_hl1])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl1]))}

    hidden_2_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl1, n_nodes_hl2])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl2]))}

    hidden_3_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl2, n_nodes_hl3])),
                      'biases':tf.Variable(tf.random_normal([n_nodes_hl3]))}

    output_layer = {'weights':tf.Variable(tf.random_normal([n_nodes_hl3, n_classes])),
                    'biases':tf.Variable(tf.random_normal([n_classes])),}


    l1 = tf.add(tf.matmul(data,hidden_1_layer['weights']), hidden_1_layer['biases'])
    l1 = tf.nn.relu(l1)

    l2 = tf.add(tf.matmul(l1,hidden_2_layer['weights']), hidden_2_layer['biases'])
    l2 = tf.nn.relu(l2)

    l3 = tf.add(tf.matmul(l2,hidden_3_layer['weights']), hidden_3_layer['biases'])
    l3 = tf.nn.relu(l3)

    output = tf.matmul(l3,output_layer['weights']) + output_layer['biases']

    return output

def train_neural_network(x):
    prediction = neural_network_model(x)
    cost = tf.reduce_mean( tf.nn.softmax_cross_entropy_with_logits(prediction,y) )
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    hm_epochs = 10
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())

        for epoch in range(hm_epochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples/batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                _, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})
                epoch_loss += c
            print('Epoch', epoch, 'completed out of',hm_epochs,'loss:',epoch_loss)

        correct = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))

        accuracy = tf.reduce_mean(tf.cast(correct, 'float'))
        print('Accuracy:',accuracy.eval({x:mnist.test.images, y:mnist.test.labels}))

train_neural_network(x)

你几乎做对了。 accuracy 张量间接依赖于 prediction 张量,后者又依赖于一个张量 x。在您的代码片段中,您没有包含 x 实际上是什么;然而来自链接教程:

x = tf.placeholder('float', [None, 784])
y = tf.placeholder('float')

所以x是一个占位符,即直接从用户那里获取值的Tensor。从

的最后一行看不太清楚
train_neural_network(x)

他实际上并没有调用一个转换函数 train_neural_network(x),它接受一个 x 并在运行中处理它,就像您对常规函数所期望的那样;相反,该函数使用对先前定义的占位符变量(实际上是虚拟变量)的引用来定义计算图,然后使用会话直接执行。 然而,该图仅使用 neural_network_model(x) 构造一次,然后 查询 给定的时期数。

你错过的是:

_, c = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})

这将查询 optimizer 操作的结果和 cost 张量,假设输入值为 epoch_x for xepoch_y for y,通过所有定义的计算节点拉取数据,一直返回 "down" 到 x。为了获得cost,还需要y。两者均由调用者提供。 AdamOptimizer 将更新所有可训练变量作为其执行的一部分,从而改变网络的权重。

之后,

accuracy.eval({x: mnist.test.images, y: mnist.test.labels})

或者,等价地

sess.run(accuracy, feed_dict={x: mnist.test.images, y: mnist.test.labels})

然后对 相同的 图进行另一个评估 - 不改变它 - 但这次使用输入 mnist.test.images 用于 xmnist.test.labels 对于 y。 它起作用是因为 prediction 本身依赖于 x,它在每次调用 sess.run(...).

时被覆盖为 user-provided 值

这是 TensorBoard 中的图形。很难分辨,但这两个占位符节点位于左下角,紧挨着名为 "Variable" 的橙色节点,并且位于右中,在绿色 "Slice_1" 下方。

这是网络图的相关部分的样子;我使用 TensorBoard 将其导出。由于没有手动标记节点(除了我自己标记的几个节点),因此有点难以获得,但这里有六个相关点。占位符是黄色的:在右下角,您会发现 x 并且 y 位于左中。 绿色是对我们有意义的中间值:左边是 prediction 张量,右边是称为 correct 的张量。蓝色部分是图表的端点:左上角是 cost 张量,右上角是 accuracy。本质上,数据是从下往上流动的。

因此,无论何时说 "evaluate prediction given x"、"evaluate accuracy given x and y" 或 "optimize my network given x and y",您实际上只是在黄色端提供值并观察绿色或蓝色端的结果。