Tensorflow:如何使用tf.train.batch()

时间:2018-04-16 11:35:25

标签: python tensorflow mini-batch

我将Tensorflow(版本1.7.0和Python 3.5)用于神经网络,并且使用tf.train.batch()函数时遇到问题。请参阅here

我的数据集的维度是:

测试图像(100000,900) 测试标签(100000,10)

所以我有100000张尺寸为30 x 30像素的测试图像。标签是一个大小为100000 x 10的单热矩阵。

import numpy as np
train_images = np.load("train_images.npy")
train_labels = np.load("train_labels.npy")

现在我想获得一个100的随机批次,并希望使用函数tf.train.batch()

我在我的代码中使用如下函数:

# Launch the graph
with tf.Session() as sess:
    sess.run(init)
    num_examples=100000
    batch_size = 100

    # Training cycle
    for epoch in range(training_epochs):
        total_batch = int(num_examples/batch_size)
        # Loop over all batches
        for i in range(total_batch):
            batch_x, batch_y = tf.train.batch(
                [train_images, train_labels],
                batch_size=batch_size,
                allow_smaller_final_batch=True,
                )

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

这样做我收到以下错误:

    Traceback (most recent call last):
    File "my_network.py", line 124, in <module>
    _, c = sess.run([optimizer, cost], feed_dict={x: batch_x, y:batch_y})
    File "/home/samuel/tensorflow/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 905, in run
    run_metadata_ptr)
    File "/home/samuel/tensorflow/lib/python3.5/site-packages/tensorflow/python/client/session.py", line 1091, in _run
    'feed with key ' + str(feed) + '.')
    TypeError: The value of a feed cannot be a tf.Tensor object. 
    Acceptable feed values include Python scalars, strings, lists, 
    numpy ndarrays, or TensorHandles.For reference, the tensor object was
    Tensor("batch:0", shape=(?, 900), dtype=uint8) which was passed to the
feed with key Tensor("Placeholder:0", shape=(?, 900), dtype=float32).

如何使用tf.train.batch()以便我的网络正常工作?我是否需要使用其他方法来创建迷你批次?

1 个答案:

答案 0 :(得分:0)

tf.train.batch已弃用,您应该使用tf.data进行批处理。

那说......

为了清晰起见,您应该将图表构建和图表运行步骤分开。

然后,当使用tf.train.batch时,在构建图形之后但在运行任何操作之前,您需要运行tf.queue_runner.start_queue_runners()来启动将预取数据到批处理的线程。