Keras API Fundamentals
8 min read
Welcome to the sweet spot of Deep Learning. If TensorFlow is the engine block of a car—powerful, heavy, and greasy—Keras is the steering wheel, dashboard, and heated seats. It makes driving the car actually possible for humans.
In this module, we are moving away from raw math operations and into Layers and Models.
1. Introduction to tf.keras: The High-Level API 🧠
Definition
tf.keras is TensorFlow's high-level API for building and training deep learning models. It provides Pythonic, object-oriented abstractions (classes and functions) for neural networks, rather than forcing you to manually manage graph execution or variable scopes.
The Problem: Why not just use raw TensorFlow?
Imagine you want to build a house.
- Raw TensorFlow: You are given atoms, molecules, and physics equations. You have to figure out how to bond carbon atoms to create wood before you can build a wall.
- The Struggle: In early versions of TensorFlow (v1.x), you had to manually initialize weights, manage session graphs, and calculate matrix multiplications by hand. It was verbose and extremely prone to shape-mismatch errors.
The Solution: Keras to the Rescue
Keras gives you pre-fabricated walls, windows, and doors (Layers). You just snap them together.
Since TensorFlow 2.0, Keras is the official high-level API. It is deeply integrated, meaning you get the ease of use of Keras with the scalability of TensorFlow.
Interesting Fact: Keras was originally developed by François Chollet. He created it because he needed a tool to help him win data science competitions faster. It was designed for "human beings, not machines."
Industry Standard
In production environments today, 95% of model code is written in Keras code. You only drop down to "low-level" TensorFlow if you are inventing a mathematically new layer that doesn't exist yet.
2. The Sequential API: Building Simple Linear Models 🥞
Definition
The Sequential API (tf.keras.Sequential) is a way to create models by stacking layers linearly, one after the other. It implies that every layer has exactly one input tensor and one output tensor.
The Problem
You want to build a standard feed-forward neural network. Data goes in one end, flows through a few processing steps, and comes out the other end as a prediction. Writing a custom Class for this boilerplate flow is unnecessary work.
The Solution
Use Sequential. Think of it like a stack of pancakes or a cafeteria line. You start with the tray (Input), add a main course (Hidden Layer), and end with dessert (Output Layer).
When NOT to use it: If your model needs multiple inputs (e.g., an image and text caption) or multiple outputs (e.g., predicting price and color), you cannot use Sequential. But for now, Sequential is your best friend.
Hands-on: Creating a Skeleton
import tensorflow as tf
from tensorflow.keras import layers
# Method 1: Passing a list of layers
model = tf.keras.Sequential([
layers.Dense(64),
layers.Dense(10)
])
# Method 2: The .add() method (Preferred by many for readability)
model = tf.keras.Sequential()
model.add(layers.Dense(64))
model.add(layers.Dense(10))3. Understanding Core Layers: Dense, Activation, and Flatten 🧱
Let's break down the "LEGO blocks" you put inside that Sequential container.
A. Flatten Layer (layers.Flatten)
Definition: A layer that transforms a multi-dimensional tensor (like a 2D image matrix) into a one-dimensional vector.
The Problem:
Computers see images as grids (e.g., 28x28 pixels). However, standard neural neurons expect a flat list of numbers as input. You can't plug a square peg (2D matrix) into a round hole (1D input).
The Solution:Flatten takes the rows of pixels and lines them up into one long spaghetti noodle of numbers.
Real Life Analogy: Reading a book. The text is 2D (lines on a page), but you read it word-by-word in a linear sequence to process the information.
# Input shape: 28x28 images (grayscale)
model.add(layers.Flatten(input_shape=(28, 28)))
# Output shape: A vector of size 784 (28 * 28)B. Dense Layer (layers.Dense)
Definition: A "fully connected" layer where every single neuron in this layer is connected to every single neuron in the previous layer.
The Problem:
We need the model to learn global relationships. If we look at a picture of a cat, the ear shape (top left) and the tail shape (bottom right) might both be important to identify it as a "cat." We need a mechanism that allows information to mix freely.
The Solution:
The Dense layer performs the classic linear operation:
It's the workhorse of deep learning.
units: The number of neurons (nodes) in the layer. More units = more capacity to learn complex patterns, but slower training.
C. Activation Functions (activation=...)
Definition: A mathematical function applied to the output of a neuron.
The Problem:
Without activation functions, a Neural Network is just a giant Linear Regression model.
If you stack linear layers (, then ), it's mathematically the same as one layer (). You can never learn curves, only straight lines.
The Solution:
We introduce non-linearity.
- ReLU (
relu): Rectified Linear Unit.- Logic: If value < 0, return 0. If value > 0, return value.
- Industry Standard: Use this for almost all hidden layers. It's fast and solves the "vanishing gradient" problem.
- Sigmoid (
sigmoid): Squishes numbers between 0 and 1.- Use case: Binary classification output (Yes/No).
- Softmax (
softmax): Converts a vector of numbers into probabilities that sum to 1.- Use case: Multi-class classification output (Cat/Dog/Bird).
Imagination: Think of ReLU as a bouncer at a club. If your "vibe" is negative (value < 0), you aren't getting in (0). If you are positive, you pass through unchanged.
4. Compiling the Model: Loss, Optimizer, and Metrics ⚙️
You have built the body of the robot (the Model). Now you need to teach it how to learn. This is the Compile step.
model.compile(
optimizer='adam',
loss='categorical_crossentropy',
metrics=['accuracy']
)A. The Loss Function (loss)
Definition: A formula that calculates the difference between the model's prediction and the actual truth.
The Problem: The model needs to know how wrong it is so it can adjust. "You guessed 5, the answer was 10. You are off by 5."
The Solution:
mean_squared_error(MSE): For Regression (predicting prices, temperature).categorical_crossentropy: For Multi-class classification (0-9 digits, A-Z letters) where labels are one-hot encoded.sparse_categorical_crossentropy: Same as above, but when labels are integers (e.g., class 5, class 7). (Most common in practice).binary_crossentropy: For Yes/No problems.
B. The Optimizer (optimizer)
Definition: The algorithm that updates the weights of the network based on the Loss to minimize error.
The Problem: We know we are wrong (Loss), but which weights do we tweak? Do we increase weight or decrease weight ? And by how much?
The Solution:
- SGD (Stochastic Gradient Descent): The grandfather. Reliable but can get stuck in "valleys" (local minima).
- Adam (Adaptive Moment Estimation): The cool kid. It adjusts the learning rate individually for each parameter.
- Industry Tip: Just use
'adam'. It is the default starting point for 99% of projects. It works famously well with little tuning.
- Industry Tip: Just use
Funny Exaggeration: If SGD is a drunk person stumbling down a hill trying to find the bottom, Adam is a drunk person with a GPS and momentum shoes who remembers which way was down 5 seconds ago.
C. Metrics (metrics)
Definition: Functions that are used to judge the performance of your model.
The Problem: The Loss function results in numbers like 0.3421 or 2.899. This is mathematically useful for the machine, but meaningless to the human boss asking "Is the model good?"
The Solution:
['accuracy']: The percentage of correct predictions.- Other metrics exist (Precision, Recall), but start with accuracy.
🧱 Putting it all together: A Complete Example
Here is a script that sets up a model to recognize handwriting (MNIST style).
import tensorflow as tf
from tensorflow.keras import layers
# 1. Define the Model (Sequential Stack)
model = tf.keras.Sequential([
# Input: 28x28 pixel images. Flatten unrolls them to 784 pixels.
layers.Flatten(input_shape=(28, 28)),
# Hidden Layer: 128 neurons trying to find patterns.
# Activation: ReLU (The standard for hidden layers)
layers.Dense(128, activation='relu'),
# Output Layer: 10 neurons (because we have digits 0-9).
# Activation: Softmax (Output probabilities summing to 1)
layers.Dense(10, activation='softmax')
])
# 2. Compile the Model (Configure learning)
model.compile(
optimizer='adam', # The best "out of the box" optimizer
loss='sparse_categorical_crossentropy', # Used for integer labels (0, 1, 2...)
metrics=['accuracy'] # We want to see % correct
)
# 3. Summary (Check your architecture)
model.summary()What happens under the hood? 🕵️♀️
When you run model.summary() and see the output, look at the Param #.
- In the first Dense layer above: parameters.
- That is over 100,000 knobs the
adamoptimizer has to turn simultaneously to learn to read.
📚 Further Reading & References
- Official TensorFlow Keras Guide - The holy grail.
- Keras Optimizer Documentation - Detailed math on Adam and friends.
- Loss Functions - Which loss to choose when.
Next Up: We will actually feed data into this monster using model.fit(). Get your GPUs ready! 🚀
Challenge
Challenge
Your task is to build and compile a tf.keras.Sequential model for a binary classification problem.
Imagine you are building a system to detect fraudulent transactions. The input for each transaction is a flattened vector of 128 numerical features.
Model Architecture Requirements:
- Instantiate a
tf.keras.Sequentialmodel. - Add a
Denselayer with 64 units. This layer should use the industry-standard activation function for hidden layers and must be correctly configured to accept the specified input shape. - Add a second
Denselayer with 32 units, also using the standard activation for hidden layers. - Add a final
Denseoutput layer, appropriately configured with the correct number of units and activation function for a binary (0 or 1) classification task.
Compilation Requirements:
After defining the model structure, compile it using the following configuration:
- Optimizer: Use the recommended default optimizer mentioned in the summary.
- Loss: Select the loss function specifically designed for binary classification.
- Metrics: Include
'accuracy'to monitor the model's performance.
Expected result
Your code should correctly define and compile a Keras Sequential model, assigning it to the model variable.
The final implementation should resemble the following structure:
import tensorflow as tf
from tensorflow.keras import layers, Sequential
# The input data for each transaction is a vector with 128 features.
# Define and compile the model below this line
model = Sequential([
layers.Dense(64, activation='relu', input_shape=(128,)),
layers.Dense(32, activation='relu'),
layers.Dense(1, activation='sigmoid')
])
model.compile(optimizer='adam',
loss='binary_crossentropy',
metrics=['accuracy'])