[Keras] 使用Keras调用多GPU时出现无法保存模型的解决方法

在使用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

[Keras] 使用Keras调用多GPU,并保存模型

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值