13. TensorFlow and Keras Fundamentalsยถ
Learn the foundations of TensorFlow and Keras, understand tensors, computation, models, layers, datasets, training, evaluation, GPU acceleration, and the complete workflow for building Deep Learning models.
๐ฏ Learning Objectivesยถ
After completing this chapter, you will be able to:
- Explain what TensorFlow is
- Explain what Keras is
- Understand the relationship between TensorFlow and Keras
- Understand tensors and their dimensions
- Work with TensorFlow tensors
- Understand tensor shapes, ranks, and data types
- Perform basic tensor operations
- Understand broadcasting
- Understand TensorFlow computation
- Understand automatic differentiation at a high level
- Understand Keras layers and models
- Build models using Keras
- Compile and train Keras models
- Evaluate and predict using Keras models
- Understand the Keras training workflow
- Work with datasets using
tf.data - Build input pipelines
- Understand batching, shuffling, caching, and prefetching
- Understand callbacks
- Save and load Keras models
- Use GPUs for TensorFlow training
- Understand CPU vs GPU execution
- Understand model parameters and trainable parameters
- Understand inference vs training mode
- Build classification and regression models using Keras
- Understand when to use Sequential vs Functional API
- Prepare for advanced Keras topics covered in later chapters
๐ Overviewยถ
TensorFlow is an open-source framework for numerical computation and Machine Learning.
It provides:
- Tensor operations
- Automatic differentiation
- Neural network primitives
- GPU and accelerator support
- Data pipelines
- Model training
- Model serialization
- Distributed training capabilities
Keras is a high-level Deep Learning API that provides a simpler interface for building and training neural networks.
The modern TensorFlow ecosystem can be viewed as:
TensorFlow
โ
โโโ Tensor Operations
โโโ Automatic Differentiation
โโโ GPU / Accelerator Execution
โโโ tf.data
โโโ Keras
โ
โโโ Layers
โโโ Models
โโโ Losses
โโโ Metrics
โโโ Optimizers
โโโ Training APIs
๐ง What Is TensorFlow?ยถ
TensorFlow is a framework for numerical computation and Machine Learning developed around tensor-based computation.
The fundamental data structure is the:
Tensor
A tensor is a multidimensional array with a defined shape and data type.
Examples:
๐ Tensor Ranksยถ
Tensor rank represents the number of dimensions of a tensor.
Rank 0 โ Scalarยถ
Rank 1 โ Vectorยถ
Rank 2 โ Matrixยถ
Rank 3ยถ
Conceptually:
flowchart LR
S["Scalar<br>Rank 0"]
V["Vector<br>Rank 1"]
M["Matrix<br>Rank 2"]
T["Tensor<br>Rank 3+"]
S --> V
V --> M
M --> T ๐งฎ Tensor Terminologyยถ
Three concepts are particularly important:
For example:
might return:
This could represent:
๐ Creating TensorFlow Tensorsยถ
import tensorflow as tf
scalar = tf.constant(10)
vector = tf.constant(
[1, 2, 3]
)
matrix = tf.constant(
[
[1, 2],
[3, 4]
]
)
tensor = tf.constant(
[
[
[1, 2],
[3, 4]
],
[
[5, 6],
[7, 8]
]
]
)
๐ Inspecting a Tensorยถ
x = tf.constant(
[
[1, 2, 3],
[4, 5, 6]
]
)
print(x)
print(x.shape)
print(x.dtype)
print(tf.rank(x))
Example:
๐ง Tensor Shapeยถ
Tensor shape describes the size of each dimension.
For:
returning:
the tensor contains:
For an image batch:
the dimensions commonly represent:
๐ผ๏ธ Image Tensor Representationยถ
A typical RGB image can be represented as:
For example:
A batch of 32 images becomes:
flowchart LR
B["Batch<br>32"]
H["Height<br>224"]
W["Width<br>224"]
C["Channels<br>3"]
B --> H
H --> W
W --> C ๐ง Tensor Data Typesยถ
TensorFlow supports multiple numeric data types.
Common examples include:
Deep Learning models commonly use:
while image data may initially be:
๐ Type Conversionยถ
This is important when preparing data for neural networks.
๐งฎ Tensor Operationsยถ
TensorFlow supports mathematical operations directly on tensors.
a = tf.constant(
[1, 2, 3]
)
b = tf.constant(
[4, 5, 6]
)
print(a + b)
print(a - b)
print(a * b)
print(a / b)
โ๏ธ Matrix Multiplicationยถ
Matrix multiplication is fundamental to neural networks.
a = tf.constant(
[
[1, 2],
[3, 4]
],
dtype=tf.float32
)
b = tf.constant(
[
[5, 6],
[7, 8]
],
dtype=tf.float32
)
result = tf.matmul(
a,
b
)
Mathematically:
[ C=AB ]
๐ Tensor Reshapingยถ
Tensor shape can often be changed without changing the underlying values.
Original:
New shape:
๐งฉ Flatteningยถ
Flattening converts multiple dimensions into one.
Result:
This is frequently used when transitioning from convolutional layers to dense layers.
๐ Broadcastingยถ
TensorFlow supports broadcasting for compatible shapes.
For example:
x = tf.constant(
[
[1, 2],
[3, 4]
],
dtype=tf.float32
)
y = tf.constant(
[10, 20],
dtype=tf.float32
)
result = x + y
Conceptually:
Result:
๐ง Why Tensors Matter in Deep Learningยถ
Neural networks operate primarily on tensors.
flowchart LR
DATA["Raw Data"]
TENSOR["Tensor"]
LAYER["Neural Network Layer"]
OUTPUT["Output Tensor"]
DATA --> TENSOR
TENSOR --> LAYER
LAYER --> OUTPUT Examples:
Images โ 4D tensors
Text โ 2D / 3D tensors
Audio โ 2D / 3D tensors
Video โ 5D tensors
Tabular โ 2D tensors
๐ง What Is Keras?ยถ
Keras is a high-level Deep Learning API designed to make neural network development easier and more readable.
It provides abstractions for:
- Layers
- Models
- Loss functions
- Optimizers
- Metrics
- Callbacks
- Training
- Evaluation
- Prediction
Instead of implementing every training operation manually, Keras provides a structured workflow.
๐ Keras Model Architectureยถ
flowchart TD
INPUT["Input"]
L1["Layer 1"]
L2["Layer 2"]
L3["Layer 3"]
OUTPUT["Output"]
INPUT --> L1
L1 --> L2
L2 --> L3
L3 --> OUTPUT A Keras model is essentially a composition of layers connected according to an architecture.
๐งฑ Keras Layersยถ
Common Keras layers include:
Example:
๐ง Dense Layerยถ
A Dense layer performs an affine transformation followed by an optional activation.
[ y=f(Wx+b) ]
where:
- (x) = input
- (W) = weights
- (b) = bias
- (f) = activation function
๐ Sequential Modelยถ
The simplest Keras model is the Sequential model.
model = tf.keras.Sequential([
tf.keras.layers.Dense(
128,
activation="relu"
),
tf.keras.layers.Dense(
64,
activation="relu"
),
tf.keras.layers.Dense(
10,
activation="softmax"
)
])
This represents:
The Sequential API is useful when the model is a simple linear stack of layers.
๐ง Input Shapeยถ
A model can explicitly define its input shape.
model = tf.keras.Sequential([
tf.keras.Input(
shape=(784,)
),
tf.keras.layers.Dense(
128,
activation="relu"
),
tf.keras.layers.Dense(
10,
activation="softmax"
)
])
Here:
๐ง Keras Model Summaryยถ
Keras provides a useful model summary.
Typical information includes:
For example:
๐งฎ Trainable Parametersยถ
For a Dense layer:
[ Parameters = InputFeatures\times OutputFeatures + OutputFeatures ]
For example:
Then:
[ 784\times128+128 = 100480 ]
This represents:
๐ง Build โ Compile โ Fit โ Evaluate โ Predictยถ
The basic Keras workflow is:
flowchart LR
BUILD["Build Model"]
COMPILE["Compile"]
FIT["Fit"]
EVAL["Evaluate"]
PRED["Predict"]
BUILD --> COMPILE
COMPILE --> FIT
FIT --> EVAL
EVAL --> PRED This is one of the most important workflows to remember.
โ๏ธ Compileยถ
Before training, configure:
Example:
model.compile(
optimizer=tf.keras.optimizers.Adam(
learning_rate=0.001
),
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
๐๏ธ Fitยถ
Training is performed using:
๐ What Happens During fit()?ยถ
Conceptually:
flowchart TD
BATCH["Training Batch"]
BATCH --> FORWARD["Forward Pass"]
FORWARD --> LOSS["Calculate Loss"]
LOSS --> BACK["Backpropagation"]
BACK --> GRAD["Gradients"]
GRAD --> OPT["Optimizer"]
OPT --> UPDATE["Update Weights"]
UPDATE --> NEXT["Next Batch"]
NEXT --> BATCH Keras handles much of this training loop automatically.
๐ Training Historyยถ
The object returned by fit() contains training history.
Typical values:
๐ Plotting Training Curvesยถ
import matplotlib.pyplot as plt
plt.figure(figsize=(10, 6))
plt.plot(
history.history["loss"],
label="Training Loss"
)
plt.plot(
history.history["val_loss"],
label="Validation Loss"
)
plt.xlabel("Epoch")
plt.ylabel("Loss")
plt.title("Training vs Validation Loss")
plt.legend()
plt.grid(True)
plt.show()
Training curves help identify:
๐งช Evaluateยถ
After training:
This evaluates the model on unseen data.
๐ฎ Predictยถ
Prediction:
For a classification model using Softmax:
The largest probability can be selected as the predicted class.
๐ง Classification Exampleยถ
For a 10-class classification problem:
model = tf.keras.Sequential([
tf.keras.Input(
shape=(784,)
),
tf.keras.layers.Dense(
128,
activation="relu"
),
tf.keras.layers.Dense(
64,
activation="relu"
),
tf.keras.layers.Dense(
10,
activation="softmax"
)
])
Compile:
๐ง Regression Exampleยถ
For regression, the output layer commonly has one unit with no classification activation.
model = tf.keras.Sequential([
tf.keras.Input(
shape=(10,)
),
tf.keras.layers.Dense(
64,
activation="relu"
),
tf.keras.layers.Dense(
32,
activation="relu"
),
tf.keras.layers.Dense(
1
)
])
Compile:
๐ง Classification vs Regressionยถ
| Problem | Output Layer | Typical Loss |
|---|---|---|
| Binary Classification | 1 + Sigmoid | Binary Cross-Entropy |
| Multi-Class Classification | N + Softmax | Categorical Cross-Entropy |
| Integer-Labeled Multi-Class | N + Softmax | Sparse Categorical Cross-Entropy |
| Regression | 1 or more linear outputs | MSE / MAE |
๐ฆ TensorFlow tf.dataยถ
TensorFlow provides the tf.data API for building efficient input pipelines.
A basic pipeline:
dataset = tf.data.Dataset.from_tensor_slices(
(X_train, y_train)
)
dataset = dataset.shuffle(
buffer_size=10000
)
dataset = dataset.batch(
32
)
dataset = dataset.prefetch(
tf.data.AUTOTUNE
)
๐ tf.data Pipelineยถ
flowchart LR
RAW["Raw Data"]
CREATE["Dataset"]
SHUFFLE["Shuffle"]
BATCH["Batch"]
PREFETCH["Prefetch"]
MODEL["Model"]
RAW --> CREATE
CREATE --> SHUFFLE
SHUFFLE --> BATCH
BATCH --> PREFETCH
PREFETCH --> MODEL ๐ Shuffleยถ
Shuffling helps prevent the model from learning unwanted ordering patterns.
For training data, shuffling is generally useful.
For evaluation datasets, deterministic ordering is usually preferred.
๐ฆ Batchยถ
Batching groups examples together.
Conceptually:
โก Prefetchยถ
Prefetching allows the input pipeline to prepare future batches while the model processes the current batch.
Conceptually:
flowchart LR
DATA["Input Pipeline"]
DATA --> B1["Batch N"]
DATA --> B2["Prepare Batch N+1"]
B1 --> GPU["GPU Training"]
B2 --> GPU This can improve hardware utilization by reducing input pipeline waiting time.
๐พ Cacheยถ
Caching can reduce repeated data-loading work.
However, caching the entire dataset in memory may not be appropriate for large datasets.
Possible approaches include:
Choose based on dataset size and infrastructure.
๐ง Complete tf.data Pipelineยถ
A common training pipeline:
train_ds = (
tf.data.Dataset
.from_tensor_slices(
(X_train, y_train)
)
.shuffle(10000)
.batch(32)
.prefetch(
tf.data.AUTOTUNE
)
)
Validation:
val_ds = (
tf.data.Dataset
.from_tensor_slices(
(X_val, y_val)
)
.batch(32)
.prefetch(
tf.data.AUTOTUNE
)
)
๐ง Data Pipeline Performanceยถ
A production pipeline should aim for:
The goal is to prevent:
๐ Keras Callbacksยถ
Callbacks allow additional behavior during training.
Common callbacks include:
โน๏ธ EarlyStoppingยถ
early_stopping = tf.keras.callbacks.EarlyStopping(
monitor="val_loss",
patience=5,
restore_best_weights=True
)
Use:
๐พ ModelCheckpointยถ
checkpoint = tf.keras.callbacks.ModelCheckpoint(
"best_model.keras",
monitor="val_loss",
save_best_only=True
)
This ensures that the best validation model can be preserved.
๐ ReduceLROnPlateauยถ
reduce_lr = tf.keras.callbacks.ReduceLROnPlateau(
monitor="val_loss",
factor=0.5,
patience=3,
min_lr=1e-6
)
This reduces the learning rate when validation performance stops improving.
๐ TensorBoardยถ
TensorBoard provides tools for inspecting:
- Training metrics
- Loss curves
- Learning rates
- Histograms
- Model graphs
- Profiling information
Example:
๐ง Complete Callback Configurationยถ
callbacks = [
tf.keras.callbacks.EarlyStopping(
monitor="val_loss",
patience=5,
restore_best_weights=True
),
tf.keras.callbacks.ModelCheckpoint(
"best_model.keras",
monitor="val_loss",
save_best_only=True
),
tf.keras.callbacks.ReduceLROnPlateau(
monitor="val_loss",
factor=0.5,
patience=3
)
]
๐พ Saving a Keras Modelยถ
Modern Keras supports saving complete models.
Load:
A complete model artifact can include:
depending on the saving configuration.
๐พ Saving Weights Onlyยถ
Load:
This is useful when the architecture is reconstructed separately.
๐ง Model Serialization Strategyยถ
flowchart TD
MODEL["Trained Model"]
MODEL --> FULL["Complete Model Artifact"]
MODEL --> WEIGHTS["Weights Only"]
FULL --> DEPLOY["Load for Inference"]
WEIGHTS --> ARCH["Recreate Architecture"]
ARCH --> DEPLOY ๐ฅ๏ธ CPU vs GPUยถ
TensorFlow can execute operations on different devices.
Common devices include:
For Deep Learning workloads:
๐ Checking GPU Availabilityยถ
If a GPU is available, TensorFlow can often place supported operations on it automatically.
๐ Inspecting Devicesยถ
Possible output:
[
PhysicalDevice(
name="/physical_device:CPU:0",
device_type="CPU"
),
PhysicalDevice(
name="/physical_device:GPU:0",
device_type="GPU"
)
]
๐ง Explicit Device Placementยถ
TensorFlow allows explicit device contexts.
In most applications, explicit placement is not necessary because TensorFlow's runtime can handle device placement.
โก GPU Training Pipelineยถ
flowchart LR
DATA["Dataset"]
CPU["CPU Input Pipeline"]
GPU["GPU"]
MODEL["Neural Network"]
GRAD["Gradients"]
UPDATE["Parameter Update"]
DATA --> CPU
CPU --> GPU
GPU --> MODEL
MODEL --> GRAD
GRAD --> UPDATE
UPDATE --> MODEL The CPU may prepare and feed data while the GPU performs tensor-heavy computation.
๐ง GPU Memoryยถ
GPU memory is a critical resource.
Memory is consumed by:
Therefore, increasing batch size may increase GPU memory consumption significantly.
๐ง Training vs Inferenceยถ
Training requires:
Inference usually requires:
Therefore, training generally consumes considerably more memory.
flowchart LR
TRAIN["Training"]
TRAIN --> FORWARD["Forward"]
FORWARD --> LOSS["Loss"]
LOSS --> BACK["Backward"]
BACK --> UPDATE["Update"]
INFER["Inference"]
INFER --> PRED["Forward"] ๐ง Trainable Parametersยถ
Keras exposes model parameters through:
You can inspect them:
๐ Freezing Layersยถ
Layers can be frozen by setting:
This is particularly important for Transfer Learning.
Example:
Transfer Learning is covered in:
21. Transfer Learning and Fine-Tuning
๐ง Keras Functional API Previewยถ
The Functional API allows non-linear model structures.
For example:
inputs = tf.keras.Input(
shape=(784,)
)
x = tf.keras.layers.Dense(
128,
activation="relu"
)(inputs)
x = tf.keras.layers.Dense(
64,
activation="relu"
)(x)
outputs = tf.keras.layers.Dense(
10,
activation="softmax"
)(x)
model = tf.keras.Model(
inputs=inputs,
outputs=outputs
)
The Functional API is covered in detail in:
14. Keras Sequential and Functional API
๐ง Custom Training Loops Previewยถ
Keras also allows custom training loops.
Conceptually:
flowchart TD
BATCH["Batch"]
BATCH --> FORWARD["Forward Pass"]
FORWARD --> LOSS["Loss"]
LOSS --> GRAD["GradientTape"]
GRAD --> OPT["Optimizer"]
OPT --> UPDATE["Update Variables"]
UPDATE --> BATCH A simplified TensorFlow example:
with tf.GradientTape() as tape:
predictions = model(
X_batch,
training=True
)
loss = loss_fn(
y_batch,
predictions
)
gradients = tape.gradient(
loss,
model.trainable_variables
)
optimizer.apply_gradients(
zip(
gradients,
model.trainable_variables
)
)
Custom models and training loops are covered in:
15. Custom Layers, Models and Training Loops
๐ง Keras Model Lifecycleยถ
A practical Keras lifecycle is:
flowchart LR
DATA["Data"]
BUILD["Build"]
COMPILE["Compile"]
TRAIN["Train"]
VALIDATE["Validate"]
SAVE["Save"]
DEPLOY["Deploy"]
MONITOR["Monitor"]
DATA --> BUILD
BUILD --> COMPILE
COMPILE --> TRAIN
TRAIN --> VALIDATE
VALIDATE --> SAVE
SAVE --> DEPLOY
DEPLOY --> MONITOR ๐งช Complete Example โ Classificationยถ
import tensorflow as tf
# Model
model = tf.keras.Sequential([
tf.keras.Input(
shape=(784,)
),
tf.keras.layers.Dense(
128,
activation="relu"
),
tf.keras.layers.Dropout(
0.2
),
tf.keras.layers.Dense(
64,
activation="relu"
),
tf.keras.layers.Dense(
10,
activation="softmax"
)
])
# Compile
model.compile(
optimizer=tf.keras.optimizers.AdamW(
learning_rate=3e-4,
weight_decay=1e-4
),
loss="sparse_categorical_crossentropy",
metrics=["accuracy"]
)
# Callbacks
callbacks = [
tf.keras.callbacks.EarlyStopping(
monitor="val_loss",
patience=5,
restore_best_weights=True
),
tf.keras.callbacks.ModelCheckpoint(
"best_model.keras",
monitor="val_loss",
save_best_only=True
)
]
# Train
history = model.fit(
X_train,
y_train,
validation_data=(
X_val,
y_val
),
epochs=50,
batch_size=64,
callbacks=callbacks
)
# Evaluate
model.evaluate(
X_test,
y_test
)
๐งช Complete Example โ Regressionยถ
import tensorflow as tf
model = tf.keras.Sequential([
tf.keras.Input(
shape=(10,)
),
tf.keras.layers.Dense(
128,
activation="relu"
),
tf.keras.layers.Dense(
64,
activation="relu"
),
tf.keras.layers.Dense(
1
)
])
model.compile(
optimizer=tf.keras.optimizers.AdamW(
learning_rate=3e-4
),
loss="mse",
metrics=["mae"]
)
history = model.fit(
X_train,
y_train,
validation_data=(
X_val,
y_val
),
epochs=50,
batch_size=64
)
๐งช Complete Example โ tf.data + Kerasยถ
train_ds = (
tf.data.Dataset
.from_tensor_slices(
(X_train, y_train)
)
.shuffle(10000)
.batch(64)
.prefetch(
tf.data.AUTOTUNE
)
)
val_ds = (
tf.data.Dataset
.from_tensor_slices(
(X_val, y_val)
)
.batch(64)
.prefetch(
tf.data.AUTOTUNE
)
)
model.fit(
train_ds,
validation_data=val_ds,
epochs=50
)
๐ง Production-Oriented TensorFlow Architectureยถ
A production Deep Learning application should separate:
Data
โ
Preprocessing
โ
Dataset Pipeline
โ
Model
โ
Training
โ
Evaluation
โ
Artifact
โ
Serving
A possible architecture:
flowchart TD
DATA["Raw Data"]
PRE["Preprocessing"]
PIPE["tf.data Pipeline"]
MODEL["Keras Model"]
TRAIN["Training"]
EVAL["Evaluation"]
ART["Model Artifact"]
SERVE["Model Serving"]
MON["Monitoring"]
DATA --> PRE
PRE --> PIPE
PIPE --> MODEL
MODEL --> TRAIN
TRAIN --> EVAL
EVAL --> ART
ART --> SERVE
SERVE --> MON ๐ข Enterprise Perspectiveยถ
TensorFlow and Keras provide more than APIs for building neural networks.
They can serve as components of an enterprise Deep Learning platform:
Data Engineering
โ
TensorFlow Data Pipeline
โ
Keras Model
โ
Training Infrastructure
โ
GPU / TPU
โ
Model Artifact
โ
Model Registry
โ
Serving
โ
Monitoring
For enterprise systems, the important concerns include:
- Reproducibility
- Dataset versioning
- Experiment tracking
- Model versioning
- Hardware utilization
- Training cost
- Model quality
- Deployment
- Monitoring
- Governance
Production Insight
A Keras model is only one component of a production Deep Learning system.
A reliable system should connect:
Versioned Data
โ
Reproducible Training
โ
Versioned Model
โ
Validated Artifact
โ
Deployment
โ
Monitoring
Optimizing only the model while ignoring the data pipeline, hardware utilization, artifact management, and observability can create a fragile production system.
โ Common Mistakesยถ
Avoid these common mistakes:
- Confusing TensorFlow with Keras
- Ignoring tensor shapes
- Mixing incompatible tensor data types
- Forgetting to normalize input data
- Using incorrect output activation functions
- Using the wrong loss function
- Forgetting validation data
- Training without monitoring validation metrics
- Ignoring GPU memory
- Using excessively large batch sizes
- Loading an entire large dataset into memory unnecessarily
- Failing to use efficient
tf.datapipelines - Applying augmentation incorrectly to validation/test data
- Saving only weights when the complete model artifact is required
- Forgetting to save the best checkpoint
- Not versioning the training configuration
- Assuming GPU usage automatically guarantees efficient training
- Ignoring CPU input-pipeline bottlenecks
- Treating training and inference as identical workloads
- Hardcoding hyperparameters throughout the codebase
๐ง Interview Questionsยถ
Beginnerยถ
1. What is TensorFlow?ยถ
TensorFlow is a framework for tensor-based numerical computation and Machine Learning, providing automatic differentiation, neural-network primitives, hardware acceleration, and other ML capabilities.
2. What is Keras?ยถ
Keras is a high-level Deep Learning API that provides abstractions for building, training, evaluating, and deploying neural networks.
3. What is a tensor?ยถ
A tensor is a multidimensional array with a defined shape and data type.
4. What is tensor rank?ยถ
Tensor rank represents the number of dimensions of a tensor.
5. What is the difference between shape and rank?ยถ
Rank tells you how many dimensions a tensor has, while shape tells you the size of each dimension.
Intermediateยถ
6. What are the main steps in a Keras workflow?ยถ
7. What does model.compile() do?ยถ
It configures the optimizer, loss function, and metrics used by the training process.
8. What does model.fit() do?ยถ
It executes the training process over the supplied dataset for the specified number of epochs.
9. What is tf.data?ยถ
tf.data is TensorFlow's API for constructing input pipelines.
10. Why is prefetch() useful?ยถ
It allows future batches to be prepared while the current batch is being processed, potentially improving hardware utilization.
11. What is a Keras callback?ยถ
A callback is an object that can execute actions at specific points during training.
12. Why use ModelCheckpoint?ยถ
It allows the best or selected model state to be saved during training.
Advancedยถ
13. Why is tensor shape important?ยถ
Neural-network layers expect inputs with compatible dimensions. Incorrect shapes can cause runtime errors or produce incorrect model behavior.
14. Why can GPU training still be slow?ยถ
Potential bottlenecks include:
15. Why is tf.data important for production?ยถ
It can provide efficient batching, shuffling, caching, prefetching, and transformation pipelines that help keep training hardware utilized.
16. What is the difference between training and inference?ยถ
Training requires forward propagation, loss computation, backpropagation, and parameter updates. Inference generally requires only the forward pass.
17. Why is optimizer state important?ยถ
Optimizers such as Adam and AdamW maintain additional tensors, increasing memory requirements during training.
18. When should you use the Functional API instead of Sequential?ยถ
Use the Functional API when the architecture contains branching, multiple inputs/outputs, skip connections, shared layers, or other non-linear graph structures.
19. Why would you use a custom training loop?ยถ
Custom loops provide control over training behavior when the standard fit() workflow is insufficient for a particular research or production requirement.
20. How would you optimize a TensorFlow training pipeline?ยถ
Inspect:
Input Pipeline
Batch Size
Prefetching
Caching
GPU Utilization
Mixed Precision
Model Complexity
Data Transfer
Then measure the actual bottleneck before optimizing.
๐งช Practical Exercisesยถ
Exercise 1 โ Tensor Fundamentalsยถ
Create tensors of:
For each tensor, print:
Exercise 2 โ Tensor Operationsยถ
Implement:
Verify the resulting shapes.
Exercise 3 โ Build a Classification Modelยถ
Create a Keras model with:
Train it on a classification dataset.
Track:
Exercise 4 โ Build a Regression Modelยถ
Create a regression network using:
Evaluate using:
Exercise 5 โ Build a tf.data Pipelineยถ
Create a pipeline using:
Measure whether the training throughput changes when prefetching is enabled.
Exercise 6 โ GPU Trainingยถ
Check:
Train the same model using:
Compare:
Exercise 7 โ Callbacksยถ
Train a model using:
Inspect the resulting training behavior.
๐ Key Takeawaysยถ
- TensorFlow provides tensor-based computation and Deep Learning infrastructure.
- Keras provides a high-level API for building and training neural networks.
- Tensors are the fundamental data structure used by Deep Learning systems.
- Tensor rank represents the number of dimensions.
- Tensor shape describes the size of each dimension.
- Data type determines how tensor values are represented.
- Matrix multiplication is fundamental to neural-network computation.
- Keras models are composed of layers.
- The basic Keras workflow is Build โ Compile โ Fit โ Evaluate โ Predict.
tf.dataprovides efficient input-pipeline capabilities.- Shuffling is generally useful for training data.
- Batching controls the number of examples processed per optimizer update.
- Prefetching can improve hardware utilization.
- Caching can reduce repeated data-loading work when used appropriately.
- Callbacks provide control over training behavior.
- Checkpointing preserves useful model states.
- Early Stopping can prevent unnecessary training.
- TensorFlow can use CPUs, GPUs, and other accelerators.
- GPU memory is consumed by parameters, gradients, optimizer state, activations, and input batches.
- Training generally requires more memory than inference.
- Sequential models are useful for simple linear stacks.
- More complex architectures should use the Functional API or custom model implementations.
- Efficient Deep Learning requires optimizing the complete pipeline, not only the neural network.
๐ Further Readingยถ
Continue with:
- 14. Keras Sequential and Functional API
- 15. Custom Layers, Models and Training Loops
- 16. PyTorch Fundamentals and Tensors
- 17. PyTorch Autograd, Dataset and DataLoader
- 18. Building Classification and Regression Models
- 19. Convolutional Neural Networks
- 21. Transfer Learning and Fine-Tuning
- 35. GPU-Accelerated Deep Learning
The next chapter goes deeper into the two major Keras model-building approaches: the Sequential API and Functional API.
โก๏ธ Next Chapterยถ
14. Keras Sequential and Functional API
Enterprise AI Engineering Handbook
Building Production-Grade Enterprise AI Systems โ One Chapter at a Time.