【发布时间】: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