iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Functional API

The Keras Functional API is the modern default. You build a graph by calling layers on tensors — supports branches, multi-input/output, residual connections, weight sharing — without subclassing.

Functional API examples

EXAMPLE
import tensorflow as tf
from tensorflow.keras import layers, Model, Input

# 1) Simple MLP
inputs = Input(shape=(28, 28))
x = layers.Flatten()(inputs)
x = layers.Dense(256, activation='relu')(x)
x = layers.Dropout(0.2)(x)
outputs = layers.Dense(10, activation='softmax')(x)
model = Model(inputs, outputs)
model.summary()

# 2) Multi-input model — text + numeric features
text = Input(shape=(100,), name='text', dtype='int32')
nums = Input(shape=(8,),   name='nums')

te = layers.Embedding(10_000, 64)(text)
te = layers.GlobalAveragePooling1D()(te)
ne = layers.Dense(32, activation='relu')(nums)

combined = layers.Concatenate()([te, ne])
out = layers.Dense(1, activation='sigmoid')(combined)
model2 = Model([text, nums], out)

# 3) Multi-output — classification + regression heads share a backbone
base  = layers.Dense(128, activation='relu')(Input(shape=(20,)))
cls   = layers.Dense(3, activation='softmax', name='class')(base)
reg   = layers.Dense(1, name='score')(base)
model3 = Model(base.inputs, [cls, reg])
model3.compile(
    optimizer='adam',
    loss={'class': 'sparse_categorical_crossentropy', 'score': 'mse'},
    loss_weights={'class': 1.0, 'score': 0.3},
    metrics={'class': ['accuracy'], 'score': ['mae']},
)

# 4) Residual block (the ResNet shape)
def res_block(x, filters):
    skip = x
    x = layers.Conv2D(filters, 3, padding='same', activation='relu')(x)
    x = layers.Conv2D(filters, 3, padding='same')(x)
    x = layers.Add()([skip, x])
    return layers.ReLU()(x)

Why it matters

Functional models serialise cleanly (model.to_json(), save / load weights) and integrate with every Keras tool. Reach for subclassing only when you need dynamic logic in call().

Tip: Tweak the snippet with Try it Yourself », then sit the quiz at the bottom of the page.

Example

Example
from tensorflow.keras import layers, Model
inp = layers.Input((784,))
x = layers.Dense(128, activation='relu')(inp)
x = layers.Dropout(0.3)(x)
out = layers.Dense(10, activation='softmax')(x)
model = Model(inp, out)
Try it Yourself »

Discussion

Loading…