Functional API 是 Keras 提供的一种灵活的模型构建方式,允许用户通过图层间的连接关系定义复杂模型结构。相比 Sequential 模型,它更适合处理多输入/多输出、共享层等场景。
✅ 优点与适用场景
- 🔁 灵活构建复杂网络拓扑
- 🔄 支持层共享(如双向 RNN)
- 📌 适用于多输入多输出模型
- 🧠 更直观地表达层间依赖关系
📚 核心概念
输入层定义
使用Input(shape=...)
创建输入张量
示例:inputs = Input(shape=(128,))
层连接方式
通过layers.Dense(...)(inputs)
实现
支持嵌套结构:outputs = Dense(64, activation='relu')(Dense(128)(inputs))
模型编译与训练
model = Model(inputs=inputs, outputs=outputs) model.compile(optimizer='adam', loss='sparse_categorical_crossentropy') model.fit(x_train, y_train, epochs=5)
🧪 实战示例
from tensorflow.keras import layers, models
# 定义输入
inputs = layers.Input(shape=(784,))
# 构建网络
x = layers.Dense(64, activation='relu')(inputs)
x = layers.Dense(32, activation='relu')(x)
outputs = layers.Dense(10, activation='softmax')(x)
# 创建模型
model = models.Model(inputs=inputs, outputs=outputs)
model.summary()
📁 相关学习资源
📌 提示:Functional API 与 Sequential 模型并非对立,可结合使用提升开发效率。建议通过 官方教程 深入实践。