C.W.K.
Stream
Lesson 02 of 07 · published

The Pattern

~9 min · functional

Level 0Keras Apprentice
0 XP0/97 lessons0/20 achievements
0/120 XP to next level120 XP to go0% complete

Three steps, every time

The Functional API follows a simple three-step pattern, and once it clicks it never changes no matter how complex the graph gets:

  1. Define inputs with keras.Input(shape=...) — this creates a symbolic tensor, a placeholder that carries shape and dtype but no data yet.
  2. Chain layers by calling them on tensors: x = Layer()(x). Each call records an edge in the graph.
  3. Create model with keras.Model(inputs, outputs) — Keras traces backward from outputs to inputs and freezes the DAG.

The double-duty parentheses

The single idea that makes this whole API feel natural: every layer is a callable. The Code block below shows the parentheses doing double duty — layers.Dense(256, activation="relu") constructs a layer object, and the second (inputs) calls it on a tensor. Construction allocates the weights; calling wires the layer into the graph and returns a new symbolic tensor.

That separation is the payoff. Because constructing and calling are two distinct steps, you can hold a layer instance in a variable and call it more than once — and every call reuses the same weights. That single fact is what makes shared layers (next lessons) and weight tying possible at all. Notice too that nothing here runs a forward pass on real data: you're describing a graph, not executing it, which is exactly why the result is serializable.

Code

The three-step Functional pattern (MNIST classifier)·python
import keras
from keras import layers

# Step 1: Define input
inputs = keras.Input(shape=(784,))

# Step 2: Chain layers
x = layers.Dense(256, activation="relu")(inputs)
x = layers.Dropout(0.3)(x)
x = layers.Dense(128, activation="relu")(x)
outputs = layers.Dense(10, activation="softmax")(x)

# Step 3: Create model
model = keras.Model(inputs=inputs, outputs=outputs, name="my_classifier")
model.summary()

External links

Exercise

Convert your MNIST Sequential model to Functional. Verify model.summary() looks identical. Then create a shared Dense layer and apply it to two different inputs — confirm both calls share weights via len(model.weights).

Progress

Progress is local-only — sign in to sync across devices.
Spotted a bug or have feedback on this page?Report an Issue

Comments 0

🔔 Reply notifications (sign in)
Sign inPlease sign in to comment.

No comments yet — be the first.