【问题标题】:how to write a generator for keras model for predict_generator如何为 predict_generator 编写 keras 模型的生成器
【发布时间】:2020-01-31 19:13:35
【问题描述】:

我有一个训练有素的 keras 模型,我正在尝试仅使用 CPU 运行预测。我希望这尽可能快,所以我想我会使用predict_generator 和多个工人。我的预测张量的所有数据都预先加载到内存中。仅供参考,array 是张量列表,第一个张量的形状为 [nsamples, x, y, nchannels]。我按照here 的说明制作了一个线程安全的生成器(我在使用fit_generator 时也遵循了这个)。

class DataGeneratorPredict(keras.utils.Sequence):
    'Generates data for Keras'
    def __init__(self, array, batch_size=128):
        'Initialization'
        self.array = array
        self.nsamples = array[0].shape[0]
        self.batch_size = batch_size
        self.ninputs = len(array)
        self.indexes = np.arange(self.nsamples)

    def __len__(self):
        'Denotes the number of batches'
        print('nbatches:',int(np.floor(self.nsamples / self.batch_size)))
        return int(np.floor(self.nsamples / self.batch_size))

    def __getitem__(self, index):
        'Generate one batch of data'
        # Generate indexes of the batch
        print(index)
        inds = self.indexes[index*self.batch_size:(index+1)*self.batch_size]

        # Generate data
        X = []
        for inp in range(self.ninputs):
          X.append(self.array[inp][inds])

        return X

我像这样使用我的模型进行预测,

#all_test_in is my list of input data tensors
gen = DataGeneratorPredict(all_test_in, batch_size=1024)
new_preds = conv_model.predict_generator(gen,workers=4,use_multiprocessing=True)

但无论工人数量如何,我都没有比使用 conv_model.predict 获得任何速度提升。这在拟合我的模型时似乎效果很好(即,使用具有多个工人的生成器来加速)。我的发电机中是否缺少某些东西?有没有更有效的方法来优化预测(除了使用 GPU)?

【问题讨论】:

    标签: python tensorflow optimization keras generator


    【解决方案1】:

    当您调用 .predict 时,Keras 已经尝试使用所有可用的内核/并行预测您提供的数据点。在这种情况下,具有多个工作人员的预测生成器可能不会增加任何好处,因为每个工作人员都需要等待轮到其执行或共享可用内核。无论哪种方式,您最终都会获得相同的性能。

    如果您的数据更普遍地使用生成器:

    • 不适合内存。您可以一次批量进行预测,而不是创建一个大型数据数组并调用预测。
    • 需要动态处理,每批可能会发生变化/随机。
    • 不能轻松地存储在 NumPy 数组中,并且除了切片数据点之外还有不同的批处理方式。

    【讨论】:

    • 感谢您的回答。您能否使用所有可用内核提供有关 keras .p​​redict 的链接?那么除了使用GPU(或获得更多CPU)之外,没有其他方法可以减少预测时间吗?
    • 其实不是Keras做的,而是Tensorflow,默认it uses all cores。是的,可以使用 GPU 或更多 CPU 来加快速度。
    猜你喜欢
    • 2020-01-05
    • 2018-11-23
    • 2019-09-16
    • 2019-03-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-16
    相关资源
    最近更新 更多