无法在 Keras 2.1.0(使用 Tensorflow 1.3.0)中保存的 Keras 2.4.3(使用 Tensorflow 2.3.0)中加载 Keras 模型

     2023-02-16     193

关键词:

【中文标题】无法在 Keras 2.1.0(使用 Tensorflow 1.3.0)中保存的 Keras 2.4.3(使用 Tensorflow 2.3.0)中加载 Keras 模型【英文标题】:Unable to load Keras model in Keras 2.4.3 (with Tensorflow 2.3.0) that was saved in Keras 2.1.0 (with Tensorflow 1.3.0) 【发布时间】:2020-12-24 16:59:27 【问题描述】:

我正在实现一个带有自定义批量重整化层的 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 发生了什么变化,有没有办法加载旧模型而不会收到此错误?

【问题讨论】:

【参考方案1】:

您不能以这种方式加载模型,因为 keras.models.load_model 将加载已定义的配置,而不是 self_customed。

要克服这个问题,您应该重新加载模型架构并尝试从中加载权重:

model = YourModelDeclaration()
model.load_weights("checkpoint/h5file")

我在自定义 BatchNormalize 时遇到了同样的问题,所以我很确定这是加载它的唯一方法。

【讨论】:

感谢您的回复,但 load_weights 也不起作用。经过一番挖掘,我发现该错误实际上是由保存然后尝试在不同版本的 Keras/Tensorflow 上加载引起的。所以真正的问题是,是否有办法加载保存在旧版本 Keras 中的模型而不会遇到此错误。 显然,您不应该只在不同的版本中保存权重,然后将其加载到较新的版本中。但奇怪的是,即使保存整个模型也不能让你来回移动:D 这似乎是一个常见问题。在这种情况下,我尝试使用其他人创建的模型,但他们没有提供有关他们使用的 Tensorflow/Keras 版本的详细信息。因此,需要进行一些猜测和检查才能使事情正常进行。在我看来,模型加载应该跨版本工作,否则共享模型将非常困难。【参考方案2】:

在 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")

【讨论】:

感谢您的回复,但 load_weights 也不起作用。经过一番挖掘,我发现该错误实际上是由保存然后尝试在不同版本的 Keras/Tensorflow 上加载引起的。所以真正的问题是,是否有办法加载保存在旧版本 Keras 中的模型而不会遇到此错误。 据我了解,保存和加载模型时不能在 Keras/tf 版本之间移动。

tensor.shape 在使用 tf.keras 时返回一个无值列表

】tensor.shape在使用tf.keras时返回一个无值列表【英文标题】:tensor.shapereturnalistofNonevalueswhenusingtf.keras【发布时间】:2021-12-0806:26:40【问题描述】:我有一个函数,它接受一个张量,并使用一个看起来像这样的方程从这个张量的形... 查看详情

Keras 替换输入层

...时间】:2018-09-0720:55:10【问题描述】:我拥有的代码(我无法更改)使用带有my_input_tensor作为input_tensor的Resnet。model1=keras.applications.resnet50.ResNet50(input_tensor=my_input_tensor,weights=\'imagenet\ 查看详情

在 Keras 中使用 LSTM 预测股票(Python 3.7、Tensorflow 2.1.0)

】在Keras中使用LSTM预测股票(Python3.7、Tensorflow2.1.0)【英文标题】:ForecastingstockswithLSTMinKeras(Python3.7,Tensorflow2.1.0)【发布时间】:2020-10-1615:17:03【问题描述】:我正在尝试使用LSTM来预测道琼斯工业平均指数在未来几个月的表现。... 查看详情

TypeError:张量是不可散列的。相反,使用 tensor.ref() 作为键。在 Keras 外科医生

】TypeError:张量是不可散列的。相反,使用tensor.ref()作为键。在Keras外科医生【英文标题】:TypeError:Tensorisunhashable.Instead,usetensor.ref()asthekey.inKerasSurgeon【发布时间】:2020-07-1806:33:11【问题描述】:我正在使用Kerassurgeon模块进行修... 查看详情

AttributeError:“Tensor”对象在自定义损失函数中没有属性“numpy”(Tensorflow 2.1.0)

】AttributeError:“Tensor”对象在自定义损失函数中没有属性“numpy”(Tensorflow2.1.0)【英文标题】:AttributeError:\'Tensor\'objecthasnoattribute\'numpy\'incustomlossfunction(Tensorflow2.1.0)【发布时间】:2020-07-1817:06:16【问题描述】:我想用自定义... 查看详情

如何在 Keras 中将 report_tensor_allocations_upon_oom 添加到 RunOptions

...【发布时间】:2018-09-1421:16:09【问题描述】:我正在尝试使用Keras在GPU上训练神经网络,但出现“资源耗尽:分配张量时出现OOM”错误。它试图分配的特定张量不是很大, 查看详情

keras自定义metrics

参考技术A在keras中操作的均为Tensor对象,因此,需要定义操作Tensor的函数来操作所有输出结果,定义好函数之后,直接将其放在model.compile函数metrics中即可生效:使用方法如下:custommetricsforbinaryclassificationinKeras 查看详情

pytorch基础(代码片段)

1.张量数据类型  比如数字2在pytorch中就是intTensor类型,该维度为0即dim=0,pytorch内部没有自带的string类型表示方法,要用的话只能通过以下两种编码方法表示:one-hot:如猫类别用【01】表示,狗类别用【10】表示embedding:如... 查看详情

分割层输出时,Keras 抛出“Tensor”对象没有属性“_keras_shape”

】分割层输出时,Keras抛出“Tensor”对象没有属性“_keras_shape”【英文标题】:Kerasthrows`\'Tensor\'objecthasnoattribute\'_keras_shape\'`whensplittingalayeroutput【发布时间】:2018-05-1622:16:47【问题描述】:我有一个维度为2*1*300的句子对的句子嵌... 查看详情

使用keras在损失函数中批量逐元素产品

】使用keras在损失函数中批量逐元素产品【英文标题】:Batchelement-wiseproductinlossfunctionwithkeras【发布时间】:2021-02-1621:40:51【问题描述】:我正在尝试在keras中编写一个自定义损失函数,我需要通过中间层的输出(其形状为(batch_si... 查看详情

解决在django中应用keras模型时出现的valueerror("tensor%sisnotanelementofthisgraph."%obj)问题(代码(代码片段)

用keras训练好模型,再在django初始化加载模型,这个过程没有问题,但是在调用到模型执行model.predict()的时候就报错:raiseValueError("Tensor%sisnotanelementofthisgraph."%obj)ValueError:TensorTensor("dense_2/Softmax:0",shape=(?,2),dtype=float32)isno 查看详情

无法使用 Plaidml 在 GPU 上运行 Keras 模型

】无法使用Plaidml在GPU上运行Keras模型【英文标题】:CannotRunKerasModelOnGPUWithPlaidml【发布时间】:2022-01-1020:01:04【问题描述】:我想在我的GPU上运行这个Keras模型,但它在我使用的cpu上运行Plaidml使用我的AMDGPU,plaidml已正确设置并运... 查看详情

如何使用 Tokenizer (Keras)?无法在角色级别生成令牌

】如何使用Tokenizer(Keras)?无法在角色级别生成令牌【英文标题】:HowtouseTokenizer(Keras)?UnabletogeneratetokensonCharacterlevel【发布时间】:2021-05-0503:21:03【问题描述】:目标:字符级矢量化问题:输出不是每个字符/字母的唯一数字,而... 查看详情

keras(tensorconversionrequesteddtypeint32fortensorwithdtypefloat32:'tensor("embe

这个问题出现根本原因是keras以及tensorflow的版本(服务器与本地)不一致通过Python   importkeras,tensorflow   keras.__version__    tensorflow.__version__查看版本然后通过pipuninstallXXXXpipin 查看详情

无法使用 intellij 13.1.2 在 grails 2.3.8 中设置断点

】无法使用intellij13.1.2在grails2.3.8中设置断点【英文标题】:unabletosetbreakpointingrails2.3.8withintellij13.1.2【发布时间】:2014-07-0204:47:25【问题描述】:我正在尝试在grails项目中设置断点(grails版本:2.3.8,Intellij版本:13.1.2),但是所... 查看详情

无法在 Google Cloud DL VM 中使用 Theano Keras 后端

】无法在GoogleCloudDLVM中使用TheanoKeras后端【英文标题】:UnabletouseTheanoKerasbackendinsideGoogleCloudDLVM【发布时间】:2019-07-0823:41:02【问题描述】:我正在尝试使用Theano后端而不是默认的Tensorflow后端在GoogleCloudDeepLearningVM实例上运行Keras... 查看详情

制作自定义 Keras 层时不能使用未知的输入尺寸(批量大小)

】制作自定义Keras层时不能使用未知的输入尺寸(批量大小)【英文标题】:Can\'tUseUnknownInputDims(BatchSize)WhenMakingCustomKerasLayer【发布时间】:2019-12-2702:31:37【问题描述】:我正在尝试在Keras(后端TensorFlow)中构建一个自定义层,... 查看详情

使用 TensorFlow 2.0 Alpha 时无法在 Tensorboard 中看到 keras 模型图

】使用TensorFlow2.0Alpha时无法在Tensorboard中看到keras模型图【英文标题】:UnabletoseekerasmodelgraphinTensorboardwhenusingTensorFlow2.0Alpha【发布时间】:2019-08-0402:33:06【问题描述】:我正在尝试在TensorFlow2.0alpha上进行自定义训练,同时我正在... 查看详情