Tensor Flow MNIST评估预测

时间:2017-01-30 19:41:09

标签: tensorflow mnist

我正在研究这个tutorial,我在下面的代码中找到了:在评估预测时,他运行准确性,运行正确的变量,然后运行预测,再次将权重再次重新设置为randoms并重建NN模型。这怎么样?我错过了什么?

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)

1 个答案:

答案 0 :(得分:2)

你几乎做对了。 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的输入值为xepoch_y的{​​{1}}通过所有已定义的计算节点拉动数据,一直向下"向下"到y。为了获得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.imagesx mnist.test.labels }}。 它有效,因为y本身取决于prediction,在x的每次调用中都会覆盖用户提供的值。

以下是TensorBoard中图表的样子。很难说,但是两个占位符节点位于左下方,橙色节点旁边叫做"变量"在中间右侧,在绿色" Slice_1"下面。

以下是网络图表的相关部分的外观;我使用TensorBoard导出了它。它有点难以获得,因为节点没有手动标记(除了我自己标记的一对),但这里有六个相关点。占位符为黄色:在右下方,您会在中间左侧找到sess.run(...)x。 绿色是对我们有意义的中间值:左边是y张量,右边是张量prediction。蓝色部分是图表的端点:左上角是correct张量,右上角是cost。实质上,数据从底部流向顶部。

Network graph

所以,每当你说'#34;评估accuracy给定prediction","评估x给定accuracy和{{1} }"或者"在给定xy"的情况下优化我的网络,你真的只是在黄色端提供值并观察绿色或蓝色的结果。