Skip to main content
TensorFlow Introduction
CHAPTER 10 Intermediate

Working with TensorFlow Keras API

Updated: May 16, 2026
6 min read

# CHAPTER 10

Working with TensorFlow Keras API

1. Introduction

Until now, we have used the Sequential API. It is incredibly easy to read, but it has a massive limitation: it forces data to move in a single, straight line. What if you want to build an advanced model that takes an Image *and* Text as inputs simultaneously? What if you want a model that outputs a Regression prediction *and* a Classification prediction at the same time? To build these cutting-edge architectures, we must graduate to the Keras Functional API.

2. Learning Objectives

By the end of this chapter, you will be able to:
  • Explain the limitations of the Sequential API.
  • Understand the syntax of the Keras Functional API.
  • Build models with non-linear topologies (branching).
  • Build a Multi-Input neural network.
  • Utilize the Model class.

3. The Functional API Syntax

In the Sequential API, you pass a list of layers. In the Functional API, you define each layer as an independent function, and you explicitly pass the output of the previous layer into it, like connecting pipes.

Let's recreate the simple digit classifier using the Functional API to see the difference.

python
123456789101112131415161718192021
import tensorflow as tf
from tensorflow.keras.layers import Input, Dense, Flatten
from tensorflow.keras.models import Model

# 1. Define the Input explicitly
# Notice how we save the layer to a variable named 'inputs'
inputs = Input(shape=(28, 28))

# 2. Connect the layers
# We call Flatten()(inputs) to pipe the data from 'inputs' into the Flatten layer.
x = Flatten()(inputs)
x = Dense(128, activation='relu')(x)
x = Dense(64, activation='relu')(x)

# 3. Define the Output layer
outputs = Dense(10, activation='softmax')(x)

# 4. Bind the Inputs and Outputs into a Model
model = Model(inputs=inputs, outputs=outputs)

model.summary()

*It looks a bit stranger, but notice how we explicitly control exactly where the data x flows at every step.*

4. Non-Linear Topologies (Branching)

Because we control the data flow, we can split the data into two different paths! This is the core concept behind complex modern architectures like ResNets.
python
12345678910111213
inputs = Input(shape=(10,))

# Branch A
path_a = Dense(32, activation='relu')(inputs)

# Branch B
path_b = Dense(32, activation='relu')(inputs)

# Merge the branches back together!
merged = tf.keras.layers.concatenate([path_a, path_b])

outputs = Dense(1, activation='sigmoid')(merged)
model_branched = Model(inputs=inputs, outputs=outputs)

5. Multi-Input Models

Imagine you are predicting house prices. You have tabular data (Square footage, Bedrooms) AND an image of the house. You need a Multi-Input model!
python
1234567891011121314151617181920
from tensorflow.keras.layers import concatenate

# Input 1: The Tabular Data (Numbers)
num_input = Input(shape=(5,), name="tabular_data")
x1 = Dense(16, activation='relu')(num_input)

# Input 2: The Image Data
img_input = Input(shape=(64, 64, 3), name="image_data")
x2 = Flatten()(img_input)
x2 = Dense(32, activation='relu')(x2)

# Merge them together
combined = concatenate([x1, x2])

# Final processing and output
z = Dense(16, activation='relu')(combined)
output = Dense(1, activation='linear', name="price_prediction")(z)

# Create the Model by passing a LIST of inputs
complex_model = Model(inputs=[num_input, img_input], outputs=output)

6. Training Multi-Input Models

When you call model.fit() on a multi-input model, you simply pass a Python list containing your multiple datasets!
python
123456
# Assuming X_train_tabular and X_train_images are already prepared
# complex_model.fit(
#     [X_train_tabular, X_train_images],  # Provide both inputs
#     y_train_prices, 
#     epochs=10
# )

7. Model Subclassing (Advanced)

For absolute bleeding-edge researchers, Keras offers a third way to build models: Subclassing. You write standard Object-Oriented Python classes (class MyModel(tf.keras.Model):) and write a custom call() method to dictate the forward pass. This is complex and generally not recommended for beginners, but you will see it in PyTorch-style codebases.

8. Common Mistakes

  • Forgetting the Input Layer: In the Sequential API, you can sometimes get away with omitting the Input layer. In the Functional API, the Input() object is absolutely mandatory. It is the starting pipe for the entire network.
  • Variable Name Confusion: In Functional API code, you often see x = Dense()(x). Beginners get confused because the variable is constantly overwriting itself. This is standard practice in Deep Learning to save memory, as you don't need to save the intermediate outputs of every hidden layer into a unique variable.

9. Best Practices

  • Name your layers: In multi-input/output models, use the name="" parameter (e.g., Dense(10, name="price_output")). When you print the model.summary(), having named layers makes debugging a massive architecture 100x easier.

10. Exercises

  1. 1. Rewrite a simple 2-layer Sequential model into Functional API syntax.
  1. 2. In the Functional API, what specific Keras class is used at the very end to bind the inputs and outputs together?

11. MCQ Quiz with Answers

Question 1

What is the primary limitation of the Keras Sequential API?

Question 2

In the Functional API, how do you combine data from two different parallel layers (branches)?

12. Interview Questions

  • Q: Explain the syntactical difference between defining a layer in the Sequential API vs the Functional API.
  • Q: Give a real-world business example of a scenario where a Multi-Input model would be required over a standard Sequential model.

13. FAQs

Q: Should I completely stop using the Sequential API? A: No! The Sequential API is clean, readable, and perfect for 90% of standard tasks (like simple image classifiers or tabular regressions). Only use the Functional API when your architecture demands it.

14. Summary

The Keras Functional API transforms TensorFlow from a simple tool into a professional engineering framework. By treating layers as connectable pipes, we can design massive, non-linear architectures capable of ingesting multiple data types and outputting complex predictions simultaneously.

15. Next Chapter Recommendation

We now know how to build complex architectures. It is time to tackle the hardest problem in AI: Vision. Why do simple Dense layers fail at recognizing complex photos? In Chapter 11: Image Classification with CNNs, we will learn the architecture that revolutionized Artificial Intelligence.

Finish this Chapter

Save your progress on your learning path and prepare for coding interview challenges.

Discussion

Join the discussion

Log in or create a free account to participate.

Sort: ·