解决方案
当您创建一个像这样的numpy数组时:
x_data = np.array( [[1,2],[4,5,6],[1,2,3,4,5,6]])
内部numpy dtype是“对象”:
array([[1, 2], [4, 5, 6], [1, 2, 3, 4, 5, 6]], dtype=object)
而且这不能用作张量流中的张量。无论如何,张量必须在每个维度中具有相同的大小,不能“破烂”,并且必须具有每个维度中一个数字定义的形状。 TensorFlow基本上对其所有数据类型进行了假设。尽管TensorFlow的设计人员可以在理论上写入它,使其接受破烂的数组并包含转换功能,但这种自动铸造并不总是一个好主意,因为它可能会在输入代码中隐藏问题。
因此,您需要填充输入数据以使其成为可用的形状。在快速搜索中,我发现 堆栈溢出中的这种方法, ,复制为对您的代码的更改:
import tensorflow as tf
import numpy as np
x = tf.placeholder( tf.int32, [3,None] )
y = x * 2
with tf.Session() as session:
x_data = np.array( [[1,2],[4,5,6],[1,2,3,4,5,6]] )
# Get lengths of each row of data
lens = np.array([len(x_data[i]) for i in range(len(x_data))])
# Mask of valid places in each row
mask = np.arange(lens.max()) < lens[:,None]
# Setup output array and put elements from data into masked positions
padded = np.zeros(mask.shape)
padded[mask] = np.hstack((x_data[:]))
# Call TensorFlow
result = session.run(y, feed_dict={x:padded})
# Remove the padding - the list function ensures we
# create same datatype as input. It is not necessary in the case
# where you are happy with a list of Numpy arrays instead
result_without_padding = np.array(
[list(result[i,0:lens[i]]) for i in range(lens.size)]
)
print( result_without_padding )
输出为:
[[2, 4] [8, 10, 12] [2, 4, 6, 8, 10, 12]]
您无需在末端卸下填充物 - 仅当您需要以相同的破烂阵列格式显示输出时才这样做。另请注意,当您喂养结果时 padded
数据到更复杂的例程,零或其他填充数据(如果更改)可能会被您实施的任何算法使用。
如果您有很多短数组,只有一个或两个很长的阵列,那么您可能需要考虑使用 稀疏张量表示 节省内存并加快计算。
其他提示
作为使用带衬垫阵列的替代方案,您只需将所有数据作为一个大意大利面条字符串馈送,然后在TensorFlow图中进行折纸
例子:
import tensorflow as tf
import numpy as np
sess = tf.InteractiveSession()
noodle = tf.placeholder(tf.float32, [None])
chop_indices = tf.placeholder(tf.int32, [None,2])
do_origami = lambda list_idx: tf.gather(noodle, tf.range(chop_indices[list_idx,0], chop_indices[list_idx,1]))
print( [do_origami(list_idx=i).eval({noodle:[1,2,3,2,3,6], chop_indices:[[0,2],[2,3],[3,6]]}).tolist() for i in range(3)] )
结果:
[[1.0, 2.0], [3.0], [2.0, 3.0, 6.0]]
但是,如果您的内部列表数量可变,那么祝您好运。您不能从tf.while_loop返回列表,也不能仅使用上述列表理解,因此您必须为每个内部列表分开进行计算。
import tensorflow as tf
sess = tf.InteractiveSession()
my_list = tf.Variable(initial_value=[1,2,3,4,5])
init = tf.global_variables_initializer()
sess.run(init)
sess.run(my_list)
结果:数组([1,2,3,4,5])