Skip to main content
 首页 » 编程设计

python之Tensorflow concat tf.data.Dataset 批处理

2024年08月16日30落叶

使用 tf.data.Dataset 时是否可以连接 数据集的批处理,而不是第二个数据集 连接在第一个的末尾,但是这样 第二个数据集的第一批在之后连接 第二个数据集的第一批等等。

我试过如下,但这给了我一个长度为 40 的数据集, 但是,我希望这里的长度为 80。

train_data = train_data.batch(40).concatenate(augmentation_data.batch(40)) 

请您参考如下方法:

不确定您的用例是什么,但您可能希望像这样分别连接批处理中的特征和标签张量:

def concat_batches(x, y): 
    features1, labels1 = x 
    features2, labels2 = y 
    return ({feature: tf.concat([features1[feature], features2[feature]], axis=0) for feature in features1.keys()}, tf.concat([labels1, labels2], axis=0)) 

举个例子:

dataset = tf.data.Dataset.from_tensor_slices(({"test": [[1], [1], [1], [1]]}, [1, 1, 1, 1])) 
b1 = dataset.repeat().batch(3).make_one_shot_iterator().get_next() 
dataset2 = tf.data.Dataset.from_tensor_slices(({"test": [[2], [2], [2], [2]]}, [2, 2, 2, 2])) 
b2 = dataset2.repeat().batch(3).make_one_shot_iterator().get_next() 
 
b_con = concat_batches(b1, b2) #tensors of batches 1 and 2 have shape (3, 1), features of the concatenated batch (6, 1) 

在评估示例时,您将看到 b_con 将如下所示:

({'test': array([[1], 
       [1], 
       [1], 
       [2], 
       [2], 
       [2]], dtype=int32)}, array([1, 1, 1, 2, 2, 2], dtype=int32)) 

希望这对您有所帮助!