liveBook · Manning

Chapter 2: The mathematical building blocks of neural networks

What you will learn in chapter 2 of Deep Learning with Python, Third Edition

The chapter introduction explains why executable code and interactive notebooks are useful for learning the mathematical ideas behind deep learning, and how to run the book’s examples.

After this chapter you will be able to

What it builds on

Section by section

Introduction

The chapter introduction explains why executable code and interactive notebooks are useful for learning the mathematical ideas behind deep learning, and how to run the book’s examples.

Key terms: mathematical notation, executable code, Jupyter notebook, Google Colaboratory, Colab, GPU runtime

2.1 A first look at a neural network

This section walks through a Keras neural network that learns to classify MNIST handwritten digits, then uses and evaluates it on unseen images.

Key terms: MNIST, training set, test set, samples, labels, classes, layer, representations, Dense layers, fully connected

2.2 Data representations for neural networks

Introduces tensors as the basic data containers of machine learning and relates them to matrices and dimensions.

Key terms: tensor, rank-2 tensor, dimension, axis

2.2.1 Scalars (rank-0 tensors)

Defines a scalar tensor and relates its rank to its number of axes in NumPy.

Key terms: scalar, scalar tensor, rank-0 tensor, 0D tensor, axes, rank

2.2.2 Vectors (rank-1 tensors)

Defines a vector as a one-axis tensor and distinguishes the number of entries on that axis from a tensor’s rank.

Key terms: vector, rank-1 tensor, 1D tensor, axis, rank, dimensionality

2.2.3 Matrices (rank-2 tensors)

Defines a matrix as a rank-2 tensor and identifies its rows and columns as its two axes.

Key terms: matrix, rank-2 tensor, 2D tensor, axes, rows, columns

2.2.4 Rank-3 tensors and higher-rank tensors

The section explains how stacking matrices creates rank-3 tensors and how stacking tensors produces higher ranks.

Key terms: rank-3 tensor, 3D tensor, rank-4 tensor

2.2.5 Key attributes

This section defines the three attributes of a tensor and uses MNIST images to show how those attributes describe real data.

Key terms: rank, ndim, shape, dtype, MNIST, train_images, rank-3 tensor, 8-bit integers, grayscale image

2.2.6 Manipulating tensors in NumPy

This section shows how to select ranges and image patches from NumPy tensors by slicing their axes.

Key terms: tensor slicing, axis, start index, stop index, negative indices, current axis

2.2.7 The notion of data batches

Explains how deep learning data is divided into batches and why a batch tensor’s first axis is called the batch axis.

Key terms: axis 0, samples axis, batch, batch size, batch axis, batch dimension

2.2.8 Real-world examples of data tensors

This section shows how common real-world datasets become tensors, with each axis representing samples, features, time, spatial dimensions, channels, or video frames.

Key terms: vector data, samples axis, features axis, rank-2 tensor, timeseries data, sequence data, timesteps, features, rank-3 tensor, image tensors

2.3 The gears of neural networks: Tensor operations

The section introduces tensor operations as the building blocks of neural-network transformations and illustrates them with a Dense layer.

Key terms: tensor operations, tensor functions, tensors, Dense layer, tensor product, matmul, W, b, relu

2.3.1 Element-wise operations

This section defines element-wise tensor operations and explains why vectorized implementations run much faster than naive Python loops.

Key terms: element-wise operations, relu, addition, vectorized implementations, NumPy, BLAS, CUDA

2.3.2 Broadcasting

Explains how broadcasting lets element-wise operations combine tensors of different shapes without physically repeating data.

Key terms: broadcasting, broadcast axes, shape, ndim, element-wise operations, virtual, algorithmic level, memory level

2.3.3 Tensor product

This section explains how tensor products combine vectors and matrices, including the shape requirements and outputs of common matmul operations.

Key terms: tensor product, dot product, matmul, vector, matrix-vector product, rows, ndim, shape compatibility, columns, matrix product

2.3.4 Tensor reshaping

Defines tensor reshaping and identifies matrix transposition as a common special case.

Key terms: tensor reshaping, target shape, coefficients, transposition, matrix, rows, columns

2.3.5 Geometric interpretation of tensor operations

This section interprets tensor operations as geometric transformations and explains why Dense networks need activation functions to produce nonlinear transformations.

Key terms: vector addition, translation, rotation, scaling, linear transform, matrix product, affine transform, Dense layer, y = W @ x + b, activation function

2.3.6 A geometric interpretation of deep learning

This section interprets deep learning as a chain of simple geometric transformations that gradually makes tangled data easier to separate.

Key terms: tensor operations, geometric transformation, high-dimensional space, data manifolds, uncrumpling, disentangles, classes, layers

2.4 The engine of neural networks: Gradient-based optimization

This section explains how a neural network learns by repeatedly measuring prediction error and using gradients to adjust its weights efficiently.

Key terms: weights, trainable parameters, kernel, bias, random initialization, training loop, batch, targets, forward pass, predictions

2.4.1 What’s a derivative?

This section explains derivatives as local slopes of smooth functions and shows how their direction guides minimization.

Key terms: smooth, local linear approximation, slope, derivative, derivative function, magnitude of the derivative, optimization, minimize, opposite direction from the derivative

2.4.2 Derivative of a tensor operation: The gradient

This section extends derivatives to tensor-valued inputs and shows how the gradient of a loss with respect to model weights suggests an update that reduces the loss.

Key terms: gradient, tensor function, derivative, W, W0, loss_value, partial derivative, gradient of loss_value with respect to W, step

2.4.3 Stochastic gradient descent

This section explains why neural networks use gradient-based updates instead of solving for optimal weights analytically, then describes mini-batch SGD, its practical choices, and momentum.

Key terms: loss function, gradient, parameters, mini-batch stochastic gradient descent, forward pass, backward pass, loss, learning rate, local minimum, true SGD

2.4.4 Chaining derivatives: The Backpropagation algorithm

This section explains how backpropagation applies the chain rule to a computation graph to calculate a neural network’s loss gradients, and how frameworks automate that process.

Key terms: chain rule, backpropagation, gradient, atomic operations, computation graph, forward pass, backward pass, loss_val, w, b

2.5 Looking back at our first example

The section revisits the first handwritten-digit example to connect its data, model, loss, optimizer, and training call to the neural-network concepts explained earlier.

Key terms: NumPy tensors, float32, Dense layers, weight tensors, loss function, sparse_categorical_crossentropy, optimizer, adam, mini-batch stochastic gradient descent, fit

2.5.1 Reimplementing our first example from scratch

The section sketches a low-level reimplementation of the first neural-network model using a simple Dense layer and a class that chains layers.

Key terms: Dense layer, W, b, model parameters, activation, NaiveDense, NaiveSequential, layers, __call__(), weights

2.5.2 Running one training step

This section explains how one batch of data produces a loss, gradients, and a small weight update, using TensorFlow’s automatic differentiation to obtain the gradients.

Key terms: training step, batch, loss, gradient, weights, weight update, learning rate, Optimizer, automatic differentiation, tf.GradientTape

2.5.3 The full training loop

Defines an epoch and the full training loop in terms of repeated training steps.

Key terms: training step, batch, epoch, full training loop

2.5.4 Evaluating the model

The section evaluates the handwritten model on test images and explains why working through its low-level steps helps readers understand Keras.

Key terms: argmax, predictions, test images, expected labels, by hand, fit(), low-level mental model, Keras API

2.6 Summary

Where this is used later

Concepts explained in this chapter

← Chapter 1: What is deep learning? Chapter 3: Introduction to TensorFlow, PyTorch, JAX, and Keras →

These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.