Skip to content
TensorFlow

Keras Model

Build models with Sequential and the functional API.

By EZ4Code Team
kerasmodel

Code

import tensorflow as tf

# Sequential for linear stacks
seq_model = tf.keras.Sequential([
    tf.keras.layers.Dense(128, activation="relu", input_shape=(784,)),
    tf.keras.layers.Dropout(0.2),
    tf.keras.layers.Dense(10, activation="softmax"),
])

# Functional API for flexible topology
inputs = tf.keras.Input(shape=(784,))
x = tf.keras.layers.Dense(128, activation="relu")(inputs)
x = tf.keras.layers.Dropout(0.2)(x)
outputs = tf.keras.layers.Dense(10, activation="softmax")(x)
func_model = tf.keras.Model(inputs, outputs, name="mlp")

# Subclassing for full control
class MLP(tf.keras.Model):
    def __init__(self):
        super().__init__()
        self.d1 = tf.keras.layers.Dense(128, activation="relu")
        self.drop = tf.keras.layers.Dropout(0.2)
        self.d2 = tf.keras.layers.Dense(10, activation="softmax")

    def call(self, x, training=False):
        x = self.d1(x)
        x = self.drop(x, training=training)
        return self.d2(x)

subclass_model = MLP()
subclass_model.build((None, 784))

Explanation

Sequential is the simplest API for stacks of layers, while the functional API supports multi-input or multi-output topologies via keras.Input and layer calls. Subclassing keras.Model gives full control over the forward pass and custom training logic. All three produce a model object with the same fit/predict API.

More TensorFlow Snippets