# 值错误：无法序列化层 'my_custom_layer'。该层的 __init__ 方法包含不可序列化的参数。

- **ID:** `tensorflow/keras-model-save-custom-layer`
- **领域:** tensorflow
- **类别:** type_error
- **错误码:** `EMSS`
- **验证级别:** ai_generated
- **修复率:** 85%

## 根因

自定义 Keras 层的构造函数包含非 TensorFlow 兼容类型的参数（例如 lambda 函数、文件句柄或不可序列化的对象），导致模型无法保存。

## 版本兼容性

| 版本 | 状态 | 引入 | 弃用 |
|------|------|------|------|
| TensorFlow 2.10.0 | active | — | — |
| Keras 2.10.0 | active | — | — |

## 解决方案

1. ```
   在自定义层中重写 get_config() 方法，返回所有可序列化参数的字典。确保每个参数是基本 Python 类型或 TensorFlow 对象。对于复杂对象，转换为可序列化形式（例如存储配置字典）。
   ```
2. ```
   使用 from_config 类方法从配置字典重建层。这确保加载模型时正确实例化层。
   ```
3. ```
   如果参数确实不可序列化（例如 lambda），将其重构为可序列化的替代方案，如字符串标识符和映射字典。
   ```

## 无效尝试

- **** — Save_weights only saves the weights, not the architecture or custom layer config, so loading requires redefining the model manually. (75% 失败率)
- **** — An empty config omits necessary parameters, leading to errors when loading the model due to missing arguments. (80% 失败率)
- **** — Global variables break encapsulation and are not serialized, causing the same issue when the model is loaded in a different context. (70% 失败率)
