tf.data,构造具有不同数据的批处理?

时间:2020-07-04 08:46:45

标签: tensorflow tensorflow-datasets tensorflow-estimator tensorflow1.15

我想使用tf.data来构造一批大小为16的数据,其中[:8]是一种数据A,[8:16]是一种数据B。

没有tf.data,很容易做到。如果使用tf.data,则代码可能是:

def _decode_record(record, name_to_features):
    example = tf.parse_single_example(record, name_to_features)
    return example

dataA = tf.data.TFRecordDataset(input_files)
dataA = dataA.apply(
            tf.contrib.data.map_and_batch(
                lambda record: _decode_record(record, name_to_features),
                batch_size=batch_size)
           )

下一步如何做? 我尝试:

dataB = tf.data.TFRecordDataset(input_files2)
dataB = dataB.apply(
            tf.contrib.data.map_and_batch(
                lambda record: _decode_record(record, name_to_features),
                batch_size=batch_size)
           )
dataC = dataA.concatenate(dataB)

但是concatenate是:将整个数据集dataB附加到dataA的末尾。

对于concatenate,请注意name_to_features对于dataAdataB应该是相同的,这意味着我应该填充很多虚拟数据。

我不想使用tf.condtf.where来判断model_fn的{​​{1}}内部的不同数据,这也很难调试。

2 个答案:

答案 0 :(得分:0)

一种解决方案是判断不同的数据:

import tensorflow as tf

data_type = tf.constant([1, 2, 1, 2])
where_index1 = tf.where(tf.equal(data_type, 1))
where_index2 = tf.where(tf.equal(data_type, 2))

data = tf.constant([[10,10],[20,20],[30,30],[40,40]])

data1 = tf.gather_nd(data,where_index1)
data2 = tf.gather_nd(data,where_index2)

sess = tf.Session()

print(sess.run(data1))
print(sess.run(data2))

但是这个答案只是以某种方式绕过了这个问题。

答案 1 :(得分:0)

您可以将数据集压缩在一起,然后从(dataA,dataB)对构造批处理:

import tensorflow as tf

dataset_1 = tf.data.Dataset.from_tensors(1).repeat(100)
dataset_2 = tf.data.Dataset.from_tensors(2).repeat(100)

dataset = tf.data.Dataset.zip((dataset_1, dataset_2))
dataset = dataset.batch(8)
dataset = dataset.map(lambda a, b: tf.concat([a, b], 0))

生产

tf.Tensor([1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2], shape=(16,), dtype=int32)
tf.Tensor([1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2], shape=(16,), dtype=int32)
tf.Tensor([1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2], shape=(16,), dtype=int32)
tf.Tensor([1 1 1 1 1 1 1 1 2 2 2 2 2 2 2 2], shape=(16,), dtype=int32)
...
相关问题