如何使用tf.train.shuffle_batch训练NN?

时间:2017-12-30 11:53:02

标签: python python-3.x tensorflow artificial-intelligence tensorflow-gpu

我已经训练了我的神经元建立了张量流网络并得到了一些我希望减少的过度拟合。我希望批量学习模型可以帮助广告我试图测试这个想法。我找到了tf.train.shuffle_batch()并且打了这个可能会做的事情。所以我尝试了它并没有奏效。 Tensorflow的文档没有帮助。我发现one topic, but the example there只打印出数组。它很有希望用它来学习NN,但在我的情况下,不是将数据分成n元素批次,我得到它们在额外维度上乘以n倍。

以下是代码示例:

nnInput = tf.placeholder(tf.float32, [None, input_width], "network_input")
nnOutput = tf.placeholder(tf.float32, [None, output_width], "expected_labels")

batch_readings, batch_labels = tf.train.shuffle_batch(
    [
        tf.constant(train_readings), 
        tf.constant(train_labels)
    ],
    batch_size = 15,
    num_threads = 4,
    capacity = 500,
    min_after_dequeue = 250,
    allow_smaller_final_batch = True
)

sess.run(tf.global_variables_initializer())

for epoch in range(learning_steps):
    print("epoch:", epoch)
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    print("Input data shapes:", train_readings.shape, train_labels.shape)
    for batch in range(10):
        x, y = sess.run([batch_readings, batch_labels])
        print("Batch shapes:", x.shape, y.shape)
        sess.run(train, feed_dict = {nnInput : x, nnOutput : y})
    coord.request_stop()
    coord.join(threads)

这是输出:

epoch: 0 
Input data shapes: (165, 60) (165, 1) 
Batch shapes: (15, 165, 60) (15, 165, 1)

错误列表以:

结束
ValueError: Cannot feed value of shape (15, 165, 60) for Tensor 'network_input_1:0', which has shape '(?, 60)'

当我用3D数组输入NN时,这种结论并不奇怪,但为什么在我期望x:(15,60)和y:(15,1)时我得到这样的批次?为什么我得到x:(15,165,60)y:(15,165,1)以及如何获得有用的批次?

我正在使用tensorflow-gpu,但希望这也应该有效,对吧?

1 个答案:

答案 0 :(得分:0)

使用 tf.train.shuffle_batch 时遇到了同样的问题。解决方案是添加参数 enqueue_many = True 。默认值为参数enqueue_many为 False

正如tf.train.shuffle_batch中的文档所述 “如果enqueue_many为True,则假设张量代表一批示例,其中第一维以示例为索引,并且张量的所有成员在第一维中应具有相同的大小。如果输入张量具有形状[*,x ,y,z],输出的形状为[batch_size,x,y,z]。“

相关问题