如何在 Tensorflow 2.0 中制作不规则批处理?

Cho*_*One 4 python python-3.x tensorflow tensorflow2.0

我正在尝试从由一维数值数据张量组成的 Tensorflow 数据集创建数据输入管道。我想创建一批不规则的张量;我不想填充数据。

例如,如果我的数据采用以下形式:

[
    [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
    [0, 1, 2, 3, 4]
    ...
]

Run Code Online (Sandbox Code Playgroud)

我希望我的数据集由以下形式的批次组成:

<tf.Tensor [
    <tf.RaggedTensor [
        [0, 1, 2, 3, 4, 5, 6, 7, 8, 9], 
        [0, 1, 2, 3, 4], 
        ...]>,
    <tf.RaggedTensor [
        [ ... ],
        ...]>
    ]>
Run Code Online (Sandbox Code Playgroud)

我尝试过RaggedTensor使用地图创建一个,但似乎无法在一维数据上执行此操作。

Cho*_*One 5

我认为这可以通过批次前后的一些工作来实现。

# First, you can expand along the 0 axis for each data point
dataset = dataset.map(lambda x: tf.expand_dims(x, 0))
# Then create a RaggedTensor with a ragged rank of 1
dataset = dataset.map(lambda x: tf.RaggedTensor.from_tensor(x))
# Create batches
dataset = dataset.batch(BATCH_SIZE)
# Squeeze the extra dimension from the created batches
dataset = dataset.map(lambda x: tf.squeeze(x, axis=1))
Run Code Online (Sandbox Code Playgroud)

那么最终的输出将是以下形式:

<tf.RaggedTensor [
    <tf.Tensor [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]>,
    <tf.Tensor [0, 1, 2, 3]>,
    ...
]>
Run Code Online (Sandbox Code Playgroud)

每批次。

  • 目前尚不清楚 - 在第一步之前如何从列表创建数据集 (3认同)