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}