Creating a model using the Sequential API in Keras is straightforward. The Sequential API allows you to create a linear stack of layers where each layer has exactly one input tensor and one output tensor. Here's how you can create a simple neural network model using the Sequential API:
import tensorflow.keras as keras
# Initialize a Sequential model
model = keras.Sequential()
# Add layers to the model
model.add(keras.layers.Dense(units=64, activation='relu', input_shape=(784,))) # Input layer
model.add(keras.layers.Dense(units=128, activation='relu')) # Hidden layer
model.add(keras.layers.Dense(units=10, activation='softmax')) # Output layer
# Compile the model
model.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])
# Print model summary
model.summary()?
In this example :* We first import the Keras library (
tensorflow.keras
).
* We initialize a Sequential model using
keras.Sequential()
.
* We add layers to the model using the
add()
method. We add a
Dense
layer as the input layer with 64 units,
ReLU
activation function, and input shape (
784
,). Then, we add another
Dense
layer as a hidden layer with
128 units
and
ReLU
activation function. Finally, we add a
Dense
layer as the output layer with 10 units (assuming it's a classification task) and softmax activation function.
* We compile the model using the
compile()
method, where we specify the optimizer (in this case, '
adam
'), the loss function (categorical crossentropy for multi-class classification), and the evaluation metric ('accuracy').
* We print the summary of the model using the
summary()
method, which provides information about the layers, output shapes, and parameters of the model.