如何使用tf.train.batch来支持填充变量长度常量?

时间:2017-04-20 05:28:29

标签: tensorflow deep-learning

我正在使用TensorFlow进行练习,我的代码如下:

a = tf.constant([[1,2,3],
               [1,2,0],
               [1,2,4],
               [1,2],
               [1,3,4,2],
               [1,2,3]])

b = tf.reshape(tf.range(12), [6,2])

num_epochs = 3
batch_size = 2
num_batches = 3

# dequeue ops
a_batched, b_batched = tt.slice_input_producer([a, b], num_epochs = num_epochs, capacity=48, shuffle=False)
aa, bb = tt.batch([a_batched, b_batched], batch_size=batch_size, dynamic_pad=True)
aa3 = tf.reduce_mean(aa)
bb3 = tf.reduce_mean(bb)
loss = tf.squared_difference(aa3, bb3)
sess = tf.Session()
sess.run([tf.global_variables_initializer(),
    tf.local_variables_initializer()])
coord = tf.train.Coordinator()
threads = queue_runner_impl.start_queue_runners(sess=sess)
for i in range(num_batches*num_epochs):
    print sess.run(loss)
    print '='*30
coord.request_stop()
coord.join(threads)

由于变量a的长度可变,因此代码会遇到错误:

  

追踪(最近一次通话):     文件“small_input_with_no_padding.py”,第16行,in       [1,2,3]])     文件“/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/constant_op.py”,第99行,常量       tensor_util.make_tensor_proto(value,dtype = dtype,shape = shape,verify_shape = verify_shape))     在make_tensor_proto中输入文件“/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/tensor_util.py”,第376行       _GetDenseDimensions(值)))   ValueError:参数必须是密集张量:[[1,2,3],[1,2,0],[1,2,4],[1,2],[1,3,4,2], [1,2,3]] - 形状[6],但想要[6,3]。

我想测试tf.train.batch如何填充可变长度的输入。那么我该如何解决这个错误呢?非常感谢你!

1 个答案:

答案 0 :(得分:0)

您不能通过无法转换为密集张量的可变长度列表来创建恒定张量。

a = tf.constant([[1,2,3], [1,2,0], [1,2,4], [1,2], [1,3,4,2], [1,2,3]])