Keras 3 API文档 / 模型API / 保存与序列化 / Keras权重文件编辑器

Keras 权重文件编辑器

[源代码]

KerasFileEditor

keras.saving.KerasFileEditor(filepath)

用于检查、编辑和重新保存Keras权重文件的实用工具。

当你在对模型进行架构更改后,需要适配旧的已保存权重文件时,你会发现这个类非常有用。

参数

  • filepath: 要检查和编辑的本地文件路径。

示例

editor = KerasFileEditor("my_model.weights.h5")

# Displays current contents
editor.summary()

# Remove the weights of an existing layer
editor.delete_object("layers/dense_2")

# Add the weights of a new layer
editor.add_object("layers/einsum_dense", weights={"0": ..., "1": ...})

# Save the weights of the edited model
editor.resave_weights("edited_model.weights.h5")

[源代码]

summary 方法

KerasFileEditor.summary()

打印已打开文件的权重结构。


[源代码]

compare 方法

KerasFileEditor.compare(reference_model)

将已打开的文件与参考模型进行比较。

此方法将列出当前打开的文件与提供的参考模型之间的所有不匹配项。

参数

  • reference_model: 用于比较的模型实例。

返回

  • 字典,包含以下键'status''error_count''match_count'。状态可以是'success''error''error_count'是找到的不匹配项的数量。'match_count'是找到匹配权重的数量。

[源代码]

save 方法

KerasFileEditor.save(filepath)

保存编辑后的权重文件。

参数

  • filepath: 保存文件的路径。必须是.weights.h5文件。

[源代码]

rename_object 方法

KerasFileEditor.rename_object(object_name, new_name)

重命名文件中的一个对象(例如,层)。

参数

  • object_name: 字符串,要重命名的对象的名称或路径(例如,"dense_2""layers/dense_2")。
  • new_name: 字符串,对象的名称。

[源代码]

delete_object 方法

KerasFileEditor.delete_object(object_name)

从文件中移除一个对象(例如,层)。

参数

  • object_name: 字符串,要删除的对象的名称或路径(例如,"dense_2""layers/dense_2")。

[源代码]

add_object 方法

KerasFileEditor.add_object(object_path, weights)

向文件中添加一个新对象(例如,层)。

参数

  • object_path: 字符串,要添加的对象的完整路径(例如,"layers/dense_2")。
  • weights: 映射权重名称到权重值(数组)的字典,例如 {"0": kernel_value, "1": bias_value}

[源代码]

delete_weight 方法

KerasFileEditor.delete_weight(object_name, weight_name)

从现有对象中移除一个权重。

参数

  • object_name: 字符串,从中移除权重的对象的名称或路径(例如,"dense_2""layers/dense_2")。
  • weight_name: 字符串,要删除的权重的名称(例如,"0")。

[源代码]

add_weights 方法

KerasFileEditor.add_weights(object_name, weights)

向现有对象添加一个或多个新权重。

参数

  • object_name: 字符串,要添加权重的对象的名称或路径(例如,"dense_2""layers/dense_2")。
  • weights: 映射权重名称到权重值(数组)的字典,例如 {"0": kernel_value, "1": bias_value}