我想使用TensorFlow2.0在几个GPU上训练一个模型。在分布式培训(https://www.tensorflow.org/guide/distributed_training)的tensorflow教程中,tf.data数据生成器转换为分布式数据集,如下所示:
dist_dataset = mirrored_strategy.experimental_distribute_dataset(dataset)但是,我希望使用自己的自定义数据生成器(例如,keras.utils.Sequence数据生成器,以及用于异步批处理生成的keras.utils.data_utils.OrderedEnqueuer )。但是mirrored_strategy.experimental_distribute_dataset方法只支持tf.data数据生成器。我该如何使用keras数据生成器呢?
谢谢!
发布于 2019-12-06 01:42:36
我在同样的情况下使用tf.data.Dataset.from_generator和我的keras.utils.sequence,它解决了我的问题!
train_generator = SegmentationMultiGenerator(datasets, folder) # My keras.utils.sequence object
def generator():
multi_enqueuer = OrderedEnqueuer(train_generator, use_multiprocessing=True)
multi_enqueuer.start(workers=10, max_queue_size=10)
while True:
batch_xs, batch_ys, dset_index = next(multi_enqueuer.get()) # I have three outputs
yield batch_xs, batch_ys, dset_index
dataset = tf.data.Dataset.from_generator(generator,
output_types=(tf.float64, tf.float64, tf.int64),
output_shapes=(tf.TensorShape([None, None, None, None]),
tf.TensorShape([None, None, None, None]),
tf.TensorShape([None, None])))
strategy = tf.distribute.MirroredStrategy()
train_dist_dataset = strategy.experimental_distribute_dataset(dataset)请注意,这是我的第一个有效的解决方案--目前,我发现最方便的方法就是在实际的输出形状中放入“None”,我发现这是可行的。
发布于 2021-02-12 23:55:47
假设你有一个生成器dg,它在调用时以(feature,label)的形式产生样本,而不使用Enqueuer,这是另一种方法:
import tensorflow as tf
import numpy as np
def get_tf_data_Dataset(data_generator_settings_dict):
length_req = data_generator_settings_dict["length"]
x_d1 = data_generator_settings_dict['x_d1']
x_d2 = data_generator_settings_dict['x_d2']
x_d3 = data_generator_settings_dict['x_d3']
y_d1 = data_generator_settings_dict['y_d1']
x_d2 = data_generator_settings_dict['x_d2']
y_d3 = data_generator_settings_dict['y_d3']
list_of_x_arrays = [np.zeros((x_d1, x_d2, x_d3)) for _ in range(length_req)]
list_of_y_arrays = [np.zeros((y_d1, y_d2, y_d3)) for _ in range(length_req)]
list_of_tuple_samples = [(x, y) for (x, y) in dg()]
list_of_x_samples = [x for (x, y) in list_of_tuple_samples]
list_of_y_samples = [y for (x, y) in list_of_tuple_samples]
for sample_index in range(length_req):
list_of_x[sample_index][:] = list_of_x_samples[sample_index]
list_of_y[sample_index][:] = list_of_y_samples[sample_index]
return tf.data.Dataset.from_tensor_slices((list_of_x, list_of_y))它很复杂,但肯定会起作用。这也意味着dg的__call__方法是一个类似于for循环(当然是在__init__之后):
def __call__(self):
for _ in self.length:
# generate x (single sample of feature)
# generate y (single matching sample of label)
yield x, yhttps://stackoverflow.com/questions/59185729
复制相似问题