参考资料:
keras官方文档中文版:https://keras.io/zh/getting-started/functional-api-guide/
tf官方文档:https://tensorflow.google.cn/guide/keras#functional_api
图片来自:https://blog.csdn.net/zjw642337320/article/details/81204560
Keras 函数式 API
Keras 函数式 API 是定义复杂模型(如多输出模型、有向无环图,或具有共享层的模型)的方法。
函数式API编程的特点:
上一篇文章中提到的全连接神经网络模型,用函数式编程的话:
构建复杂的模型拓扑指的是:
- 网络层的实例是可调用的,它以张量为参数,并且返回一个张量
- 输入和输出均为张量,它们都可以用来定义
tf.keras.Model实例
- 这样的模型同 Keras 的 Sequential 模型一样,都可以被训练
- 多输入模型,
- 多输出模型,
- 具有共享层的模型(同一层被调用多次),
- 具有非序列数据流的模型(例如,剩余连接)。
上篇文章中提到的全连接神经网络模型:https://blog.csdn.net/weixin_42483560/article/details/84951612
用函数式编程的实现代码如下:
from keras.layers import Input, Dense
from keras.models import Model
# 定义训练样本
data = np.random.random((1000, 32))
labels = np.random.random((1000, 10))
# 这部分返回一个张量
inputs = Input(shape=(784,))
# 层的实例是可调用的,它以张量为参数,并且返回一个张量
x = Dense(64, activation='relu')(inputs)
x = Dense(64, activation='relu')(x)
predictions = Dense(10, activation='softmax')(x)
# 这部分创建了一个包含输入层和三个全连接层的模型
model = Model(inputs=inputs, outputs=predictions)
model.compile(optimizer='rmsprop',
loss='categorical_crossentropy',
metrics=['accuracy'])
model.fit(data, labels) # 开始训练
下篇文章会整理一个用函数式API编程写的多输入多输出网络的实例。
填坑:函数式API编程写的多输入多输出网络(Text-CNN网络)的实例:https://blog.csdn.net/weixin_42483560/article/details/89552490