keras multi_gpu_model saved_model 无法在 TF2 代码中加载模型

keras multi_gpu_model saved_model failed to load model in TF2 code

我已经使用 tensorflow 1.13/1.14 训练了 multi_gpu_model 并使用 keras.model.save('<.hdf5>') 保存了它们。 现在,在迁移到 tensorflow 2.4.1 之后,其中 Keras 被集成为 tensorflow.keras,我不能像以前那样 tensorflow.keras.models.load_model,因为以下错误:

AttributeError: module 'tensorflow.python.keras.backend' has no attribute 'slice'

尝试导入 keras.models.load_model 并尝试不同版本的 keras (2.2.4 -> 2.4.1) 和 tensorflow (2.2 -> 2.4.1) 后,我无法 load_model我的 .hdf5 文件使用我的 TF 2.2+ 代码。

我知道在 TF 2.X + 中我们可以通过实施“策略”范围来使用分布式机器进行训练,它确实有效,但我需要很多“旧”模型使用现在正在迁移到 TF 2.4.1

的相同代码库

显然问题不在于 TF 版本,而是我在 TF 1.X 代码版本上保存模型的方式。

我使用 keras.multi_gpu_model class 进行训练和保存,但这种做法是错误的,正如 Keras 文档中明确指出的那样:

"要保存多GPU模型,使用.save(fname).save_weights(fname) 使用模板模型(您传递给 multi_gpu_model 的参数), 而不是 multi_gpu_model."

返回的模型

于是,想出了一个模型转换的方法,使用TF1.X代码,被采纳:

  1. 从头开始构建模型,即 new_model
  2. 从multi_gpu_model加载你预训练的权重,即'old_model'
  3. 将你的 old_model 的权重,即 old_model.layers[3](由于 multi_gpu_model 的错误用法)复制到你的 new_model
  4. new_model 另存为 .hdf5 文件
  5. 到处使用 new_model.hdf5 - TF 1.X 和 TF 2.X