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 and a feature vector , the classifier of this lesson has one tanh hidden layer of width and computes
where tanh acts entry by entry, is a matrix, and have entries and is a number. The logit gives the score , and with a decision threshold the classifier predicts when . At this is the rule . 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 estimates 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 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 exactly when . Four ReLU hidden units represent it exactly. With , take the logit
Since , the logit equals . It is nonnegative exactly when , that is, when . At the point the logit is , a positive prediction, and at it is . 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 input features, one tanh hidden layer of width and one logit, the trainable arrays are with shape , the vectors and with entries and the number , so the network has parameters. A batch of examples is an array , and the forward pass
produces an hidden array and logits, where is the all-ones vector of length . 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 the count is , so the widths and used below give and parameters, against for logistic regression on the same two features. For a batch of examples and width , the arrays , , and have shapes , , and . In NumPy the forward pass, the loss and the gradients by backpropagation take a few lines. The loss uses the form through np.logaddexp, which never takes the logarithm of a probability that has rounded to or .
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 by . At threshold it predicts on the half-plane where when , and the same class everywhere when . Its mean cross-entropy is convex in . No rule of this form reproduces the same-sign labels. An affine function that is nonnegative at the positive points and is nonnegative at their midpoint , and one that is negative at the negative points and 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 , with validation loss , barely below the value of a constant score . All its logits are negative, so it predicts the negative class for every training, validation and test case. Since of the training cases are positive, it makes the same decisions as the majority-class rule. On the test cases it is right for the negatives, an accuracy of , its recall is , and its precision is undefined because it makes no positive predictions. A designed feature would change the picture. With the inputs , and , the logit with any is nonnegative exactly when , so a logistic regression with 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 , with training, validation and test cases and the label exactly when . 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 , shuffled mini-batches of at most cases and a budget of 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.
| Candidate | Parameters | Best epoch | Validation loss | Validation accuracy |
|---|---|---|---|---|
| Logistic regression | ||||
| Network, width | ||||
| Network, width |
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 , the test set is opened once. The selected network has , , and , so its accuracy is , its recall is , its precision is and its test cross-entropy is about . Having no false positives among negatives does not show that the false positive rate is zero. If the test negatives are independent draws, an exact one-sided percent upper confidence bound for that rate is . The three missed positives lie at about , and , each within of an axis, with scores near , and all seven validation errors lie within 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 .
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 , and , and seed sets the initial weights and the mini-batch order. The network weights start as normal draws with mean and standard deviation , which is for and for , the biases start at , and the baseline starts from all zeros. In an additional check on the same data, the training seeds to , which include seed , give best validation losses from to for the width-4 network, with mean about , and from to for the width-12 network, with mean about . With seed the width-4 network scores and the width-12 network , the reverse of the seed-7 ranking in the table above. The average over the ten seeds favors width on this construction, but the ranges overlap, so a choice between the widths should rest on several seeds and not on one.
Check yourself
- A network has input features, one tanh hidden layer of width 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 examples?
Show the answer
The weight matrix has shape , which gives parameters, the hidden bias and the output weights have entries each, and the output bias is one number. The total is , which agrees with . For a batch of examples the hidden array has shape , and there are logits, one for each example.
- A selected model is evaluated once on test cases with , , and . 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 actual positives and actual negatives. The model’s accuracy is , its precision is and its recall is .
The baseline is right for the negatives, so its accuracy is , and it finds none of the positives, so its recall is . Its precision is , which is undefined because it makes no positive predictions. Report it as undefined rather than as or .
These numbers rest on cases with only 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.
- After the test set of this lesson has been opened, a colleague notices that the three missed positives have scores between and , lowers the threshold to and reports the new test accuracy . What is wrong with this report? On the validation set, the selected network gives the counts , , and at both thresholds and . 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 is an optimistic estimate of the accuracy on new cases. It is also not the declared procedure. At threshold the three missed positives become true positives, but one test negative with score about turns into a false positive, which gives , , and .
The validation counts are identical at and , 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 at threshold , 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.