← Back to Python

All Topics

Advertisement

Learn/Python/Deep Learning

Keras Sequential

Topic: Keras

Advertisement

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

  1. Build simple feedforward network
  2. Add multiple layers with different activations
  3. Compile with different optimizers
  4. Train with validation data
  5. Make predictions on test set

Advertisement

Advertisement

Need More Practice?

Get personalized Python help from ChatWhole's AI-powered platform.

Get Expert Help →