最简单的解决方法是填充所有输入数据(例如用零填充),以使所有数组具有相同的维度。请注意,张量流旨在使用 张量 执行计算,张量具有矩形而非可变形状。因此,这样您的操作可能会更快完成,但您需要调整算法以忽略尾随零。
在上面的例子中,代码很简单:
# can hold any number of 4-D vectors
input = tf.placeholder(dtype=tf.float32, shape=[None, 4])
with tf.Session() as session:
data = [[0, 1, 2, 0], [3, 4, 0, 0], [5, 6, 7, 8]]
print session.run(input, feed_dict={input: data})
如果长度恰好是固定的,您可以这样对输入进行分区
input = tf.placeholder(dtype=tf.float32, shape=[None])
split = tf.dynamic_partition(input, partitions=[0, 0, 0, 1, 1, 2, 2, 2, 2], num_partitions=3)
with tf.Session() as session:
data = [0, 1, 2, 3, 4, 5, 6, 7, 8]
print session.run(split, feed_dict={input: data})
结果如下:
[array([ 0., 1., 2.], dtype=float32), array([ 3., 4.], dtype=float32), array([ 5., 6., 7., 8.], dtype=float32)]
partitions参数不能是张量,所以在建图的时候必须静态知道。