如何解决无法加载在Keras 2.1.0带有Tensorflow 1.3.0中保存的Keras 2.4.3带有Tensorflow 2.3.0中的Keras模型
我正在用自定义的批量重新规范化层实现Keras模型,该层具有4个权重(β,γ,running_mean和running_std)和3个状态变量(r_max,d_max和t):
self.gamma = self.add_weight(shape = shape,#NK - shape = shape
initializer=self.gamma_init,regularizer=self.gamma_regularizer,name='{}_gamma'.format(self.name))
self.beta = self.add_weight(shape = shape,#NK - shape = shape
initializer=self.beta_init,regularizer=self.beta_regularizer,name='{}_beta'.format(self.name))
self.running_mean = self.add_weight(shape = shape,#NK - shape = shape
initializer='zero',name='{}_running_mean'.format(self.name),trainable=False)
# Note: running_std actually holds the running variance,not the running std.
self.running_std = self.add_weight(shape = shape,initializer='one',name='{}_running_std'.format(self.name),trainable=False)
self.r_max = K.variable(np.ones((1,)),name='{}_r_max'.format(self.name))
self.d_max = K.variable(np.zeros((1,name='{}_d_max'.format(self.name))
self.t = K.variable(np.zeros((1,name='{}_t'.format(self.name))
当我对模型进行检查时,仅保存了gamma,beta,running_mean和running_std(按预期),但是当我尝试加载模型时,出现此错误:
Layer #1 (named "batch_renormalization_1" in the current model) was found to correspond to layer batch_renormalization_1 in the save file. However the new layer batch_renormalization_1 expects 7 weights,but the saved weights have 4 elements.
因此,看起来模型希望所有7个权重都成为保存文件的一部分,即使其中一些权重是状态变量也是如此。
关于如何解决此问题的任何见解?
编辑:我意识到问题在于模型已经过训练并保存在Keras 2.1.0(带有Tensorflow 1.3.0后端)上,并且仅在使用加载模型时出现错误Keras 2.4.3(使用Tensorflow 2.3.0后端)。我可以使用Keras将模型加载到2.1.0。
真正的问题是-Keras / Tensorflow中发生了什么变化,有没有办法加载旧模型而不会收到此错误?
解决方法
您不能以这种方式加载模型,因为keras.models.load_model将加载已定义的配置,而不是自定义的配置。
要克服这个问题,您应该重新加载模型架构,并尝试从中加载load_weights:
model = YourModelDeclaration()
model.load_weights("checkpoint/h5file")
我自定义BatchNormalize时遇到相同的问题,因此我可以肯定这是加载它的唯一方法。
,在Keras中,有两种保存模型状态的方法。
您可以调用model.save()
和model.save_weights()
函数。
model.save()
保存整个模型,包括权重和渐变。在您的情况下,此方法将保存4个权重和3个状态变量。您只需使用load_model("path.h5")
方法即可恢复模型。
model.save_weights()
函数仅保存模型的权重,而根本不保存结构。这里要注意的重要事情是 Keras检查点回调在幕后使用model.save_weights()
方法。如果要使用检查点权重,则必须实例化模型结构model = customModel()
,然后将权重加载到其中model.load_weights("checkpoint.h5")
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。