The Keras Functional API provides a way to create models in a more flexible and modular way. It allows you to define the layers of your model as a sequence or a graph of layers, which can be connected in various ways.
Key Features
- Modularity: Define layers as building blocks and connect them in various configurations.
- Flexibility: Suitable for complex models where you need to define custom layers or connections.
- Reusability: Layers can be reused across different models.
Basic Usage
Here's a simple example of how to use the Functional API to create a model:
from keras.models import Model
from keras.layers import Input, Dense
# Define the input
input_tensor = Input(shape=(32,))
# Define the first layer
x = Dense(64, activation='relu')(input_tensor)
# Define the second layer
output_tensor = Dense(10, activation='softmax')(x)
# Create the model
model = Model(inputs=input_tensor, outputs=output_tensor)
Layers
Keras provides a wide range of layers that can be used in the Functional API. Here are some commonly used layers:
- Dense: Fully connected layer.
- Conv2D: Convolutional layer for 2D data (e.g., images).
- MaxPooling2D: Pooling layer for 2D data.
- Dropout: Dropout layer for regularization.
Model Compilation
After defining the model, you need to compile it with an optimizer, a loss function, and metrics:
model.compile(optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy'])
Model Training
You can train the model using the fit
method:
model.fit(x_train, y_train, epochs=10, batch_size=32)
Further Reading
For more information on the Keras Functional API, you can refer to the official documentation.
Keras Model Architecture