Neural networks with Keras
Build XOR, understand one gradient, then compare Dense and convolutional networks.
Prerequisites: arrays, affine maps and derivatives. Programs use Python, NumPy, Matplotlib and TensorFlow/Keras. Run each complete example in a fresh Python session; Parts 5 and 6 run sequentially together. The programs contain no assertions: checks are printed. Part 4 revisits the original Spam/Ham exercise with a runnable correction.
Part 1 · Build XOR by hand
Four points and the limit of one neuron
XOR returns 1 when exactly one input is 1. Its table is $(0,0)\mapsto0$, $(0,1)\mapsto1$, $(1,0)\mapsto1$, $(1,1)\mapsto0$. Each row is one observation, with two input coordinates and a binary target.
A single neuron first computes $z=w_1x_1+w_2x_2+b$. Thresholding this score at zero produces a straight decision line. Applying a sigmoid first does not change that line: $\sigma(z)\ge0.5$ exactly when $z\ge0$.
Proof. A correct separator would need $b<0$, $w_1+w_2+b<0$, $w_1+b\ge0$ and $w_2+b\ge0$. Adding the first two gives $w_1+w_2+2b<0$; adding the last two gives the opposite inequality. No training method can overcome this representational obstruction.
Two hidden ReLU neurons create useful coordinates
Construct $h_1=\max(0,x_1-x_2)$ and $h_2=\max(0,x_2-x_1)$. Use an affine output $z=4h_1+4h_2-2$. Each hidden neuron detects one sign of the difference. Their sum is $|x_1-x_2|$.
Each input to hidden layer is weighted ±1; both hidden biases are 0. Each hidden to output weight is 4; the output bias is −2.
Class 0 · probability 11.9%
| Input | h1 | h2 | Score z | Class |
|---|---|---|---|---|
| (0,0) | 0 | 0 | −2 | 0 |
| (0,1) | 0 | 1 | 2 | 1 |
| (1,0) | 1 | 0 | 2 | 1 |
| (1,1) | 0 | 0 | −2 | 0 |
The representation turns XOR into an affine classification problem in hidden coordinates: class 0 maps to the origin and class 1 to either axis. These imposed weights establish that the network can represent XOR; no optimization has occurred.
Implement the imposed weights in Keras
# Two imposed ReLU neurons and an affine output: no training needed.import numpy as npimport tensorflow as tffrom tensorflow import kerasX = np.array([[0,0],[0,1],[1,0],[1,1]], dtype='float32')y = np.array([0,1,1,0])model = keras.Sequential([ keras.Input(shape=(2,)), # Dense learns a kernel K (inputs x units) AND a bias vector b, one bias per neuron (use_bias=True by default) keras.layers.Dense(2, activation='relu'), keras.layers.Dense(1) # Default activation is linear: affine score.])model.set_weights([ np.array([[1,-1],[-1,1]], dtype='float32'), np.array([0,0], dtype='float32'), np.array([[4],[4]], dtype='float32'), np.array([-2], dtype='float32')])print('Hidden values:', model.layers[0](X).numpy())print('Affine scores:', model(X).numpy().ravel())print('Probabilities:', tf.sigmoid(model(X)).numpy().ravel())
Xcontains four observations.Input(shape=(2,))describes one observation; Keras keeps the batch axis.Dense(2, activation="relu")computes the hidden features. The nextDense(1)has its default linear activation and returns an unrestricted affine score.set_weightsreceives the first kernel, first bias, second kernel and second bias. A Dense kernel has shape (inputs, outputs): its columns contain the weights of the output neurons. Here the kernels are (2,2) and (2,1), with biases (2,) and (1,): nine parameters in all.- The printed hidden values and scores reproduce the table above.
tf.sigmoidconverts the scores into probabilities for inspection; it does not change the imposed weights.
Run this block first. The plotting block below reuses X, y and model.
Plot the score and the probability
# Run after xor_hand.py: model, X and y are already defined.import matplotlib.pyplot as pltu = np.linspace(-0.2, 1.2, 180)a, b = np.meshgrid(u, u)grid = np.column_stack([a.ravel(), b.ravel()]).astype('float32')z = model(grid).numpy().reshape(a.shape)p = tf.sigmoid(z).numpy()fig, axes = plt.subplots(1, 2, figsize=(10, 4))for ax, surface, title, boundary in zip( axes, [z, p], ['Affine output score', 'Sigmoid probability'], [0, .5]): image = ax.contourf(a, b, surface, levels=20, cmap='coolwarm') ax.contour(a, b, surface, levels=[boundary], colors='black') ax.scatter(X[:, 0], X[:, 1], c=y, cmap='coolwarm', edgecolors='black') ax.set(title=title, xlabel='x1', ylabel='x2') fig.colorbar(image, ax=ax)plt.tight_layout()plt.show()
linspacecreates coordinate values;meshgridcombines them into a two-dimensional grid.column_stackturns the grid into rows of (x1,x2) inputs. The model gives one score per row;reshaperestores the grid shape.- Apply the sigmoid to get the probability surface.
contourffills both surfaces. The black curves mark score 0 and probability 0.5, which define the same decision boundary. This grid includes zero, so both contours are visible. scatteradds the four known observations. The smooth surfaces between them follow from the chosen weights, not from extra training data.
Why turn a score into a probability?
The score $z$ can be any real number. The sigmoid $\sigma(z)=1/(1+e^{-z})$ maps it into $(0,1)$: negative scores give $\sigma(z)<0.5$, zero gives 0.5, and positive scores give $\sigma(z)>0.5$. This lets us read how strongly the model favours class 1 rather than seeing only a hard decision. Scores −2 and 2 become approximately 0.1192 and 0.8808.
A value $\sigma(z)=0.88$ means the model assigns 88% to class 1 under its chosen parameters; it is not a guarantee that 88% of similar future cases will be correct. Four XOR examples do not establish calibration. Here the sigmoid is applied only when reading and plotting the imposed score. Part 2 introduces learning from labelled observations.
Part 2 · One sigmoid neuron learns a line
Data, neuron and decision line
We now train on eight labelled points in the plane. For example, $(1,-1)$ belongs to class 0 and $(0,1)$ belongs to class 1. The two coordinates have different roles in this dataset, so their learned weights should differ. The bias shifts the line away from the origin.
The neuron combines the two coordinates and the constant input $+1$: $z=w_1x_1+w_2x_2+b$. Its activation is $\sigma(z)=1/(1+e^{-z})$, interpreted as the model probability of class 1. The class-1 decision is $\sigma(z)\ge0.5$, equivalent to $z\ge0$. The boundary $w_1x_1+w_2x_2+b=0$ is a straight line.
The red and blue points are linearly separable. The dashed +1 input in the neuron schematic carries the bias, exactly as in the preceding XOR network. At the zero initialization every point has $\sigma(z)=0.5$; the first useful line appears after one update. The chosen finite training budget gives a visible trajectory, even though the weights of unregularized logistic regression may continue to grow on separable data.
Notation first: what are the score and probability?
There are $N=8$ observations. Observation $i$ has input vector $x_i=(x_{i1},x_{i2})^T$ and known label $y_i\in\{0,1\}$. In the program, $X$ has one observation per row and shape $(8,2)$; $y$ is an $(8,1)$ column. The weight vector is $w=(w_1,w_2)^T$, and $b$ is one scalar bias.
For each row, define its score $z_i=w_1x_{i1}+w_2x_{i2}+b$ and its predicted class-1 probability $p_i=\sigma(z_i)$. Thus $p_i$ is the model output for observation $i$; it is not its true label $y_i$. Write $p=(p_1,\ldots,p_N)^T$ when collecting all predictions. The training objective measures how well these probabilities match the known labels.
Calculate the BCE gradient step by step
For one observation, binary cross-entropy is the negative log-likelihood of its known class:
\[\ell_i=-y_i\log p_i-(1-y_i)\log(1-p_i).\]If $y_i=1$, this is $-\log p_i$: it decreases when the model raises the correct-class probability. If $y_i=0$, it is $-\log(1-p_i)$. We average the eight losses:
\[L(w,b)=\frac1N\sum_{i=1}^{N}\ell_i.\]Use the chain rule. First $d\sigma(z_i)/dz_i=p_i(1-p_i)$. Next $d\ell_i/dp_i=-y_i/p_i+(1-y_i)/(1-p_i)$. Multiplying and simplifying gives the particularly simple result
\[\frac{\partial\ell_i}{\partial z_i}=p_i-y_i.\]Since $\partial z_i/\partial w_1=x_{i1}$, $\partial z_i/\partial w_2=x_{i2}$ and $\partial z_i/\partial b=1$,
\[\frac{\partial L}{\partial w_j}=\frac1N\sum_{i=1}^{N}(p_i-y_i)x_{ij},\quad j=1,2;\qquad \frac{\partial L}{\partial b}=\frac1N\sum_{i=1}^{N}(p_i-y_i).\]In matrix form, $\nabla_wL=X^T(p-y)/N$. Gradient descent subtracts $\eta$ times each derivative. For a class-1 point predicted with very low probability, $p_i-y_i$ is close to $-1$; the update tends to increase its score through its coordinates. Contributions from the other points may reinforce or oppose it.
At the initial $w=b=0$, every $p_i=0.5$. Substitution of the eight rows below gives $\nabla_{w_1}L=-0.3125$, $\nabla_{w_2}L=-0.5$ and $\partial_bL=0$ up to floating-point rounding. With $\eta=0.1$, the first weights become $(0.03125,0.05)$: the unequal gradient components already rotate the line.
Backpropagation on this small example
The gradient formulas of the previous card were obtained by the chain rule. Backpropagation is the name of the way to organize this computation so that it stays cheap when the network has many layers: one pass forward to compute and store the values, then one pass backward to compute all the derivatives.
The computation of the loss is a graph: the inputs and the weights give $z$, then $p=\sigma(z)$, then the loss $\ell$. The forward pass evaluates this graph from the inputs to the loss and stores every intermediate value ($z_i$, $p_i$, $\ell_i$). The backward pass starts at the loss, where $\partial\ell/\partial\ell=1$, and moves toward the weights. At each node, the derivative with respect to its input is the derivative that arrives from the right (upstream) multiplied by the derivative of the node itself (local).
For one sample $(x_1,x_2,y)$, with $z=w_1x_1+w_2x_2+b$, $p=\sigma(z)$ and $\ell=-y\log p-(1-y)\log(1-p)$,
\[\frac{\partial\ell}{\partial z}=p-y,\qquad \frac{\partial\ell}{\partial w_1}=(p-y)\,x_1,\quad \frac{\partial\ell}{\partial w_2}=(p-y)\,x_2,\quad \frac{\partial\ell}{\partial b}=p-y.\]Proof
Go backward. The loss depends on $p$ only: $\partial\ell/\partial p=-y/p+(1-y)/(1-p)$. The sigmoid is a local node with $\sigma'(z)=p(1-p)$, so the derivative arriving at $z$ is $\dfrac{\partial\ell}{\partial z}=\dfrac{\partial\ell}{\partial p}\,p(1-p)=-y(1-p)+(1-y)p=p-y$. The node $z$ is a sum, so it sends this same number to each weight multiplied by the local derivative of the sum with respect to that weight: $\partial z/\partial w_1=x_1$, $\partial z/\partial w_2=x_2$, $\partial z/\partial b=1$. $\square$
A number you can check. At the initialization $w=(0,0)$, $b=0$, take the last sample $x=(3,1)$, $y=1$. Forward: $z=0$, $p=0.5$, $\ell=-\log0.5=0.693$. Backward: $\partial\ell/\partial p=-1/0.5=-2$, the local derivative is $0.5\cdot0.5=0.25$, hence $\partial\ell/\partial z=-0.5=p-y$, and $\partial\ell/\partial w_1=-0.5\cdot3=-1.5$, $\partial\ell/\partial w_2=-0.5$, $\partial\ell/\partial b=-0.5$. The loss $L$ of the course is the mean over the eight samples, so its gradient is the mean of the eight per-sample gradients; with the eight rows, this gives $(-0.3125,-0.5,0)$. One update with $\eta=0.1$ then gives $w=(0.03125,0.05)$.
Why backward? The factor $p-y$ is computed once and reused for the three parameters: each weight gets its derivative at the price of one multiplication. With many layers the same two passes are repeated layer by layer: if $\delta^{(l)}=\partial L/\partial z^{(l)}$ is the derivative at the scores of layer $l$, then $\delta^{(l)}=\big(W^{(l+1)\top}\delta^{(l+1)}\big)\odot\varphi'(z^{(l)})$ and $\partial L/\partial W^{(l)}=\delta^{(l)}a^{(l-1)\top}$. The backward pass costs about as much as the forward pass, and it needs the values stored by the forward pass. This is exactly what tf.GradientTape does in the next code: it records the forward pass, then tape.gradient replays it backward. Training is the loop forward, loss, backward, update, which the lab below lets you run step by step.
Why use BCE rather than least squares here?
There are two different squared-error choices. Squaring $z_i-y_i$ treats an unrestricted affine score as a numeric regression target; scores need not lie between 0 and 1, so this objective does not describe a Bernoulli label. Squaring the probability $p_i-y_i$ keeps a sigmoid output, but changes the gradient.
For the half-squared probability error $Q_i=\tfrac12(p_i-y_i)^2$, the chain rule gives $dQ_i/dz_i=(p_i-y_i)p_i(1-p_i)$. Compare this with $d\ell_i/dz_i=p_i-y_i$ for BCE. When $z_i=-6$ and $y_i=1$, the model is confidently wrong: $p_i\approx0.00247$. The BCE derivative is about $-0.99753$; the half-squared error derivative is about $-0.00246$. The extra $p_i(1-p_i)$ factor makes a correction much smaller for this saturated example.
Both objectives can be optimized in suitable settings. The point here is that BCE matches the Bernoulli model of binary labels and gives this useful gradient behavior. A sigmoid neuron with BCE remains a smooth optimization problem; unlike ordinary affine least squares, it has no normal-equation solution. For linearly separable data, the unregularized BCE can keep decreasing as the weight norm grows.
Keras workflow: data, fit, then inference
Run this first self-contained program. It creates the eight labelled rows, declares a one-neuron sigmoid model, chooses SGD with step size 0.1 and BCE, then calls fit for 200 full-batch epochs. Finally, it reads the learned kernel and bias and predicts four new points.
# Complete Keras workflow: data, optimizer, fit, then inference.import numpy as npimport tensorflow as tffrom tensorflow import keraskeras.utils.set_random_seed(12)# Eight planar observations, with a deliberately oblique separating line.X = np.array([[-2,-1],[-1,-1],[0,-1],[1,-1], [-1,1],[0,1],[1,1],[3,1]], dtype='float32')y = np.array([[0],[0],[0],[0],[1],[1],[1],[1]], dtype='float32')print('Data shapes:', X.shape, y.shape)model = keras.Sequential([ keras.Input(shape=(2,)), # Dense learns a kernel K (inputs x units) AND a bias vector b, one bias per neuron (use_bias=True by default) keras.layers.Dense(1, activation='sigmoid', kernel_initializer='zeros', bias_initializer='zeros')])model.compile(optimizer=keras.optimizers.SGD(learning_rate=0.1), loss=keras.losses.BinaryCrossentropy())history = model.fit(X, y, epochs=200, batch_size=8, shuffle=False, verbose=0)print('BCE: first and last epoch:', history.history['loss'][0], history.history['loss'][-1])print('Learned kernel and bias:', model.layers[0].get_weights())new_points = np.array([[-1,0],[0,0],[0,1],[2,0]], dtype='float32')probabilities = model(new_points, training=False).numpy().ravel()classes = (probabilities >= 0.5).astype(int)for point, probability, predicted in zip(new_points, probabilities, classes): print('Point', point, 'sigma(z) =', round(float(probability), 4), 'predicted class =', predicted)
Xis float32 with two columns.yis a binary column with the same number of rows. Printing the shapes catches an input/target mismatch before training.Dense(1, activation="sigmoid")returns probabilities.BinaryCrossentropy()therefore uses its defaultfrom_logits=False. The kernel has shape (2,1); the bias shape (1,).compileconnects the optimizer and loss to the model.fitcalculates predictions, loss, gradients and updates for each batch. Withbatch_size=8, every epoch uses all eight observations in one update;shuffle=Falsemakes the order explicit.history.history['loss']reports training loss by epoch.get_weights()reads the final kernel and bias. The two weights are different because the two input coordinates contribute differently to separating the chosen points.model(new_points, training=False)performs inference with fixed learned parameters. The threshold at 0.5 converts each probability into a class. Inspect probabilities as well as the classes; a point near the learned line is naturally less decisive.
On the verified CPU run, the kernel is approximately $(0.4512,2.7699)^T$, the bias $-0.0219$, and final BCE about 0.0538. The exact last digits can vary by environment. These outputs are training results on eight points, not an estimate of performance on a broader population.
See the gradients: inspect what fit normally handles
The previous fit program trains the classifier concisely. To understand the mechanism, we now inspect the gradient at the first update and record how $w_1$, $w_2$, $b$ and BCE change over 200 updates. fit performs those computations internally, but its usual return value gives epoch-level losses, not the raw gradient and parameter vector at each update. We therefore write the same full-batch SGD step explicitly with tf.GradientTape.
This second program starts again from the same zero weights; it does not continue training the previous model. Inside the tape, Keras calculates sigmoid probabilities and BCE. The tape differentiates the loss with respect to the Dense kernel and bias; SGD applies the update. Read the first gradient before looking at the printed later parameters.
# Data, one sigmoid neuron, and 200 explicit gradient updates.import numpy as npimport tensorflow as tffrom tensorflow import keraskeras.utils.set_random_seed(12)# Class 0 is mostly below the oblique line x1 + 2*x2 = 0.5.X = np.array([[-2,-1],[-1,-1],[0,-1],[1,-1], [-1,1],[0,1],[1,1],[3,1]], dtype='float32')y = np.array([[0],[0],[0],[0],[1],[1],[1],[1]], dtype='float32')model = keras.Sequential([ keras.Input(shape=(2,)), # Dense learns a kernel K (inputs x units) AND a bias vector b, one bias per neuron (use_bias=True by default) keras.layers.Dense(1, activation='sigmoid', kernel_initializer='zeros', bias_initializer='zeros')])loss_function = keras.losses.BinaryCrossentropy()optimizer = keras.optimizers.SGD(learning_rate=0.1)weights, biases, losses = [], [], []for step in range(201): probabilities = model(X, training=False) weights.append(model.layers[0].kernel.numpy().ravel().copy()) biases.append(float(model.layers[0].bias.numpy()[0])) losses.append(float(loss_function(y, probabilities))) if step in [0, 1, 10, 50, 200]: print(step, 'w =', weights[-1], 'b =', biases[-1], 'BCE =', losses[-1]) if step < 200: with tf.GradientTape() as tape: probabilities = model(X, training=True) loss = loss_function(y, probabilities) gradients = tape.gradient(loss, model.trainable_variables) if step == 0: print('First gradient:', [g.numpy() for g in gradients]) optimizer.apply_gradients(zip(gradients, model.trainable_variables))
The arrays weights, biases and losses hold states before each update, including the final state after 200 updates. On the verified run, the first kernel gradient is $(-0.3125,-0.5)^T$ and the bias gradient is essentially zero. The final weights are about $(0.45115,2.76991)^T$, bias $-0.02192$ and BCE 0.05358. The slight distinction between the final explicit loss and the final fit history value comes from when each reports loss: the explicit loop measures after the last update, while fit records its batch loss during that update.
Plot the boundary, both weights, the bias and the loss
Run this plotting block after the explicit-gradient program. It uses the recorded arrays to draw the line after steps 1, 10 and 200, then plots $w_1$, $w_2$, $b$ and the BCE history. The line calculation solves $x_2=-(w_1x_1+b)/w_2$; here $w_2$ is nonzero for all plotted states. A different dataset could yield a vertical boundary and require a separate plotting case.
# Run after separator.py: X, y, weights, biases and losses are available.import numpy as npimport matplotlib.pyplot as pltweights = np.array(weights)fig, axes = plt.subplots(1, 3, figsize=(13, 4))axes[0].scatter(X[:,0], X[:,1], c=y.ravel(), cmap='coolwarm', edgecolors='black')u = np.linspace(-3.2, 3.2, 100)for step in [1, 10, 200]: w = weights[step] v = -(w[0]*u + biases[step])/w[1] axes[0].plot(u, v, label='Step '+str(step))axes[0].set(xlim=(-3.2,3.2), ylim=(-2.5,2.5), xlabel='x1', ylabel='x2')axes[0].legend()axes[1].plot(weights[:,0], label='w1')axes[1].plot(weights[:,1], label='w2')axes[1].plot(biases, label='b')axes[1].set_xlabel('Gradient updates')axes[1].legend()axes[2].plot(losses)axes[2].set(xlabel='Gradient updates', ylabel='Mean BCE')plt.tight_layout()plt.show()
Part 3 · Layers, activations and learned XOR with tanh
A multilayer perceptron changes the representation
A Dense layer applies multiple neurons in parallel. With observations in rows, $H=\phi(XK_1+b_1)$ and $z=HK_2+b_2$. Keras stores $K_1$ as (inputs, hidden units). Each connection carries a weight; each bias is equivalently the weight of a constant +1 input.
Without a nonlinear activation, $(XK_1+b_1)K_2+b_2=X(K_1K_2)+(b_1K_2+b_2)$ remains affine. Stacking affine layers cannot solve XOR. With nonlinear activations, hidden units can construct features that separate the classes.
Two hidden neurons without a nonlinear activation cannot solve XOR
Take the four XOR points: class 0 at $(0,0)$ and $(1,1)$, class 1 at $(0,1)$ and $(1,0)$. Let $z(x)=\big(xK_1+b_1\big)K_2+b_2$ be a network with two hidden neurons (or any number of them) whose activation is linear ($\phi(u)=u$, as with no activation function), followed by the sigmoid and the threshold $0.5$. Then no choice of the weights classifies the four points correctly.
Proof
Step 1 · with linear activations the network is only affine. With $K_1\in\mathbb R^{2\times2}$, $b_1\in\mathbb R^{2}$, $K_2\in\mathbb R^{2\times1}$, $b_2\in\mathbb R$,
\[z(x)=(xK_1+b_1)K_2+b_2=x\,(K_1K_2)+(b_1K_2+b_2)=w^Tx+b,\]with $w=K_1K_2\in\mathbb R^2$ and $b=b_1K_2+b_2\in\mathbb R$. The two hidden neurons disappear: the model is a single neuron. The class is 1 when $\sigma(z)>\tfrac12$, i.e. when $z(x)>0$.
Step 2 · an affine function cannot give XOR. Suppose the points of class 1 have $z>0$ and those of class 0 have $z\le0$. Because $z$ is affine, its value at the midpoint of two points is the mean of their values. The point $(\tfrac12,\tfrac12)$ is the midpoint of $(0,1)$ and $(1,0)$, and also of $(0,0)$ and $(1,1)$. Hence
\[\underbrace{z\big(\tfrac12,\tfrac12\big)=\tfrac12\big(z(0,1)+z(1,0)\big)>0}_{\text{class 1 points}}\qquad\text{and}\qquad \underbrace{z\big(\tfrac12,\tfrac12\big)=\tfrac12\big(z(0,0)+z(1,1)\big)\le0}_{\text{class 0 points}},\]which is a contradiction. If the signs are reversed (class 1 for $z<0$), the same argument gives the same contradiction with the inequalities reversed. $\square$
What changes with a nonlinear activation. The collapse of Step 1 uses a linear activation $\phi(u)=u$: it needs $\phi(xK_1+b_1)K_2$ to be linear in $xK_1$. With ReLU and two hidden neurons, $h_1=\mathrm{ReLU}(x_1+x_2)$ and $h_2=\mathrm{ReLU}(x_1+x_2-1)$ give the output $h_1-2h_2=0,1,1,0$ on the four points (the network of Part 1). The hidden layer bends the plane, and the classes become separable in the $(h_1,h_2)$ plane.
The model has $(2+1)8+(8+1)1=33$ parameters. The input layer has no trainable parameters. A batch of four rows produces hidden shape (4,8), then output shape (4,1).
The classical result explaining why one hidden layer is enough in principle is the universal approximation theorem: functions $F(x)=\sum_{i=1}^N\alpha_i\,\phi(\omega_i^Tx+b_i)$, a network with one hidden layer of $N$ neurons and a linear output, can approximate any continuous function on a compact set. The theorem says nothing about how many neurons are needed or about how to find the weights by training.
Universal approximation (Cybenko, Hornik)
Let $\phi:\mathbb R\to\mathbb R$ be continuous, bounded, non-constant and non-decreasing, and let $I_m=[0,1]^m$. For every $f\in\mathcal C(I_m)$ and every $\varepsilon>0$ there exist $N\in\mathbb N$, $\alpha_i,b_i\in\mathbb R$ and $\omega_i\in\mathbb R^m$ such that
$$F(x)=\sum_{i=1}^N\alpha_i\,\phi(\omega_i^Tx+b_i)\quad\text{satisfies}\quad \forall x\in I_m,\ |F(x)-f(x)|<\varepsilon .$$In other words, the functions of the form $F$ are dense in $\mathcal C(I_m)$ for the uniform norm.
Proof
Let $S$ be the vector space of functions $x\mapsto\sum_i\alpha_i\phi(\omega_i^Tx+b_i)$ and $\bar S$ its closure for the uniform norm on $I_m$; $\bar S$ is a vector space. Taking $\omega=0$ shows that $S$ contains the constants $\phi(b)$, hence all constants because $\phi\not\equiv0$.
Step 1: dimension one. Being monotone, bounded and non-constant, $\phi$ has limits $a<c$ at $-\infty$ and $+\infty$. Put $\psi=(\phi-a)/(c-a)$: it is non-decreasing with limits $0$ and $1$, hence $0\le\psi\le1$. Let $g$ be continuous on $[-R,R]$ and $\varepsilon>0$. By uniform continuity, choose $\delta$ with $|g(s)-g(t)|<\varepsilon/2$ whenever $|s-t|<\delta$, a subdivision $-R=t_0<\dots<t_n=R$ of mesh smaller than $\delta/2$, and $\eta<\delta/2$ smaller than half the mesh. Set $d_j=g(t_j)-g(t_{j-1})$ and
$$G_\lambda(t)=g(t_0)+\sum_{j=1}^n d_j\,\psi\big(\lambda(t-t_j)\big).$$$G_\lambda$ is a sum of constants and terms $\phi(\lambda t+b)$, so it lies in $S$ (one variable). Choose $\lambda$ so large that $\psi(\lambda u)$ is within $\gamma$ of $0$ for $u\le-\eta$ and of $1$ for $u\ge\eta$, where $\gamma\sum_j|d_j|<\varepsilon/4$. If $t\in[t_{k-1}+\eta,\,t_k-\eta]$, all steps $j\le k-1$ are on, all steps $j\ge k$ are off, so $|G_\lambda(t)-g(t_{k-1})|<\varepsilon/4$, and $|g(t)-g(t_{k-1})|<\varepsilon/2$: the error is below $3\varepsilon/4$. If $|t-t_k|<\eta$, only the $k$-th step is undecided with value $\theta\in[0,1]$, so $G_\lambda(t)$ is within $\varepsilon/4$ of $g(t_{k-1})+\theta d_k$, a number between $g(t_{k-1})$ and $g(t_k)$, both within $\varepsilon/2$ of $g(t)$. Hence $\|G_\lambda-g\|_\infty<\varepsilon$.
Step 2: cosines. Fix $\omega\in\mathbb R^m$ and $b\in\mathbb R$. For $x\in I_m$, $t=\omega^Tx$ lies in $[-R,R]$ with $R=\|\omega\|\sqrt m$. Step 1 applied to $g(t)=\cos(t+b)$ gives $\sum_i\alpha_i\phi(\lambda_it+b_i)$ uniformly close to it; replacing $t$ by $\omega^Tx$ gives an element of $S$ uniformly close to $x\mapsto\cos(\omega^Tx+b)$ on $I_m$. So these functions belong to $\bar S$, and so does the vector space $A$ they span.
Step 3: Stone–Weierstrass. $A$ is an algebra, since $\cos u\cos v=\tfrac12[\cos(u-v)+\cos(u+v)]$. It contains the constants ($\omega=0$, $b=0$). It separates points: if $x\ne y$ in $I_m$, take $\omega=s(x-y)$ with $s>0$ so small that $|\omega^Tx|,|\omega^Ty|<\pi/2$, and $b=-\pi/2$, so that $\cos(\omega^Tx+b)=\sin(\omega^Tx)\ne\sin(\omega^Ty)$ because $\sin$ is strictly increasing on $(-\pi/2,\pi/2)$ and $\omega^T(x-y)=s\|x-y\|^2>0$. By the Stone–Weierstrass theorem, $A$ is dense in $\mathcal C(I_m)$. Since $A\subset\bar S$ and $\bar S$ is closed, $\bar S=\mathcal C(I_m)$. $\square$
Why tanh?
$\tanh(u)=(e^u-e^{-u})/(e^u+e^{-u})$ is smooth, odd and centered on zero, with values in $(-1,1)$. Its derivative is $1-\tanh^2(u)$. Positive and negative activations can combine to form useful features. Near zero its slope is close to one; far from zero it saturates and gradients become small. This is a tradeoff, not a claim that tanh is always preferable to ReLU.
For the output residual $R=(\sigma(z)-y)/N$, backpropagation gives $G_{K_2}=H^TR$ and hidden residual $D=(RK_2^T)\odot(1-H^2)$, followed by $G_{K_1}=X^TD$. Bias gradients are row sums. Keras computes these chain-rule derivatives automatically.
Train the weights rather than impose them
import numpy as npimport tensorflow as tffrom tensorflow import keraskeras.utils.set_random_seed(7)X = np.array([[0,0],[0,1],[1,0],[1,1]],dtype='float32')y = np.array([[0],[1],[1],[0]],dtype='float32')model = keras.Sequential([ keras.Input(shape=(2,)), # Dense learns a kernel K (inputs x units) AND a bias vector b, one bias per neuron (use_bias=True by default) keras.layers.Dense(8,activation='tanh'), keras.layers.Dense(1)])model.compile(optimizer=keras.optimizers.Adam(0.03), loss=keras.losses.BinaryCrossentropy(from_logits=True))history = model.fit(X,y,epochs=1500,batch_size=4,shuffle=False,verbose=0) # 1500 epochs; one batch = the 4 rows = one update per epochlosses = history.history['loss'] # training BCE after each epochprint('Probabilities:',tf.sigmoid(model(X)).numpy().ravel())print('Parameters:',model.count_params())
- The seed fixes one initialization. Different seeds or software versions can change the trajectory.
- Eight hidden tanh units provide more flexibility than the minimal two-unit ReLU construction. They start with random kernels to break symmetry.
- The output is affine, so BCE receives logits with
from_logits=True. Adam updates the parameters; its learning rate is 0.03. fitruns 1500 epochs; withbatch_size=4each epoch is one update on the four rows, andhistory.history['loss']records the training BCE of each epoch.- The probability map and loss curve show the result. Inspect all four printed probabilities and the 0.5 contour.
Plot the learned tanh network
# Run after xor_tanh.py: model, X, y and losses are available.import numpy as npimport matplotlib.pyplot as pltimport tensorflow as tfu = np.linspace(-.2,1.2,160)a,b = np.meshgrid(u,u)grid = np.column_stack([a.ravel(),b.ravel()]).astype('float32')probabilities = tf.sigmoid(model(grid,training=False)).numpy().reshape(a.shape)fig,axes = plt.subplots(1,2,figsize=(10,4))axes[0].plot(losses)axes[0].set(xlabel='Epoch (one full-batch update)',ylabel='Training BCE')axes[1].contourf(a,b,probabilities,levels=np.linspace(0,1,21),cmap='coolwarm')axes[1].contour(a,b,probabilities,levels=[.5],colors='black')axes[1].scatter(X[:,0],X[:,1],c=y.ravel(),cmap='coolwarm',edgecolors='black')axes[1].set(xlabel='x1',ylabel='x2',title='Learned probability and σ(z) = 0.5 boundary')plt.tight_layout()plt.show()
The first plot follows the training loss recorded by fit at each epoch. The second evaluates the fixed trained model on a fine input grid and draws the $\sigma(z)=0.5$ boundary. It reuses model, X, y and losses from Step 1.
All Boolean inputs are in training. Correctly recovering these four labels verifies representation of the truth table, not independent generalization to an unseen distribution. The off-corner extension is not uniquely determined.
Part 4 · Exercise: Spam or Ham with a Keras MLP
Start with the messages and a word dictionary
Use the original labelled SMS file. Save it as sms.txt beside the Python program. Each line contains ham or spam, a tab, then a message. Encode ham as 0 and spam as 1.
A neural network needs numbers, not raw strings. Begin by finding the 3,000 words that occur in the most training messages. Give each word a column number: for example, if free has column 7, that column describes the presence of free in every message. This vocabulary step resembles the indexing needed before Word2Vec, but the vectors built here are multi-hot presence vectors. Word2Vec instead learns dense word embeddings from context.
Training, validation and test: three different jobs
The goal of a classifier is not to be right on the messages it has seen, but on new messages. A model with enough parameters can memorize its training messages (here a hidden layer has $3000\times16+16=48{,}016$ weights for about 3,100 messages), so the score on the training messages says very little about the score on new ones. We therefore cut the messages into three groups with three different roles.
| Training | Validation | Test | |
|---|---|---|---|
| Question | What are the best weights? | Which model and which settings are best? | How well will the final model do on new messages? |
| Used for | gradients, updates of the weights, vocabulary, normalization | reading the curves, stopping, choosing the architecture, the learning rate, the number of epochs and the 0.5 threshold | one final measurement |
| In the code | fit(x_train_vec, y_train), Counter on x_train | validation_data=(x_valid_vec, y_valid) | confusion_matrix(y_test, …) at the end |
| Bias of its score | optimistic: the model was fitted to it | slightly optimistic: we chose the model because it scores well here | none, if it was used only once |
An analogy. The training messages are the exercises you work through with their answers; the validation messages are the mock exams you take to decide how to revise; the test messages are the real exam, whose subject you must not know in advance. If you look at the real exam to choose what to revise, its mark no longer measures what you know.
Why two held-out groups and not one? Each time we compare two models, or two thresholds, on the validation messages and keep the best one, we adapt a little to them. After many choices the validation score is too good, in the same way that a training score is. The test group, never used for any decision, gives the honest final score. It may only be used once: if the test result makes you change the model, the test has become a second validation set and you need new data.
How to read the learning curves (the figure of the exercise). The training loss decreases almost always. The validation loss decreases, then stops or increases when the model begins to memorize: this is overfitting. A large gap between the training and the validation accuracy is the same signal. In the exercise, the MLP reaches an accuracy close to 1.00 on the training messages and stays near 0.98 on the validation messages.
Typical mistakes (data leakage). (1) Building the vocabulary on all the messages: information from the validation and test messages enters the model. (2) Keeping duplicates: the same message may fall in training and in test and be “recognized”. (3) Choosing the threshold, or the number of epochs, with the test group. (4) Splitting without stratify: spam is rare, and a group could contain too few spam messages to give a stable score. This is why the code removes the duplicates, splits first, and learns everything on the training messages only.
Guided exercise · build the data representation
- Read the SMS file, split each line at the first tab, and remove exact duplicate messages. Why must the labels stay paired with their messages?
- Split the raw messages into stratified training, validation and test groups in proportions 60/20/20. Why must the vocabulary be learned from training messages only?
- Lowercase each training message and extract words. Count each word once per message; retain the 3,000 most frequent and build a
word → columndictionary. What happens to words absent from this dictionary? - Create a matrix with one row per message and one column per retained word. Put 1 when the word occurs and 0 otherwise. Predict the shape of the training matrix and explain what a row loses about the original sentence.
- Build a Keras network with 16 ReLU hidden neurons and one sigmoid output. Choose BCE and Adam, train for 12 epochs with validation data, and plot the evolution of the loss and of the accuracy on the training and validation messages (the expected display is shown under the scaffold). Then report the test confusion matrix, spam precision and spam recall. Compare it with a single sigmoid neuron if time permits.
Accuracy alone can hide missed spam when ham is much more common. Decide on a threshold using validation data before evaluating test data.
Python scaffold · complete the network and fit
The scaffold performs reading, splitting, dictionary creation and manual vectorization. Run it to inspect the first vocabulary entries and matrix shapes. Continue from the open tasks at the end; design the model and training call yourself before reading the correction.
# Download sms.txt and put it beside this script.# Goal of this part: turn raw text messages into fixed-size numeric vectors that a Dense network can read.from collections import Counter # Counter: a dictionary word -> number of occurrencesfrom pathlib import Path # Path: read a text file in one lineimport re # re: regular expressions, used to cut a message into wordsimport numpy as np # numpy: arrays of numbersfrom sklearn.model_selection import train_test_split # splits the data into training / validation / test groupsfrom tensorflow import keras # Keras: the neural network librarykeras.utils.set_random_seed(23) # fixes the seeds of Python, NumPy and TensorFlow: same weights at each run# ---- 1. Read the file: one line = "ham<TAB>message" or "spam<TAB>message" ----------------------------messages, labels = [], [] # two parallel lists: messages[i] has the label labels[i]seen = set() # messages already read, to drop exact duplicatesfor line in Path('sms.txt').read_text(encoding='utf-8-sig').splitlines(): # utf-8-sig removes an invisible BOM at the start label, tab, message = line.partition('\t') # cut at the FIRST tab: (text before, the tab, text after) if tab and label in ('ham', 'spam') and message and message not in seen: # valid line, non-empty, not seen yet seen.add(message) # remember it: a duplicate in two groups would leak test data into training messages.append(message) labels.append(int(label == 'spam')) # ham -> 0, spam -> 1 (the network outputs the probability of spam)messages = np.array(messages, dtype=str) # arrays allow indexing with lists of positions (needed by train_test_split)labels = np.array(labels, dtype='int32')# ---- 2. Split BEFORE building the vocabulary: validation and test messages must stay unseen -----------x_train, x_rest, y_train, y_rest = train_test_split( messages, labels, test_size=0.4, stratify=labels, random_state=23) # 60% train; stratify keeps the spam rate equal in each groupx_valid, x_test, y_valid, y_test = train_test_split( x_rest, y_rest, test_size=0.5, stratify=y_rest, random_state=23) # the remaining 40% -> 20% validation + 20% test# ---- 3. Vocabulary: the 3,000 words found in the most TRAINING messages -------------------------------counts = Counter() # counts[word] = number of training messages containing the wordfor message in x_train: words = set(re.findall(r"[a-z0-9']+", message.lower())) # lowercase, extract letters/digits/apostrophes; set(): once per message counts.update(words) # add 1 to the counter of each distinct word of this messagevocabulary = [word for word, count in counts.most_common(3000)] # the 3,000 most frequent words, most frequent firstword_to_column = {word: column for column, word in enumerate(vocabulary)} # word -> column number (0 to 2999)print('First ten words:', vocabulary[:10])# ---- 4. Multi-hot vectors: one row per message, one column per word, 1 = "the word is present" ---------matrices = []for group in (x_train, x_valid, x_test): # the SAME dictionary transforms the three groups matrix = np.zeros((len(group), len(vocabulary)), dtype='float32') # starts with only zeros; float32 is what Keras expects for row, message in enumerate(group): for word in set(re.findall(r"[a-z0-9']+", message.lower())): # distinct words of the message column = word_to_column.get(word) # None if the word is not in the vocabulary if column is not None: # unknown words are ignored: their information is lost matrix[row, column] = 1.0 # presence, not number of occurrences matrices.append(matrix)x_train_vec, x_valid_vec, x_test_vec = matricesprint('Train, validation, test shapes:', x_train_vec.shape, x_valid_vec.shape, x_test_vec.shape) # (number of messages, 3000)# ---- 5. Your part --------------------------------------------------------------------------------# TODO: Choose and build a network for these multi-hot rows. (input size 3000, output: one probability)# TODO: Compile and train it using the validation split. (loss for a binary label, validation_data=...)# TODO: Plot the evolution of the loss and of the accuracy (training and validation) with the History returned by fit.# TODO: Evaluate its predictions on the untouched test split. (use the test set only once, at the end)
set(...) counts each word once per SMS and produces a binary row later. The same dictionary transforms validation and test; unknown words simply leave all known-word columns unchanged. The split happens before counting to avoid information leaking from held-out messages.
Show the correction
Open this complete correction after trying the scaffold. It uses the same word dictionary and trains both the requested MLP and a single-neuron baseline on the same split.
# Place sms.txt beside this script before running it.from collections import Counter # dictionary word -> number of occurrencesfrom pathlib import Path # reads a text file in one lineimport re # regular expressions: cut a message into wordsimport numpy as np # arrays of numbersimport matplotlib.pyplot as plt # plots of the learning curvesfrom sklearn.model_selection import train_test_split # train / validation / test splitfrom sklearn.metrics import confusion_matrix, precision_score, recall_score # metrics of a classifierfrom tensorflow import keras # neural network librarykeras.utils.set_random_seed(23) # same initial weights and same shuffling at every run# 1. Read labels and messages, then remove exact duplicate messages.messages, labels = [], [] # parallel lists: messages[i] <-> labels[i] (they must stay paired)seen = set() # messages already metfor line in Path('sms.txt').read_text(encoding='utf-8-sig').splitlines(): # one line = "label<TAB>message" label, tab, message = line.partition('\t') # cut at the first tab only: a message may contain other tabs if tab and label in ('ham', 'spam') and message and message not in seen: # ignore malformed, empty and duplicate lines seen.add(message) messages.append(message) labels.append(int(label == 'spam')) # ham = 0, spam = 1messages = np.array(messages, dtype=str)labels = np.array(labels, dtype='int32')# 2. Split raw messages before learning which words are frequent.# If the vocabulary used the test messages, the test would no longer simulate new, unseen SMS.x_train, x_rest, y_train, y_rest = train_test_split( messages, labels, test_size=0.4, stratify=labels, random_state=23) # 60% training; stratify = same spam proportion everywherex_valid, x_test, y_valid, y_test = train_test_split( x_rest, y_rest, test_size=0.5, stratify=y_rest, random_state=23) # 20% validation (choose the model) + 20% test (final check)# 3. Count document frequency on training messages only.counts = Counter()for message in x_train: words = set(re.findall(r"[a-z0-9']+", message.lower())) # lowercase; words = letters, digits, apostrophes; set() = once per message counts.update(words) # +1 for every distinct word of this messagevocabulary = [word for word, count in counts.most_common(3000)] # 3,000 most frequent wordsword_to_column = {word: column for column, word in enumerate(vocabulary)} # word -> column of the multi-hot matrixprint('First ten words:', vocabulary[:10])print('Vocabulary size:', len(vocabulary))# 4. Make one multi-hot row per message. Unknown words are ignored.matrices = []for group in (x_train, x_valid, x_test): # the same dictionary for the three groups matrix = np.zeros((len(group), len(vocabulary)), dtype='float32') # (messages, 3000), all zeros at the start for row, message in enumerate(group): for word in set(re.findall(r"[a-z0-9']+", message.lower())): column = word_to_column.get(word) # column of the word, or None if it is out of vocabulary if column is not None: matrix[row, column] = 1.0 # the word is present in this message matrices.append(matrix)x_train_vec, x_valid_vec, x_test_vec = matricesprint('Vector shapes:', x_train_vec.shape, x_valid_vec.shape, x_test_vec.shape)histories = {} # name -> learning curves of each model# 5. Train a linear baseline and a one-hidden-layer MLP, on exactly the same data.# Why a loop over two models? A score alone means little: we need a reference.# - ('single neuron', 0): no hidden layer, so the model is Dense(1, sigmoid) = logistic regression on the 3000 word columns.# It is the simplest model, the one to try first and the baseline to beat.# - ('MLP', 16): the same model with 16 ReLU hidden neurons, which can combine words (for example "free" AND "call").# The loop changes only hidden_units; data, optimizer, loss, epochs, batch size and evaluation are the same,# so a difference in the scores comes from the hidden layer. (Check also that the baseline has converged:# its curves are still decreasing after 12 epochs, so part of the gap is training speed.)# One loop also means one code: nothing can differ by accident between the two versions.for name, hidden_units in [('single neuron', 0), ('MLP', 16)]: # name labels the prints and the curves; 0 = no hidden layer layers = [keras.Input(shape=(len(vocabulary),))] # input: one row of 3000 values (0 or 1) if hidden_units: # 0 is False: the hidden layer is added only for the MLP layers.append(keras.layers.Dense(hidden_units, activation='relu')) # hidden layer: 3000*16 weights + 16 biases = 48,016 parameters layers.append(keras.layers.Dense(1, activation='sigmoid')) # output: probability that the message is spam (weights + one bias) model = keras.Sequential(layers) # stack the layers in the order of the list model.compile(optimizer=keras.optimizers.Adam(0.001), # Adam: gradient descent with adaptive steps, learning rate 0.001 loss=keras.losses.BinaryCrossentropy(), # BCE for one probability and a 0/1 label (sigmoid output) metrics=['accuracy']) # also record the accuracy (fraction of correct classes) at each epoch history = model.fit(x_train_vec, y_train, # training data: the gradient updates use these only validation_data=(x_valid_vec, y_valid), # the loss on these is measured but never trained on epochs=12, batch_size=64, verbose=0) # 12 passes over the data, an update every 64 messages; verbose=0: silent histories[name] = history.history # keys: loss, accuracy, val_loss, val_accuracy (one value per epoch) print(name, 'last validation BCE:', round(history.history['val_loss'][-1], 4)) # history: one value per epoch # 6. Inspect the untouched test set once the model is fixed. probabilities = model(x_test_vec, training=False).numpy().ravel() # call the model: (n,1) probabilities -> flat vector predicted = (probabilities >= 0.5).astype('int32') # threshold 0.5: probability -> class 0 (ham) or 1 (spam) print(name, 'confusion matrix (true rows, predicted columns):') print(confusion_matrix(y_test, predicted, labels=[0, 1])) # [[ham ok, ham called spam], [spam missed, spam found]] print('Spam precision:', round(precision_score(y_test, predicted, zero_division=0), 3)) # found spam / messages called spam print('Spam recall:', round(recall_score(y_test, predicted, zero_division=0), 3)) # found spam / real spam# 7. Learning curves: evolution of the loss and of the accuracy, on the training and on the validation messages.fig, axes = plt.subplots(1, 2, figsize=(11, 4))for name, h in histories.items(): axes[0].plot(range(1, 13), h['loss'], label=name + ' · training') # solid: data used for the updates axes[0].plot(range(1, 13), h['val_loss'], '--', label=name + ' · validation') # dashed: held-out data axes[1].plot(range(1, 13), h['accuracy'], label=name + ' · training') axes[1].plot(range(1, 13), h['val_accuracy'], '--', label=name + ' · validation')axes[0].set(xlabel='epoch', ylabel='binary cross-entropy', title='Loss') # the quantity that is minimizedaxes[1].set(xlabel='epoch', ylabel='accuracy', title='Accuracy') # an easier quantity to read, not optimized directlyaxes[0].legend(); axes[1].legend()plt.tight_layout(); plt.show() # a gap between solid and dashed curves means overfitting
Read the result: each matrix has 3,000 columns, one per retained word. The first Dense kernel therefore has shape $(3000,16)$ for the MLP. The confusion matrix has true classes as rows and predictions as columns, ordered ham then spam. Spam precision measures the fraction of spam predictions that are correct; spam recall measures the fraction of real spam found. A different tokenizer or split may change the scores, and even two runs of the same code can differ in the last digits (parallel floating-point sums on the CPU).
Why train two models in a loop? A score alone means little: we need a reference. The first model, ('single neuron', 0), has no hidden layer: it is Dense(1, sigmoid), a logistic regression on the 3,000 word columns. It is the simplest model, the one to try first and the baseline to beat. The second, ('MLP', 16), adds 16 ReLU hidden neurons, which can combine words (for example “free” and “call” together). The loop changes only hidden_units; the messages, the split, Adam, the BCE loss, 12 epochs, the batch size and the evaluation are identical, so a difference in the scores comes from the hidden layer, and one loop guarantees that no setting differs by accident between the two versions. In this run the single neuron finds about 72 % of the spam and the MLP about 88 %, with a precision of 1.0 for both; the validation BCE is about 0.21 against 0.08. Caution: the curves of the single neuron are still decreasing after 12 epochs, so part of the gap is training speed and not only capacity; for a rigorous comparison, train the baseline longer and repeat with several seeds.
Why automate the text preprocessing?
The manual code makes every step visible, but it repeats tokenization and column lookup for each group. A production preprocessing layer can keep the learned vocabulary and its transformation together. This reduces the chance of accidentally using different rules for training and inference. The manual tokenizer above keeps apostrophes and counts presence by message; Keras defaults use their own standardization and tokenization rules, so the resulting columns and scores need not match exactly.
TextVectorization performs lowercase/standardization, learns a vocabulary with adapt, then creates multi-hot rows. Call adapt(x_train) only on training messages; transform validation and test with that same layer. Its max_tokens=3000 includes reserved token slots, so its number of ordinary word columns can differ from the manual top 3,000. The following continuation runs after the complete correction, using its existing split and imports.
# Run after spam_ham.py: reuse x_train, x_valid, x_test and their labels.# TextVectorization does the tokenization, the vocabulary and the multi-hot encoding of the manual code in one Keras layer.vectorizer = keras.layers.TextVectorization( max_tokens=3000, # vocabulary size, including 2 reserved slots (padding and unknown word) output_mode='multi_hot') # one 0/1 column per vocabulary word, as in the manual codevectorizer.adapt(x_train) # learns the vocabulary from the TRAINING messages onlytrain_auto = vectorizer(x_train).numpy() # the same layer transforms the three groups:valid_auto = vectorizer(x_valid).numpy() # the rules of training and inference cannot differtest_auto = vectorizer(x_test).numpy()print('TextVectorization vocabulary size:', len(vectorizer.get_vocabulary()))print('Automatic vector shapes:', train_auto.shape, valid_auto.shape, test_auto.shape)auto_model = keras.Sequential([ # the same MLP as before: only the input vectors change keras.Input(shape=(train_auto.shape[1],)), keras.layers.Dense(16, activation='relu'), # 16 hidden neurons: kernel (3000, 16) and a bias vector of 16 values keras.layers.Dense(1, activation='sigmoid'), # probability of spam])auto_model.compile(optimizer=keras.optimizers.Adam(0.001), loss=keras.losses.BinaryCrossentropy())auto_history = auto_model.fit(train_auto, y_train, validation_data=(valid_auto, y_valid), # monitored, never used for the updates epochs=12, batch_size=64, verbose=0)print('Automatic vectorizer validation BCE:', round(auto_history.history['val_loss'][-1], 4))auto_probabilities = auto_model(test_auto, training=False).numpy().ravel() # test set, used onceauto_predicted = (auto_probabilities >= 0.5).astype('int32') # probability -> classprint(confusion_matrix(y_test, auto_predicted, labels=[0, 1]))print('Spam precision:', round(precision_score(y_test, auto_predicted, zero_division=0), 3))print('Spam recall:', round(recall_score(y_test, auto_predicted, zero_division=0), 3))
Compare the input shapes, validation BCE and test confusion matrices. The two runs illustrate two preprocessing choices; they are not a controlled comparison of network architectures because their vocabularies and tokenization differ.
Part 5 · Exercise: MNIST with Dense layers
MNIST in Keras: structured images and ten output scores
Keras provides MNIST as an already structured dataset: each image is paired with its known digit label. keras.datasets.mnist.load_data() returns two pairs, (images, labels) for 60,000 training images and for 10,000 official test images. An image is a 28×28 array of grayscale pixel values from 0 to 255; its label is one integer from 0 to 9. The arrays are ready to load, but we still scale pixels by 255 and reserve the last 10,000 training images for validation, leaving 50,000 for fitting. We never use the test pair to fit or choose the model. Here is one real training image for each label.

# Keras provides MNIST as arrays of images paired with integer labels.from tensorflow import keras(x_all, y_all), (x_test, y_test) = keras.datasets.mnist.load_data()print('Training images and labels:', x_all.shape, y_all.shape)print('Test images and labels:', x_test.shape, y_test.shape)print('One image:', x_all[0].shape, 'first label:', y_all[0])print('Pixel range:', x_all.min(), 'to', x_all.max())
In this part, the Dense model receives images shaped (batch,28,28); Flatten later makes 784 inputs. In Part 6, Conv2D instead requires a channel axis, giving (batch,28,28,1) for grayscale. At the other end, the classifier must return ten components per image, one for each possible digit 0–9. A final Dense(10) produces a score vector $z=(z_0,z_1,\ldots,z_9)$ with shape (batch,10). These scores are called logits; they can be negative and do not yet sum to one. The predicted digit is the index of the largest score.
Softmax: turn ten scores into ten class probabilities
To read the model's scores as a distribution over the ten digits, apply softmax:
\[p_k=\frac{e^{z_k}}{\sum_{j=0}^{9}e^{z_j}},\qquad k=0,\ldots,9.\]Every $p_k$ is between 0 and 1, and $\sum_{k=0}^{9}p_k=1$. A higher score gives a higher probability, so softmax leaves the winning digit unchanged. It also makes the ten outputs comparable as shares of one total. The diagram uses illustrative scores: digit 3 has score 3 and every other digit has score 0. Their exponentials sum to $e^3+9\approx29.09$; hence $p_3\approx0.691$ and each other $p_k\approx0.0344$.
In code, subtract the largest logit before exponentiating: $e^{z_k-m}/\sum_j e^{z_j-m}$ with $m=\max_jz_j$ gives the same probabilities and avoids very large exponentials. For training, our Dense classifier ends with Dense(10) and uses SparseCategoricalCrossentropy(from_logits=True); Keras performs the stable softmax and log calculation inside the loss. Do not put another softmax on that output during training. For inference, apply keras.activations.softmax to the ten logits. A softmax probability describes this model's output; it is not automatically a calibrated measure of real-world certainty.
Exercise · calculate and use softmax
- For ten scores $z=(0,0,0,3,0,0,0,0,0,0)$, calculate the denominator, the probability of digit 3 and that of any other digit. Check that the ten probabilities add to one.
- Complete the short Python starting code using a numerically stable exponential. Compare your result with
keras.activations.softmax. Which digit doesargmaxpredict? - After training your Dense model below, take one test image, obtain its ten logits, convert them with softmax and compare the predicted digit with its label. Explain why the Dense model's training loss still uses
from_logits=True.
import numpy as npfrom tensorflow import kerasscores = np.array([0, 0, 0, 3, 0, 0, 0, 0, 0, 0], dtype='float32')# Calculate ten probabilities, their sum and the predicted digit.# Compare your calculation with keras.activations.softmax(scores).
Show the correction
# Ten scores for one image: class 3 has the highest score.import numpy as npfrom tensorflow import kerasscores = np.array([0, 0, 0, 3, 0, 0, 0, 0, 0, 0], dtype='float32')shifted_exp = np.exp(scores - scores.max())manual_probabilities = shifted_exp / shifted_exp.sum()keras_probabilities = keras.activations.softmax(scores).numpy()print('Manual softmax:', np.round(manual_probabilities, 4))print('Keras softmax:', np.round(keras_probabilities, 4))print('Sum:', keras_probabilities.sum())print('Predicted digit:', np.argmax(keras_probabilities))
scores.max() is subtracted from every score before np.exp; this changes neither the probabilities nor their order. The two methods give approximately 0.6906 for digit 3 and 0.0344 for each other digit, subject to rounding. For the trained Dense model, replace the illustrative scores with mlp(x_test[:1], training=False)[0], then call softmax and compare np.argmax with y_test[0].
Three partitions with different roles
MNIST comes with 60,000 training images and an official test set of 10,000 images. Keep the test set untouched. Take 10,000 of the training images as a validation set and fit weights on the remaining 50,000. The validation set is used to choose the architecture and the stopping epoch; the test set is evaluated once, after every choice is frozen.
A stratified split keeps the proportion of each digit equal in the two parts. Dividing pixels by the known maximum 255 needs no estimated statistic; a learned normalization (a mean, a standard deviation) must be computed on the training part only, otherwise information from the validation or test images leaks into training.
Exercise · split MNIST without touching the test set
- Load MNIST and reserve 10,000 training images for validation, stratified by digit.
- Scale the three image arrays by 255 and convert them to
float32. - Print the three sizes and check that the digit proportions agree in the two training parts.
The starting code only loads the data; the correction is folded below.
import numpy as npfrom sklearn.model_selection import train_test_splitfrom tensorflow import keras(x_all, y_all), (x_test, y_test) = keras.datasets.mnist.load_data()# TO DO: keep 10,000 of the 60,000 training images for validation, stratified by digit# TO DO: divide pixels by 255 and cast them to float32 (training, validation and test)# TO DO: print the three sizes and compare the digit proportions in training and validation
Show the correction
import numpy as npfrom sklearn.model_selection import train_test_splitfrom tensorflow import keras(x_all, y_all), (x_test, y_test) = keras.datasets.mnist.load_data()x_fit, x_val, y_fit, y_val = train_test_split( x_all, y_all, test_size=10000, stratify=y_all, random_state=21)x_fit, x_val, x_check = [a.astype('float32') / 255.0 for a in (x_fit, x_val, x_test)]print('Fit / validation / test:', len(y_fit), len(y_val), len(x_check))print('Training proportions :', np.round(np.bincount(y_fit) / len(y_fit), 3))print('Validation proportions:', np.round(np.bincount(y_val) / len(y_val), 3))
stratify=y_all preserves the digit proportions, which the two printed lines confirm. The Dense program below keeps the last 10,000 images instead, which is also reasonable because the order of MNIST training images carries no useful structure here; use the stratified split when classes are imbalanced.
Build and assess a Dense classifier
- Load MNIST, separate train/validation/test and display a few digits with their labels.
- Use
Input((28,28)),Flatten(), 64 ReLU units, then 10 affine logits. Predict every tensor shape. - Compile with Adam at 0.001 and sparse categorical cross-entropy from logits. Why does the label remain an integer?
- Train for five epochs, batches of 128. Plot training and validation losses.
- Count parameters, evaluate the fixed model on the test data, and inspect errors.
The short starting code loads the dataset. Complete the data split, normalization, model and training in that order; the next folded frame contains a full solution. Part 6 reuses the data and trained model.
from tensorflow import keras(x_all, y_all), (x_test, y_test) = keras.datasets.mnist.load_data()# Prepare training, validation and test arrays.# Explore sample images and their labels.# Build and compile a Dense classifier.# Train it with validation data, then inspect the learned model.
Show the correction
# Parts 5 and 6: train the Dense and convolutional MNIST models.import numpy as npimport tensorflow as tffrom tensorflow import kerasimport timekeras.utils.set_random_seed(21)(x_all, y_all), (x_test, y_test) = keras.datasets.mnist.load_data()# Reserve the last 10000 official training images for validation.x_train = x_all[:50000].astype('float32') / 255.0x_valid = x_all[50000:].astype('float32') / 255.0x_test = x_test.astype('float32') / 255.0y_train, y_valid = y_all[:50000], y_all[50000:]print('Train / validation / test:', len(x_train), len(x_valid), len(x_test))# Part 5: a Dense MLP. Flatten keeps the batch dimension.mlp = keras.Sequential([ keras.Input(shape=(28,28)), keras.layers.Flatten(), keras.layers.Dense(64, activation='relu'), keras.layers.Dense(10)])mlp.compile(optimizer=keras.optimizers.Adam(0.001), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])start = time.perf_counter()history_mlp = mlp.fit(x_train, y_train, validation_data=(x_valid,y_valid), epochs=5, batch_size=128, verbose=2)time_mlp = time.perf_counter() - start
Flatten changes each (28,28) image into 784 inputs without weights. Dense 64 has $784\times64+64=50,240$ parameters; Dense 10 adds $64\times10+10=650$, giving 50,890. The output is (batch,10). Sparse categorical cross-entropy selects the log-probability of the true integer label; it applies the stable log-softmax internally. Do not add softmax before a loss configured for logits.
fit loops over mini-batches, computes gradients and updates weights. Validation performs forward evaluation without learning. history_mlp.history stores one metric per epoch. Timing surrounds training only and includes overhead; it is not a hardware-independent score.
Graph the Dense training history
# Run after the Dense model in Part 5: history_mlp is already available.import matplotlib.pyplot as pltepochs = range(1, len(history_mlp.history['loss']) + 1)plt.plot(epochs, history_mlp.history['loss'], label='Training loss')plt.plot(epochs, history_mlp.history['val_loss'], '--', label='Validation loss')plt.xlabel('Epoch')plt.ylabel('Cross-entropy')plt.legend()plt.show()
The solid curve shows training loss and the dashed curve validation loss. They are measured on different data. Read whether both decrease and whether a gap opens before selecting a training duration. The code reuses history_mlp from the Keras block above.
Choose the number of epochs: early stopping
Training loss usually keeps decreasing, but the validation loss may stop improving and then increase: the model starts fitting details of the training images. EarlyStopping watches a validation metric. With patience=3 it stops after three epochs without improvement, and restore_best_weights=True returns the weights of the best epoch instead of the last ones.
The selection uses validation data only. The test set stays out of this decision, and the number of epochs you report is the one chosen here.
Exercise · stop when validation stops improving
- Rebuild the Dense classifier of this part and compile it with the same loss and optimizer.
- Add an
EarlyStoppingcallback onval_lossand allow up to 30 epochs. - Report the best epoch and the validation loss of the restored weights, then plot both loss curves.
# Run after the Dense data preparation (x_train, y_train, x_valid, y_valid).import numpy as npimport matplotlib.pyplot as pltfrom tensorflow import keras# TO DO: build the same Dense model (Input (28,28), Flatten, 64 ReLU units, 10 logits) and compile it# TO DO: create keras.callbacks.EarlyStopping on 'val_loss', patience 3, restore_best_weights=True# TO DO: fit for up to 30 epochs (batches of 128) with the validation data and the callback# TO DO: print the epoch with the lowest validation loss and plot the two loss curves
Show the correction
# Run after the Dense data preparation (x_train, y_train, x_valid, y_valid).import numpy as npimport matplotlib.pyplot as pltfrom tensorflow import keraskeras.utils.set_random_seed(21)model = keras.Sequential([ keras.Input(shape=(28, 28)), keras.layers.Flatten(), keras.layers.Dense(64, activation='relu'), keras.layers.Dense(10)])model.compile(optimizer=keras.optimizers.Adam(0.001), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])stop = keras.callbacks.EarlyStopping(monitor='val_loss', patience=3, restore_best_weights=True)history = model.fit(x_train, y_train, validation_data=(x_valid, y_valid), epochs=30, batch_size=128, callbacks=[stop], verbose=0)val_loss = history.history['val_loss']best_epoch = int(np.argmin(val_loss)) + 1print('Epochs run:', len(val_loss), '| best epoch:', best_epoch, '| best validation loss:', round(min(val_loss), 4))print('Validation loss of the restored weights:', round(model.evaluate(x_valid, y_valid, verbose=0)[0], 4))plt.plot(range(1, len(val_loss) + 1), history.history['loss'], label='Training loss')plt.plot(range(1, len(val_loss) + 1), val_loss, '--', label='Validation loss')plt.axvline(best_epoch, color='gray', linewidth=1)plt.xlabel('Epoch'); plt.ylabel('Cross-entropy'); plt.legend(); plt.show()
The restored model is the one at the vertical line, not the one of the last epoch. If every epoch still improves, increase the epoch budget: stopping rules cannot fix a budget that is too small.
Project the learned digit representation with PCA
After training the Dense model, take the 64 ReLU activations just before its ten output scores. Each image now has a learned vector $h_i\in\mathbb{R}^{64}$: training for digit classification has changed this representation. To draw it in a plane, use principal component analysis (PCA), a classical linear, unsupervised projection. PCA does not retrain the network and does not use digit labels to choose its axes.
Form a matrix $H$ with one feature vector per training image. Subtract the column mean $\mu$ to obtain $H_c=H-\mu$. Its covariance is $C=H_c^TH_c/(N-1)$. The two eigenvectors $v_1,v_2$ with the largest eigenvalues give the two directions of greatest variance. Project each image to $q_i=((h_i-\mu)\cdot v_1,(h_i-\mu)\cdot v_2)$. Scikit-learn computes these directions with a numerically stable singular-value decomposition. Its explained_variance_ratio_ says what fraction of the training-feature variance each axis retains.
The program fits PCA on 1,000 training images per digit, using their 64 learned features. It plots 400 per digit so the dots stay legible. Color uses each image's known training label; the large numbered dots are the mean projected position of each labelled group. The labels and means are added for interpretation after PCA, not used to train it. Then the program applies the same fitted PCA transform to six test images, after model inference. Their star colors indicate predicted digits, and each annotation reads true label → prediction.
Read the projected groups and their limits

Open the projection at full resolution. In the reference run, the first two axes retain about 35.3% of feature variance. The example labelled 5 but predicted 6 is marked 5→6. These six selected examples illustrate the map; they are not an accuracy estimate.
Limits: a 2D view discards most of the 64-dimensional information. Overlap in this plane does not prove that the trained ten-score classifier confuses two digits; it can separate them using directions absent from the plot. Conversely, visible distance does not guarantee correct predictions. PCA maximizes overall variance, not class separation, and it gives no decision boundaries. The colored groups come from a supervised representation and known labels; the model did not run a clustering algorithm. The balanced sample affects the displayed density and the fitted axes. Axis signs may flip between runs without changing the geometry. Fit PCA on training features only, then transform new images with the same mean and axes.
Program · PCA projection and inference points
Run this block after the complete Dense training correction in the same Python session. It reuses mlp, x_train, y_train, x_test and y_test. It saves mnist-pca.png in the working directory. The ten colored groups show training labels; the six stars are test inputs processed by the trained network and projected without refitting PCA.
# Run after the complete Dense training code in Part 5.# Reuses mlp, x_train, y_train, x_test and y_test.import numpy as npimport matplotlib.pyplot as pltfrom sklearn.decomposition import PCAfrom tensorflow import keras# The first Dense layer (after Flatten) contains 64 learned ReLU features.features = keras.Model(inputs=mlp.inputs, outputs=mlp.layers[1].output)# Fit PCA on a balanced training subset only: 1000 images of each digit.fit_ids = np.concatenate([ np.flatnonzero(y_train == digit)[:1000] for digit in range(10)])hidden_train = features.predict(x_train[fit_ids], batch_size=512, verbose=0)pca = PCA(n_components=2, svd_solver='full')train_xy = pca.fit_transform(hidden_train)fit_labels = y_train[fit_ids]centers = np.array([train_xy[fit_labels == digit].mean(axis=0) for digit in range(10)])print('Variance retained by two axes:', np.round(pca.explained_variance_ratio_, 4), 'total:', round(pca.explained_variance_ratio_.sum(), 4))# Inference examples: first test image of six known digits. The test# images do not participate in PCA fitting or centroid calculation.shown_digits = [0, 1, 2, 3, 5, 8]test_ids = np.array([np.flatnonzero(y_test == digit)[0] for digit in shown_digits])hidden_test = features.predict(x_test[test_ids], verbose=0)test_xy = pca.transform(hidden_test)logits = mlp(x_test[test_ids], training=False).numpy()probabilities = keras.activations.softmax(logits).numpy()predicted = probabilities.argmax(axis=1)for row, index in enumerate(test_ids): print('Test index', index, 'true:', y_test[index], 'predicted:', predicted[row], 'PCA:', np.round(test_xy[row], 2))# Draw a light sample of the learned training representation, its class# centroids, and the fixed test examples in the very same PCA plane.palette = plt.get_cmap('tab10')fig, axes = plt.subplots(1, 2, figsize=(13, 5.8), sharex=True, sharey=True)center_offsets = [(8, 2), (8, 9), (8, 9), (8, 8), (17, -14), (11, 10), (-16, 9), (-25, -15), (11, -10), (-25, 10)]for digit in range(10): locations = np.flatnonzero(fit_labels == digit)[:400] for ax in axes: ax.scatter(train_xy[locations, 0], train_xy[locations, 1], s=6, alpha=0.16 if ax is axes[0] else 0.07, color=palette(digit), rasterized=True) axes[0].scatter(centers[digit, 0], centers[digit, 1], s=120, color=palette(digit), edgecolor='black', linewidth=1.1) axes[0].annotate(str(digit), centers[digit], xytext=center_offsets[digit], textcoords='offset points', fontsize=11, fontweight='bold')test_offsets = [(8, 8), (8, 8), (8, 8), (-48, 15), (9, 10), (12, 15)]for row, digit in enumerate(shown_digits): axes[1].scatter(test_xy[row, 0], test_xy[row, 1], marker='*', s=210, color=palette(int(predicted[row])), edgecolor='black', linewidth=0.9, zorder=4) axes[1].annotate(f'{digit}→{predicted[row]}', test_xy[row], xytext=test_offsets[row], textcoords='offset points', fontsize=10, fontweight='bold', zorder=5)axes[0].set_title('Training features: color = true digit; large dot = class mean')axes[1].set_title('Test inference: star = predicted digit; label = true→predicted')for ax in axes: ax.set_xlabel('Principal component 1') ax.set_ylabel('Principal component 2') ax.grid(alpha=0.2)fig.suptitle('MNIST Dense model: PCA of 64 learned hidden activations', fontsize=15)fig.tight_layout()fig.savefig('mnist-pca.png', dpi=170)plt.show()
To project an additional image later, apply the same pixel scaling, obtain its 64 hidden activations with features, then call pca.transform. Never call fit on that new image; doing so changes the coordinate system and makes positions incomparable.
Part 6 · Convolution, MNIST CNN and comparison
Convolution: slide one filter over an image
A Dense layer treats pixels as separate coordinates. A convolutional layer applies the same small filter at every position. The orange 3×3 window below shows which input values are multiplied by the filter. Use Next or Play to move it across the 4×4 image; each position fills one output cell.
Here every image row is [0,0,1,0] and every filter row is [−1,2,−1]. At the first position the three products in each row sum to −1, so the three rows give −3. Sliding one column right gives 6. With stride 1 and valid padding, a 4×4 image and 3×3 filter produce a 2×2 score map. ReLU clips negative scores to zero. The filter is fixed only for this demonstration; a CNN learns filter coefficients by gradient descent.
Keras Conv2D performs cross-correlation, with no kernel flip. padding="same" and stride 1 preserve spatial width and height. One filter produces one output channel. The filter's nine coefficients are shared across all four positions; a learned bias would add one value per filter.
# One 4x4 image, one fixed 3x3 filter, valid padding and stride 1.import numpy as npimport tensorflow as tffrom tensorflow import kerasimage = np.array([[0, 0, 1, 0]] * 4, dtype='float32')[None, :, :, None]kernel = np.array([[-1, 2, -1]] * 3, dtype='float32')[:, :, None, None]layer = keras.layers.Conv2D(1, 3, padding='valid', use_bias=False)layer(image) # Build the layer before assigning its illustrative weights.layer.set_weights([kernel])scores = layer(image).numpy()[0, :, :, 0]print('Convolution scores:\n', scores)print('After ReLU:\n', tf.nn.relu(scores).numpy())
The code first builds the layer, then assigns the illustrative 3×3 weights. It prints the score map [[-3, 6], [-3, 6]] and its ReLU result [[0, 6], [0, 6]]. In a trained model, fit learns the weights instead of set_weights.
Max pooling: retain the strongest local response
Max pooling takes the largest value in each small window, independently for each channel. It has no trainable weights. For the 4×4 activation map below, a 2×2 window with stride 2 visits four non-overlapping regions and produces a 2×2 output. Move the orange window to see each maximum.
For example, the top-left window contains 1, 3, 4 and 2, so its output is 4. The four outputs are [[4, 5], [6, 8]]. Pooling reduces spatial size and computation for later layers while keeping strong local activations. A small displacement can leave a window's maximum unchanged, but pooling does not guarantee invariance to every translation; changing window boundaries can change the result.
# Take the maximum in each non-overlapping 2x2 window.import numpy as npfrom tensorflow import kerasimage = np.array([[1, 3, 0, 2], [4, 2, 5, 1], [0, 1, 2, 8], [3, 6, 4, 1]], dtype='float32')[None, :, :, None]pool = keras.layers.MaxPooling2D(pool_size=2, strides=2)result = pool(image).numpy()[0, :, :, 0]print('Pooled image:\n', result)
MaxPooling2D(pool_size=2, strides=2) has no weights to fit. The leading dimensions of the input are batch and channel: (1,4,4,1) becomes (1,2,2,1).
Predict the shape and parameters of a convolutional layer
With channels-last tensors, a Conv2D layer takes $(B,H,W,C_{in})$ and has $C_{out}$ filters of size $k\times k$. With symmetric padding $p$, stride $s$ and dilation 1, the output size along one axis is
\[H_{out}=\left\lfloor\frac{H+2p-k}{s}\right\rfloor+1,\qquad \text{parameters}=(k^2C_{in}+1)\,C_{out}.\]Keras padding="valid" means $p=0$; padding="same" with stride 1 keeps $H_{out}=H$. A $2\times2$ max-pooling with stride 2 halves an even size and has no trainable parameters. Both formulas explain the counts 80 and 1,168 of the CNN below.
Exercise · count before you train
- Write two small functions for the output size and for the number of parameters.
- Apply them to
Conv2D(8, 3)on a $28\times28\times1$ image with valid, then same padding. - Compute the parameters of a second layer with 16 filters on the 8 channels of the first, and verify everything with Keras layers.
import numpy as npfrom tensorflow import kerasdef conv_output_size(n, k, padding=0, stride=1): return ... # TO DO: floor((n + 2*padding - k) / stride) + 1def conv_parameters(k, c_in, c_out): return ... # TO DO: weights k*k*c_in*c_out plus one bias per filter# TO DO: spatial size and parameters of Conv2D(8, 3) on a 28x28x1 image, with 'valid' then 'same' padding# TO DO: check your numbers by calling the Keras layer on np.zeros((1, 28, 28, 1))
Show the correction
import numpy as npfrom tensorflow import kerasdef conv_output_size(n, k, padding=0, stride=1): return (n + 2 * padding - k) // stride + 1def conv_parameters(k, c_in, c_out): return (k * k * c_in + 1) * c_outprint('valid:', conv_output_size(28, 3, padding=0), '| same:', conv_output_size(28, 3, padding=1))print('parameters, 8 filters on 1 channel:', conv_parameters(3, 1, 8))print('second layer, 16 filters on 8 channels:', conv_parameters(3, 8, 16))dummy = np.zeros((1, 28, 28, 1), dtype='float32')for padding in ('valid', 'same'): layer = keras.layers.Conv2D(8, 3, padding=padding) print(padding, 'Keras output shape:', layer(dummy).shape, '| parameters:', layer.count_params())print('valid size matches the formula:', keras.layers.Conv2D(8, 3, padding='valid')(dummy).shape[1] == conv_output_size(28, 3, 0))print('same size matches the formula:', keras.layers.Conv2D(8, 3, padding='same')(dummy).shape[1] == conv_output_size(28, 3, 1))print('second layer has 1,168 parameters:', conv_parameters(3, 8, 16) == 1168)
The depth of the filter is the number of input channels: the second layer has $3\times3\times8$ weights per filter, hence $(72+1)\times16=1{,}168$ parameters, whereas the first has only $(9+1)\times8=80$.
Exercise: apply convolution and max pooling to MNIST
- Reuse the MNIST split and scaling from Part 5. Add one grayscale channel to each image. Predict the new input shape.
- Build a CNN that alternates a 3×3 convolution and 2×2 max pooling twice, then uses a small Dense classifier. Choose 8 and 16 filters, followed by 32 hidden Dense units and ten class scores.
- Before running it, calculate the spatial sizes and the number of trainable parameters. Which layers have no trainable parameters?
- Train with the same optimizer, batch size and five-epoch budget as the Part 5 MLP. Compare test loss, accuracy, parameter count and training time; inspect a confusion matrix and a few errors.
The starting code keeps only the data connection and the work to complete. Try the architecture yourself before opening the correction.
# Continue after the Dense model in Part 5.x_train_cnn = x_train[..., None]x_valid_cnn = x_valid[..., None]x_test_cnn = x_test[..., None]# Build a CNN with Conv2D and MaxPooling2D layers.# Compile and fit it on x_train_cnn, using x_valid_cnn for validation.# Evaluate once on x_test_cnn and compare with the Dense model.
Show the correction
# Run after the Dense training in mnist.py.import timefrom tensorflow import keras# Part 6: keep the image grid and add the channel axis (one grayscale channel).cnn = keras.Sequential([ keras.Input(shape=(28,28,1)), keras.layers.Conv2D(8, 3, padding='same', activation='relu'), keras.layers.MaxPooling2D(2), keras.layers.Conv2D(16, 3, padding='same', activation='relu'), keras.layers.MaxPooling2D(2), keras.layers.Flatten(), keras.layers.Dense(32, activation='relu'), keras.layers.Dense(10)])cnn.compile(optimizer=keras.optimizers.Adam(0.001), loss=keras.losses.SparseCategoricalCrossentropy(from_logits=True), metrics=['accuracy'])start = time.perf_counter()history_cnn = cnn.fit(x_train[...,None], y_train, validation_data=(x_valid[...,None],y_valid), epochs=5, batch_size=128, verbose=2)time_cnn = time.perf_counter() - start
Shapes are 28×28×8 → 14×14×8 → 14×14×16 → 7×7×16 → 784 → 32 → 10. Parameter counts are 80, 0, 1,168, 0, 0, 25,120, 330: 26,698 total. For a convolution use $(k^2C_{in}+1)C_{out}$; for Dense use $(n_{in}+1)n_{out}$. The added None inserts a channel axis, not additional pixel information.
# Run after both Keras models are trained in Parts 5 and 6.loss_mlp, accuracy_mlp = mlp.evaluate(x_test, y_test, verbose=0)loss_cnn, accuracy_cnn = cnn.evaluate(x_test[..., None], y_test, verbose=0)print('Model | parameters | seconds | test loss | test accuracy')print('MLP', mlp.count_params(), time_mlp, loss_mlp, accuracy_mlp)print('CNN', cnn.count_params(), time_cnn, loss_cnn, accuracy_cnn)
The two architectures and epoch budget are fixed before evaluating on test data. Read the measured loss, accuracy, parameter count and training time before plotting.
Graphical correction · compare curves and inspect mistakes
# Run after mnist.py: both trained models and their histories are available.import numpy as npimport matplotlib.pyplot as pltimport tensorflow as tffig, axes = plt.subplots(1,2,figsize=(10,4))for history, name in [(history_mlp,'MLP'),(history_cnn,'CNN')]: axes[0].plot(range(1,6),history.history['loss'],label=name+' train') axes[0].plot(range(1,6),history.history['val_loss'],'--',label=name+' validation') axes[1].plot(range(1,6),history.history['val_accuracy'],label=name)axes[0].set(xlabel='Epoch',ylabel='Cross-entropy')axes[1].set(xlabel='Epoch',ylabel='Validation accuracy')axes[0].legend()axes[1].legend()plt.tight_layout()plt.show()scores = cnn.predict(x_test[...,None],batch_size=256,verbose=0)predicted = scores.argmax(axis=1)confusion = tf.math.confusion_matrix(y_test,predicted,num_classes=10).numpy()plt.imshow(confusion,cmap='Blues')plt.xlabel('Predicted digit')plt.ylabel('True digit')plt.xticks(range(10))plt.yticks(range(10))plt.colorbar()plt.show()wrong = np.flatnonzero(predicted != y_test)[:9]fig, axes = plt.subplots(3,3,figsize=(7,7))for ax, i in zip(axes.ravel(),wrong): ax.imshow(x_test[i],cmap='gray') ax.set_title('True '+str(y_test[i])+' / predicted '+str(predicted[i])) ax.axis('off')plt.tight_layout()plt.show()
These plots reuse the two trained models, their histories, the fixed test set and the predictions. The curves compare training and validation losses. The confusion matrix uses true labels in rows and predicted labels in columns; the image grid displays nine CNN errors. Five epochs means the same number of passes through the observations, while training times can differ. Compare measured results and avoid using the test set for tuning.
Accuracy, macro F1 and confident mistakes
Accuracy is the fraction of correct labels. The F1 score of one digit combines its precision and recall; the macro F1 averages the ten per-digit scores with equal weights, so a rare or difficult class counts as much as an easy one. Compare them with the confusion matrix (true classes in rows, predictions in columns).
A softmax probability is not a guarantee: a model can be wrong with probability close to 1. Look at the mistakes together with their maximum probability. Report the architecture, the number of epochs, the seed and which images were used with every score.
Exercise · read the final report of the CNN
- After training the CNN, compute its probabilities and predictions on the test images.
- Report accuracy and macro F1, then the F1 score of each digit: which digit is the hardest?
- Find the mistake with the highest maximum probability and display the image.
# Run after training the CNN of this part (cnn, x_test, y_test).import numpy as npimport tensorflow as tffrom sklearn.metrics import accuracy_score, f1_scoreprobabilities = ... # TO DO: softmax of the CNN logits on x_test[..., None]predicted = ... # TO DO: most probable digit# TO DO: accuracy and macro F1 (average='macro')# TO DO: one F1 score per digit with average=None; which digit is the hardest?# TO DO: among the errors, find the one with the largest maximum probability and show it
Show the correction
# Run after training the CNN of this part (cnn, x_test, y_test).import numpy as npimport tensorflow as tfimport matplotlib.pyplot as pltfrom sklearn.metrics import accuracy_score, f1_scoreprobabilities = tf.nn.softmax(cnn(x_test[..., None], training=False), axis=1).numpy()predicted = probabilities.argmax(axis=1)print('Accuracy:', round(accuracy_score(y_test, predicted), 4))print('Macro F1:', round(f1_score(y_test, predicted, average='macro'), 4))per_digit = f1_score(y_test, predicted, average=None)print('F1 per digit:', np.round(per_digit, 3), '| hardest digit:', int(per_digit.argmin()))errors = np.flatnonzero(predicted != y_test)worst = errors[probabilities[errors].max(axis=1).argmax()]print('Most confident mistake: true', y_test[worst], 'predicted', predicted[worst], 'with probability', round(float(probabilities[worst].max()), 3))plt.imshow(x_test[worst], cmap='gray'); plt.axis('off'); plt.show()
Evaluate on the test set only once, with the architecture and epoch budget fixed beforehand. If one digit is much weaker, inspect its errors before changing anything, and use the validation set for every new attempt.
Reference run and further reading
Measured reference run (CPU, TensorFlow 2.21, seed 21, five epochs): MLP — 50,890 parameters, test accuracy 96.26%, test cross-entropy 0.12373, training 1.92 s; CNN — 26,698 parameters, test accuracy 98.18%, test cross-entropy 0.05720, training 5.28 s. These are one run on this machine, not guaranteed scores or portable timings.
This course adapts the constructions, neuron diagrams, BCE derivations and convolution example from the local IRIS didactic MLP/CNN and autonomous Keras teaching sheets. The programs here use TensorFlow as the Keras backend and keep the student workflow sequential.