我有一个训练有素的keras模型,并且我试图仅使用CPU运行预测。我希望此操作尽快完成,所以我想我将predict_generator
与多个工作人员一起使用。我的预测张量的所有数据都预先加载到内存中。仅供参考,数组是张量的列表,第一个张量的形状为[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外)?
答案 0 :(得分:1)
当您仅调用.predict
时,Keras 已经尝试使用所有可用的内核/并行预测您提供的数据点。在这种情况下,具有多个工作线程的预测生成器可能不会增加任何好处,因为每个工作线程将需要等待轮到执行或共享可用内核。无论哪种方式,您最终都会获得相同的性能。
如果您的数据使用生成器,则更为常见。