在Keras中,Sequential和Functional API都可以用来建立神经网络模型,但是Functional API更加灵活,可以处理更加复杂的模型结构,而且还能够方便地处理多输入和多输出情况。因此,Kera的Functional API在表现上要比Sequential更好。
下面是一个非常简单的使用Functional API建立模型的例子:
from keras.layers import Input, Dense
from keras.models import Model
inputs = Input(shape=(784,))
hidden1 = Dense(64, activation='relu')(inputs)
hidden2 = Dense(64, activation='relu')(hidden1)
outputs = Dense(10, activation='softmax')(hidden2)
model = Model(inputs=inputs, outputs=outputs)
在这个例子中,我们首先使用Input层定义了模型的输入形状,然后分别使用Dense层定义了两个隐藏层和一个输出层,最后通过Model函数将输入和输出连接起来,创建出了完整的模型。
可以看到,Functional API的使用方式非常直观和简单,而且能够灵活地拓展模型结构,因此更加适用于较为复杂的场景。