Introduction
Keras Sequential API provides a simple way to build neural networks layer by layer in a linear stack.
Creating a Sequential Model
from tensorflow import keras
from tensorflow.keras import layers
model = keras.Sequential([
layers.Dense(64, activation='relu', input_shape=(784,)),
layers.Dense(32, activation='relu'),
layers.Dense(10, activation='softmax')
])
model.summary()
Adding Layers
model = keras.Sequential()
model.add(layers.Dense(64, activation='relu', input_shape=(784,)))
model.add(layers.Dense(32, activation='relu'))
model.add(layers.Dense(10, activation='softmax'))
# Or insert at specific position
model.insert(1, layers.Dropout(0.2))
Compiling Model
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)
# Custom optimizer settings
model.compile(
optimizer=keras.optimizers.Adam(learning_rate=0.001),
loss='sparse_categorical_crossentropy',
metrics=['accuracy']
)
Training Model
model.fit(
x_train, y_train,
epochs=10,
batch_size=32,
validation_split=0.2,
callbacks=[keras.callbacks.EarlyStopping(patience=2)]
)
Making Predictions
# Predict classes
predictions = model.predict(x_test)
predicted_classes = np.argmax(predictions, axis=1)
# Get model output
output = model(x_test) # Functional call
Practice Problems
- Build simple feedforward network
- Add multiple layers with different activations
- Compile with different optimizers
- Train with validation data
- Make predictions on test set