在使用keras 的并行多路GPU时出现了模型无法
保存,在使用单个GPU时运行完全没有问题。运行出现can't pickle的问题
随后在网上找了很多解决方法。下面列举一些我实验成功的方法。
方法一
class ParallelModelCheckpoint(ModelCheckpoint):
def __init__(self,model,filepath, monitor='val_loss', verbose=0,
save_best_only=False, save_weights_only=False,
mode='auto', period=1):
self.single_model = model
super(ParallelModelCheckpoint,self).__init__(filepath, monitor, verbose,save_best_only, save_weights_only,mode, period)
def set_model(self, model):
super(ParallelModelCheckpoint,self).set_model(self.single_model)
check_point = ParallelModelCheckpoint(single_model ,'best.hd5')
在这里需要解释一下 这个single_model 时没有进行并行的model
model = Model(inputs = [inputs], outputs = [conv10])
parallel_model = multi_gpu_model(model, gpus=2)
在这里第一就是single_model.直接用这个model checkpoint 就可以了 亲测有效
方法二
original_model = ...
parallel_model = multi_gpu_model(original_model, gpus=n)
class MyCbk(keras.callbacks.Callback):
def __init__(self, model):
self.model_to_save = model
def on_epoch_end(self, epoch, logs=None):
self.model_to_save.save('model_at_epoch_%d.h5' % epoch)
cbk = MyCbk(original_model)
parallel_model.fit(..., callbacks=[cbk])
同理这里也是一样的。其实在上面两种方法中可以发现,基本都是在checkpoint 问题上都是使用了单个model进行运行的。
意思就是直接使用传入方法keras.utils.multi_gpu_model(model, gpus)
中的model
即可,而不要使用返回的parallel_model
,
参考网站
call_back_error when using multi_gpu_model
Multi_gpu in keras not working with callbacks, but works fine if callback is removed