我正在实现一个带有自定义批次归一化层的Keras模型,该层具有4个权重(beta、gamma、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 中发生了什么变化,有没有办法在不收到此错误的情况下加载旧模型?