DeployU
Interviews / AI & MLOps / What is the difference between `tf.keras.Model` and `tf.keras.Sequential`?

What is the difference between `tf.keras.Model` and `tf.keras.Sequential`?

conceptual Keras API Interactive Quiz Code Examples

The Scenario

You are building a new model in Keras and need to decide whether to use the Sequential model or the Model class (functional API).

The Challenge

Explain the difference between the Sequential model and the Model class. When would you use one over the other?

Wrong Approach

A junior engineer might think that they are interchangeable. They might not be aware of the flexibility of the `Model` class or the limitations of the `Sequential` model.

Right Approach

A senior engineer would know that the `Sequential` model is a simpler way to build a model, but that the `Model` class provides much more flexibility. They would be able to explain that the `Sequential` model is only suitable for simple, linear stacks of layers, while the `Model` class can be used to build any kind of model.

tf.keras.Sequential

The Sequential model is a container for a linear stack of layers. It is the simplest way to build a model in Keras.

When to use it:

  • When you have a simple, linear stack of layers.
  • When you want a quick and easy way to build a model.

Example:

import tensorflow as tf

model = tf.keras.Sequential([
    tf.keras.layers.Dense(128, activation="relu"),
    tf.keras.layers.Dense(10, activation="softmax")
])

tf.keras.Model (Functional API)

The Model class allows you to build more complex models with multiple inputs and outputs, and with shared layers. It is more flexible than the Sequential model.

When to use it:

  • When you have a more complex model with multiple inputs or outputs.
  • When you need to share layers between different parts of the model.
  • When you are building a model with a non-linear topology.

Example:

import tensorflow as tf

input_tensor = tf.keras.Input(shape=(784,))
x = tf.keras.layers.Dense(128, activation="relu")(input_tensor)
output_tensor = tf.keras.layers.Dense(10, activation="softmax")(x)

model = tf.keras.Model(inputs=input_tensor, outputs=output_tensor)

Comparison

FeatureSequential ModelModel Class (Functional API)
FlexibilityLimited, only works for linear stacks of layers.Very flexible, can be used to build any kind of model.
Ease of UseVery easy to use.More complex to use than the Sequential model.
Use CasesSimple classification and regression tasks.Complex models with multiple inputs/outputs, shared layers, etc.

Practice Question

You are building a model with two inputs and two outputs. Which of the following would you use?