Unit 9, lesson 66

A Complete Neural Classification Example

How a small neural network classifier is trained and selected against a logistic regression baseline, with its architecture, data roles, decision threshold and random seeds recorded.

  • Video 66
  • Training and Evaluating Networks

Two constructed sensor readings, already on the same scale, are labeled positive when they have the same sign. Can a small neural network learn this rule, and is it worth its extra parameters compared with a simpler model? An honest answer needs more than a network that trains. This lesson fixes the data roles before any comparison, trains a logistic regression baseline and two networks under the same rules, selects one on validation data, opens the test set once, and records the architecture, threshold and random seeds that the result depends on.

Key terms

Neural network classifier

Definition A neural network classifier passes the features through one or more hidden layers to an output unit that scores the classes. For a binary label y∈{0,1}y \in \{0, 1\} and a feature vector x∈Rp\mathbf{x} \in \mathbb{R}^p, the classifier of this lesson has one tanh hidden layer of width hh and computes

a=tanh⁡(W⊤x+b),z=v⊤a+c,\begin{gathered} \mathbf{a} = \tanh(W^{\top}\mathbf{x} + \mathbf{b}), \\[0.4em] z = \mathbf{v}^{\top}\mathbf{a} + c, \end{gathered}

where tanh acts entry by entry, WW is a p×hp \times h matrix, b\mathbf{b} and v\mathbf{v} have hh entries and cc is a number. The logit zz gives the score σ(z)=1/(1+e−z)\sigma(z) = 1/(1 + e^{-z}), and with a decision threshold τ\tau the classifier predicts 11 when σ(z)≥τ\sigma(z) \ge \tau. At τ=0.5\tau = 0.5 this is the rule z≥0z \ge 0. The parameters are fitted by minimizing the mean binary cross-entropy over the training examples. That loss is not convex in the parameters, so the solution reached can depend on the initialization and on the order of the mini-batches. The score σ(z)\sigma(z) estimates P(Y=1∣x)P(Y = 1 \mid \mathbf{x}) only as far as it is calibrated, which training by cross-entropy does not guarantee and which has to be checked on held-out data, as in Probability Calibration.

In plain words The hidden layer builds hh new features from the inputs, and the output unit is a logistic regression on those learned features. Because the features are learned, the boundary between the two predicted classes can bend, and the region predicted positive can even fall into separate pieces, which a single straight line cannot produce.

Example The same-sign rule says y=1y = 1 exactly when x1x2≥0x_1 x_2 \ge 0. Four ReLU hidden units represent it exactly. With ReLU⁡(u)=max⁡(u,0)\operatorname{ReLU}(u) = \max(u, 0), take the logit

z=ReLU⁡(x1+x2)+ReLU⁡(−x1−x2)−ReLU⁡(x1−x2)−ReLU⁡(x2−x1).\begin{aligned} z &= \operatorname{ReLU}(x_1 + x_2) \\[0.4em] &\quad + \operatorname{ReLU}(-x_1 - x_2) \\[0.4em] &\quad - \operatorname{ReLU}(x_1 - x_2) \\[0.4em] &\quad - \operatorname{ReLU}(x_2 - x_1) . \end{aligned}

Since ReLU⁡(u)+ReLU⁡(−u)=∣u∣\operatorname{ReLU}(u) + \operatorname{ReLU}(-u) = \lvert u \rvert, the logit equals ∣x1+x2∣−∣x1−x2∣\lvert x_1 + x_2 \rvert - \lvert x_1 - x_2 \rvert. It is nonnegative exactly when (x1+x2)2≥(x1−x2)2(x_1 + x_2)^2 \ge (x_1 - x_2)^2, that is, when 4x1x2≥04x_1 x_2 \ge 0. At the point (0.5,0.2)(0.5, 0.2) the logit is 0.7−0.3=0.40.7 - 0.3 = 0.4, a positive prediction, and at (0.5,−0.2)(0.5, -0.2) it is 0.3−0.7=−0.40.3 - 0.7 = -0.4. The tanh networks trained in this lesson have to find a representation from data, and the ones found only approximate the rule.

Network architecture

Definition The architecture fixes the family of functions before training, namely the number of layers, their widths, the activation functions, the output unit and the loss. For pp input features, one tanh hidden layer of width hh and one logit, the trainable arrays are WW with shape p×hp \times h, the vectors b\mathbf{b} and v\mathbf{v} with hh entries and the number cc, so the network has (p+2)h+1(p + 2)h + 1 parameters. A batch of mm examples is an m×pm \times p array XX, and the forward pass

H=tanh⁡(XW+1b⊤),z=Hv+c1\begin{gathered} H = \tanh(XW + \mathbf{1}\mathbf{b}^{\top}), \\[0.4em] \mathbf{z} = H\mathbf{v} + c\mathbf{1} \end{gathered}

produces an m×hm \times h hidden array and mm logits, where 1\mathbf{1} is the all-ones vector of length mm. Width, depth and activation are hyperparameters, chosen with validation data like any other setting and never by test results.

In plain words The architecture is the blueprint of the model. Writing out the shape of every array and the parameter count catches many implementation mistakes before training starts, and the count shows how many more parameters the network fits than the baseline does.

Example With p=2p = 2 the count is 4h+14h + 1, so the widths 44 and 1212 used below give 1717 and 4949 parameters, against 33 for logistic regression on the same two features. For a batch of 1616 examples and width 1212, the arrays XX, WW, HH and z\mathbf{z} have shapes 16×216 \times 2, 2×122 \times 12, 16×1216 \times 12 and 1616. In NumPy the forward pass, the loss and the gradients by backpropagation take a few lines. The loss uses the form ln⁡(1+ez)−yz\ln(1 + e^{z}) - yz through np.logaddexp, which never takes the logarithm of a probability that has rounded to 00 or 11.

import numpy as np

def forward(X, W, b, v, c):
    H = np.tanh(X @ W + b)                  # hidden array, shape (m, h)
    return H, H @ v + c                     # logits, shape (m,)

def mean_bce(y, z):
    return np.mean(np.logaddexp(0.0, z) - y * z)

def gradients(X, y, W, b, v, c):
    H, z = forward(X, W, b, v, c)
    prob = np.exp(-np.logaddexp(0.0, -z))   # sigmoid(z), computed stably
    dz = (prob - y) / len(y)                # derivative of the mean loss in z
    dA = np.outer(dz, v) * (1.0 - H**2)     # back through tanh
    return X.T @ dA, dA.sum(axis=0), H.T @ dz, dz.sum()

Logistic regression baseline

Definition A baseline is a simpler model trained and evaluated with the same data roles, the same information, the same loss and the same selection rule as the model it is compared with, so that a difference in results reflects the models and not the procedure. The logistic regression baseline estimates P(Y=1∣x)P(Y = 1 \mid \mathbf{x}) by σ(w⊤x+b)\sigma(\mathbf{w}^{\top}\mathbf{x} + b). At threshold 0.50.5 it predicts 11 on the half-plane where w⊤x+b≥0\mathbf{w}^{\top}\mathbf{x} + b \ge 0 when w≠0\mathbf{w} \ne \mathbf{0}, and the same class everywhere when w=0\mathbf{w} = \mathbf{0}. Its mean cross-entropy is convex in (w,b)(\mathbf{w}, b). No rule of this form reproduces the same-sign labels. An affine function that is nonnegative at the positive points (1,1)(1, 1) and (−1,−1)(-1, -1) is nonnegative at their midpoint (0,0)(0, 0), and one that is negative at the negative points (1,−1)(1, -1) and (−1,1)(-1, 1) is negative at the same midpoint, so no affine function has the required signs at all four points. A majority-class rule, which predicts the more common training class for every case, is a further reference, especially when the classes are unbalanced.

In plain words A baseline answers how much of the result needs the network at all. Here geometry predicts the answer, since the positive class fills two opposite quadrants and a line can only cut the plane into two sides. The comparison is still run, because a prediction about a model is not a measurement of it.

Example On the constructed data of this lesson, the baseline’s best validation checkpoint comes at epoch 22, with validation loss 0.69120.6912, barely below the value ln⁡2≈0.6931\ln 2 \approx 0.6931 of a constant score 0.50.5. All its logits are negative, so it predicts the negative class for every training, validation and test case. Since 5050 of the 120120 training cases are positive, it makes the same decisions as the majority-class rule. On the 8080 test cases it is right for the 4646 negatives, an accuracy of 0.5750.575, its recall is 00, and its precision is undefined because it makes no positive predictions. A designed feature would change the picture. With the inputs x1x_1, x2x_2 and x1x2x_1 x_2, the logit w3x1x2w_3 x_1 x_2 with any w3>0w_3 > 0 is nonnegative exactly when x1x2≥0x_1 x_2 \ge 0, so a logistic regression with 44 parameters can represent the rule exactly. In real data such a feature is rarely known in advance, and trying it adds a new candidate that has to go through the same validation step.

Data roles

Definition Data roles assign every example to one job, declared before any model is compared. The training set fits the parameters and any preprocessing statistics. The validation set chooses checkpoints, architectures and the threshold and compares the candidates with the baseline. The test set evaluates the single frozen procedure once. The roles assume examples drawn independently from the population of interest, and grouped or time-ordered data need splits that keep related examples together or respect the order in time. A test result describes the frozen procedure on cases like the test cases, under the relationship between features and target that produced them.

In plain words Each data set answers one question. Training data teach, validation data choose and test data report. A set used for two jobs gives an optimistic answer to the second one.

Example The three sets are drawn with separate fixed seeds from the uniform distribution on [−1,1]2[-1, 1]^2, with 120120 training, 6060 validation and 8080 test cases and the label 11 exactly when x1x2≥0x_1 x_2 \ge 0. Both features already share one dimensionless range, so no scaling is fitted. Had scaling been needed, its means and standard deviations would come from the training set and be applied unchanged to the other two. Every candidate is trained on mean cross-entropy with learning rate 0.10.1, shuffled mini-batches of at most 1616 cases and a budget of 500500 epochs, and keeps its own best validation checkpoint. The record kept with the code lists the seeds, the data rule, the absence of fitted preprocessing, the candidates, the selection metric and the threshold.

CandidateParametersBest epochValidation lossValidation accuracy
Logistic regression33220.69120.691232/6032/60
Network, width 4417173743740.25400.254053/6053/60
Network, width 121249493043040.22740.227453/6053/60

The width-12 network has the lowest validation loss and is selected. The two networks tie on accuracy, and the loss separates them because it also measures how confident each correct and incorrect score is. With the parameters frozen and the threshold kept at 0.50.5, the test set is opened once. The selected network has TP=31\text{TP} = 31, FP=0\text{FP} = 0, FN=3\text{FN} = 3 and TN=46\text{TN} = 46, so its accuracy is 77/80=0.962577/80 = 0.9625, its recall is 31/34≈0.91231/34 \approx 0.912, its precision is 31/31=131/31 = 1 and its test cross-entropy is about 0.11160.1116. Having no false positives among 4646 negatives does not show that the false positive rate is zero. If the test negatives are independent draws, an exact one-sided 9595 percent upper confidence bound for that rate is 1−0.051/46≈0.0631 - 0.05^{1/46} \approx 0.063. The three missed positives lie at about (0.096,0.710)(0.096, 0.710), (0.650,0.024)(0.650, 0.024) and (0.154,0.935)(0.154, 0.935), each within 0.160.16 of an axis, with scores near 0.420.42, and all seven validation errors lie within 0.080.08 of an axis. The errors sit close to the true boundary, where a slightly misplaced learned boundary produces mistakes. Inspecting them explains the result without changing the model. The claim also depends on the labeling rule. If the same test points were labeled by the reversed rule, positive for opposite signs, the frozen network’s accuracy would fall to 3/80=0.03753/80 = 0.0375.

Random seed

Definition A random seed is the starting state of a pseudorandom number generator. Fixing it makes every number the generator draws repeatable, such as the data sample, the initial weights, the order of the mini-batches and the dropout masks, given the same code, library versions and hardware. A run is reproducible when its seeds, data, preprocessing, architecture, threshold and settings are recorded so that it can be repeated. Bit-identical results on other machines or library versions are not guaranteed, because floating-point results can depend on the order of operations. A seed does not make a conclusion stable. Another seed is another draw of the training randomness, and with a nonconvex loss it can lead to a different solution. Choosing the seed with the best validation loss is a selection like any other, and the winning value is optimistic.

In plain words A seed makes a run repeatable, not representative. To learn how much a result owes to chance, train with several seeds and report the spread.

Example The training, validation and test data of this lesson come from the seeds 661661, 662662 and 663663, and seed 77 sets the initial weights and the mini-batch order. The network weights start as normal draws with mean 00 and standard deviation 1/fan-in1/\sqrt{\text{fan-in}}, which is 1/21/\sqrt{2} for WW and 1/h1/\sqrt{h} for v\mathbf{v}, the biases start at 00, and the baseline starts from all zeros. In an additional check on the same data, the training seeds 11 to 1010, which include seed 77, give best validation losses from 0.22260.2226 to 0.36820.3682 for the width-4 network, with mean about 0.25950.2595, and from 0.21570.2157 to 0.25010.2501 for the width-12 network, with mean about 0.23600.2360. With seed 11 the width-4 network scores 0.22260.2226 and the width-12 network 0.25010.2501, the reverse of the seed-7 ranking in the table above. The average over the ten seeds favors width 1212 on this construction, but the ranges overlap, so a choice between the widths should rest on several seeds and not on one.

Check yourself

  1. A network has 33 input features, one tanh hidden layer of width 88 and one logit. How many trainable parameters does it have, and what are the shapes of the hidden array and of the logits for a batch of 3232 examples?
Show the answer

The weight matrix WW has shape 3×83 \times 8, which gives 2424 parameters, the hidden bias and the output weights have 88 entries each, and the output bias is one number. The total is 24+8+8+1=4124 + 8 + 8 + 1 = 41, which agrees with (p+2)h+1=5⋅8+1(p + 2)h + 1 = 5 \cdot 8 + 1. For a batch of 3232 examples the hidden array has shape 32×832 \times 8, and there are 3232 logits, one for each example.

  1. A selected model is evaluated once on 4040 test cases with TP=13\text{TP} = 13, FP=4\text{FP} = 4, FN=2\text{FN} = 2 and TN=21\text{TN} = 21. A baseline that predicts the negative class for every case is evaluated on the same cases. Compute the accuracy, precision and recall of both, and name one claim that these numbers cannot support.
Show the answer

The test set has 13+2=1513 + 2 = 15 actual positives and 4+21=254 + 21 = 25 actual negatives. The model’s accuracy is (13+21)/40=34/40=0.85(13 + 21)/40 = 34/40 = 0.85, its precision is 13/(13+4)=13/17≈0.76513/(13 + 4) = 13/17 \approx 0.765 and its recall is 13/(13+2)=13/15≈0.86713/(13 + 2) = 13/15 \approx 0.867.

The baseline is right for the 2525 negatives, so its accuracy is 25/40=0.62525/40 = 0.625, and it finds none of the 1515 positives, so its recall is 0/15=00/15 = 0. Its precision is 0/00/0, which is undefined because it makes no positive predictions. Report it as undefined rather than as 00 or 11.

These numbers rest on 4040 cases with only 1515 positives, so they are uncertain estimates. They do not show that the scores are calibrated probabilities, that performance holds under other operating conditions or a changed population, or that acting on the predictions leads to better outcomes.

  1. After the test set of this lesson has been opened, a colleague notices that the three missed positives have scores between 0.420.42 and 0.430.43, lowers the threshold to 0.40.4 and reports the new test accuracy 79/80=0.987579/80 = 0.9875. What is wrong with this report? On the validation set, the selected network gives the counts TP=27\text{TP} = 27, FP=6\text{FP} = 6, FN=1\text{FN} = 1 and TN=26\text{TN} = 26 at both thresholds 0.50.5 and 0.40.4. What do these counts say, and what would a sound next step be?
Show the answer

The new threshold was chosen by looking at test labels, so the test set has become development data, and 0.98750.9875 is an optimistic estimate of the accuracy on new cases. It is also not the declared procedure. At threshold 0.40.4 the three missed positives become true positives, but one test negative with score about 0.4750.475 turns into a false positive, which gives TP=34\text{TP} = 34, FP=1\text{FP} = 1, FN=0\text{FN} = 0 and TN=45\text{TN} = 45.

The validation counts are identical at 0.50.5 and 0.40.4, so the evidence that was meant to choose the threshold gives no reason to move it. A threshold should be set before the test is opened, from validation data and from the costs of false negatives and false positives.

The honest report is the declared result, accuracy 0.96250.9625 at threshold 0.50.5, together with the observation that the errors lie near the axes. If a different threshold is wanted, choosing it starts a new development cycle on validation data, and a claim about the new procedure needs fresh test data that played no part in any choice.

How this lesson connects