使用Tensorflow,MNIST的预测

时间:2018-03-31 20:39:26

标签: python tensorflow mnist

我试图为mnist创建一个深度NN。我理解训练部分但我对在恢复预训练模型后如何进行实际预测感到非常困惑。这是我的代码:

import tensorflow as tf
from tensorflow.examples.tutorials.mnist import input_data

mnist = input_data.read_data_sets('tmp/data/', one_hot=True)

n_nodes_hl1 = n_nodes_hl2 = n_nodes_hl3 = 500
n_classes, batch_size = 10, 100

x = tf.placeholder(tf.float32, shape=(None, 784))
y = tf.placeholder(tf.float32)

def DeepNN_model(data):

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

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

    hl3 = {
        '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]))
    }

    # (input * weights) + biases

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

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

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

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

    return output

def train_DeepNN(x):

    # treat these like defs
    prediction = DeepNN_model(x)
    cost = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(logits=prediction, labels=y))
    optimizer = tf.train.AdamOptimizer().minimize(cost)

    # feedforward + backprop
    n_epochs = 10

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

        for epoch in range(n_epochs):
            epoch_loss = 0
            for _ in range(int(mnist.train.num_examples/batch_size)):
                epoch_x, epoch_y = mnist.train.next_batch(batch_size)
                _, cost_value = sess.run([optimizer, cost], feed_dict={x: epoch_x, y: epoch_y})
                epoch_loss += cost_value

            print('Epoch: ', epoch + 1, ' Loss: ', epoch_loss)

        # 'saver' must be created after the variables that you want to save (or restore)
        tf.add_to_collection('x', x)
        tf.add_to_collection('preds', prediction)
        saver = tf.train.Saver()
        saver.save(sess, 'tmp/mnist_DeepNN.ckpt')

        # treat these like defs too; too high level, almost weird, still cool
        correctness = tf.equal(tf.argmax(prediction, 1), tf.argmax(y, 1))
        accuracy = tf.reduce_mean(tf.cast(correctness, tf.float32))

        print('Accuracy: ', 100*accuracy.eval({
            x: mnist.test.images,
            y: mnist.test.labels
            }))

def predict(x_test):
    with tf.Session() as sess:
        sess.run(tf.global_variables_initializer())
        saver = tf.train.import_meta_graph('tmp/mnist_DeepNN.ckpt.meta')
        saver.restore(sess, tf.train.latest_checkpoint('./tmp/'))

        x = tf.get_collection('x')[0]
        prediction = tf.get_collection('preds')[0]
        print('DeepNN restored!')

        predict = sess.run(prediction, feed_dict={x: x_test})
        print(predict)
        print(tf.argmax(predict, 1), tf.argmax(mnist.test.labels, 1))

#train_DeepNN(x)
predict(mnist.test.images)

我在predict()函数中收到以下错误:

  

InvalidArgumentError(参见上面的追溯):
  您必须为占位符张量提供一个值' Placeholder_2' dtype浮点数和形状[?,784]

我想我不明白sess.run()中传递的内容。我在过去的三个小时里一直在谷歌搜索,而且我找不到任何东西。

我的predict()功能出了什么问题?

0 个答案:

没有答案