Keras 函数式 API 提供了一种灵活的方式来构建和训练模型。它允许你以编程的方式定义模型,而不是使用预定义的层和模型。
快速开始
导入必要的库
from keras.layers import Input, Dense, Flatten from keras.models import Model
定义输入层
input_tensor = Input(shape=(input_shape,))
添加中间层
x = Dense(64, activation='relu')(input_tensor) x = Flatten()(x)
定义输出层
output_tensor = Dense(num_classes, activation='softmax')(x)
创建模型
model = Model(inputs=input_tensor, outputs=output_tensor)
编译模型
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
训练模型
model.fit(x_train, y_train, epochs=epochs, batch_size=batch_size)
评估模型
model.evaluate(x_test, y_test)
保存模型
model.save('/path/to/my/model.h5')
加载模型
model = load_model('/path/to/my/model.h5')
更多资源
想要了解更多关于 Keras 函数式 API 的信息,请访问我们的 Keras 官方文档。
神经网络