值错误:无法序列化层 'my_custom_layer'。该层的 __init__ 方法包含不可序列化的参数。
ValueError: Unable to serialize the layer 'my_custom_layer'. The layer has a non-serializable argument in its __init__ method.
ID: tensorflow/keras-model-save-custom-layer
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| TensorFlow 2.10.0 | active | — | — | — |
| Keras 2.10.0 | active | — | — | — |
根因分析
自定义 Keras 层的构造函数包含非 TensorFlow 兼容类型的参数(例如 lambda 函数、文件句柄或不可序列化的对象),导致模型无法保存。
English
A custom Keras layer has a constructor parameter that is not a TensorFlow-compatible type (e.g., a lambda function, a file handle, or a non-serializable object), which prevents model saving.
官方文档
https://www.tensorflow.org/guide/keras/save_and_serialize#custom_objects解决方案
-
在自定义层中重写 get_config() 方法,返回所有可序列化参数的字典。确保每个参数是基本 Python 类型或 TensorFlow 对象。对于复杂对象,转换为可序列化形式(例如存储配置字典)。
-
使用 from_config 类方法从配置字典重建层。这确保加载模型时正确实例化层。
-
如果参数确实不可序列化(例如 lambda),将其重构为可序列化的替代方案,如字符串标识符和映射字典。
无效尝试
常见但无效的做法:
-
75% 失败
Save_weights only saves the weights, not the architecture or custom layer config, so loading requires redefining the model manually.
-
80% 失败
An empty config omits necessary parameters, leading to errors when loading the model due to missing arguments.
-
70% 失败
Global variables break encapsulation and are not serialized, causing the same issue when the model is loaded in a different context.