tf.data:从不同形状的 Numpy 数组列表创建数据集

tf.data: create a Dataset from a list of Numpy arrays of different shape

我有一个不同形状的 Numpy 数组列表。

我需要创建一个数据集,这样每次请求一个元素时,我都会得到一个具有给定 Numpy 数组的形状和值的张量。

我怎样才能做到这一点?

没有工作:

dataset = tf.data.Dataset.from_tensor_slices(list_of_arrays)

既然你得到了,如你所料:

Can't convert non-rectangular Python sequence to Tensor.

p.s。我知道无法使用不同形状的元素对数据集进行批处理。

您是否尝试过将初始值转换为参差不齐的张量?

tensor_with_from_dimensions = tf.ragged.constant([[1, 2], [3], [4, 5, 6]])

请记住:

All scalar values in pylist must have the same nesting depth K, and the returned RaggedTensor will have rank K. If pylist contains no scalar values, then K is one greater than the maximum depth of empty lists in pylist. All scalar values in pylist must be compatible with dtype.

您可以在此处阅读更多相关信息:https://www.tensorflow.org/api_docs/python/tf/ragged/constant

我接受了 Timbus Calin 的解决方案,因为它更紧凑,但我发现了另一种提供很大灵活性的方法,值得一提。

它基于生成器:

def create_generator(list_of_arrays):
    for i in list_of_arrays:
        yield i

dataset = tf.data.Dataset.from_generator(lambda: create_generator(list_of_arrays),output_types= tf.float32, output_shapes=(None,4))