你能解释一下keras模型中tensorflow加载和hdf5加载之间的区别吗

Can you explain difference between tensorflow loading and hdf5 loading in keras model

我试图加载我在 training.So 期间保存的 keras 模型 我去了 keras documentation 我看到这个的地方。

Only topological loading (by_name=False) is supported when loading weights from the TensorFlow format. Note that topological loading differs slightly between TensorFlow and HDF5 formats for user-defined classes inheriting from tf.keras.Model: HDF5 loads based on a flattened list of weights, while the TensorFlow format loads based on the object-local names of attributes to which layers are assigned in the Model's constructor.

你能解释一下上面那个吗?

为清楚起见,让我们考虑两种情况。
案例一:简单模型,and
案例 2:使用了从 tf.keras.Model 继承的用户定义 类 的复杂模型。

案例 1:简单模型(如 keras 功能模型和顺序模型)

当您保存模型权重(使用 model.save_weights)然后加载权重(使用 model.load_weights)时,默认情况下 load_weights 方法使用拓扑加载。 Tensorflow saved_model ('tf') 格式和 'h5' 格式也是如此。例如,

loadedh5_model.load_weights('./MyModel_h5.h5') 
# the line above is same as the line below (as second and third arguments are default)
#loadedh5_model.load_weights('./MyModel_h5.h5',by_name=False, skip_mismatch=False)

如果您想加载已保存模型的特定层的权重,则需要使用by_name=True。有些用例需要这种类型的加载。

loadedh5_model.load_weights('./MyModel_h5.h5',by_name=True, skip_mismatch=False)

案例 2:复杂模型(如 Keras 子类模型)

截至目前,仅当在模型创建中使用从 tf.keras.Model 继承的用户定义 类 时,才支持 'tf' 格式。

Only topological loading (by_name=False) is supported when loading weights from the TensorFlow format. Note that topological loading differs slightly between TensorFlow and HDF5 formats for user-defined classes inheriting from tf.keras.Model: HDF5 loads based on a flattened list of weights, while the TensorFlow format loads based on the object-local names of attributes to which layers are assigned in the Model's constructor.

主要原因是h5格式和tf格式的权重。 例如,考虑 Case 1,其中 HDF5 加载基于扁平化的权重列表。重量加载没有任何错误。但是,在 Case 2 中,模型具有 user defined classes,这需要不同的方法,而不仅仅是加载扁平权重。为了处理自定义 类、'tf' 格式的权重分配,根据模型构造函数中分配给层的属性的对象本地名称加载权重。

keras官网上提到的下面这段话,进一步说明

When loading a weight file in TensorFlow format, returns the same status object as tf.train.Checkpoint.restore. When graph building, restore ops are run automatically as soon as the network is built (on first call for user-defined classes inheriting from Model, immediately if it is already built).

另一点要理解的是keras FunctionalSequential模型是层的静态图,可以毫无问题地使用扁平权重。 Keras 子类模型(如我们的案例 2)是一段 Python 代码(一种调用方法)。没有图层图。因此,一旦使用自定义 类 构建网络,恢复操作就是 运行 更新状态对象。希望能帮助到你。