Review: from the linear model to the artificial neuron
Connect a single neural layer with linear, logistic and softmax regression, and derive stable losses and gradients for batched inputs.
After this lesson you can
- Rewrite linear, logistic and softmax regression as one-layer networks with weights W and bias b in batch notation.
- Derive the cross-entropy gradient with respect to logits (P - Y) and W without notes.
- Use shape checks to determine the correct shape of a matrix gradient.
- Interpret weights and bias geometrically as the orientation and displacement of a hyperplane.
- Train a one-layer softmax classifier on 8x8 digits using gradient descent in NumPy.
Before you start
A neuron you already know
You want to recognize a digit from its 64 pixels. A first proposal assigns each class a score: sum the pixels, weighted differently for each digit, and add a constant. Then convert those scores to probabilities. You have studied this model as softmax regression; now look at it as a one-layer network. The same operation will recur inside deeper networks, although their inputs will be features learned by earlier layers.
An artificial neuron takes , computes and returns , where is an activation. The weighted sum abstractly recalls signal integration in a biological neuron; it does not model its temporal dynamics, chemistry or structure. The analogy helps name the component, but does not justify its properties.
Weights and bias are learnable parameters: determines how each feature contributes and shifts the threshold. Before training them, examine their geometry.
For , points satisfying form a hyperplane with normal . The closest point to the origin is : it lies on the plane and any other point on the plane differs from it in a direction perpendicular to . By Pythagoras, the minimum distance is . If , there is no hyperplane: the equation holds everywhere if and nowhere if .
The sigmoid equals at the boundary. Multiplying both parameters by preserves the set , but changes outside it: with large it approaches an abrupt decision. Multiplying only while shifts the boundary. Model probability is not necessarily a calibrated frequency on new data.
A convention for the whole batch
On paper, each example is a column vector. To compute many at once we stack their transposes as rows: the batch convention uses , and . Then
In NumPy X @ W + b uses broadcasting: the same bias row is added to each example. Mathematical indices start at 1; code indices start at 0. is batch size, the number of inputs and the number of outputs. Choosing rows makes representing a batch as a matrix convenient; it does not change the model. A layer torch.nn.Linear(d, k) stores weights as and computes X @ weight.T + bias: this is the transpose of our , not a different model. Matrix multiplication determines shapes; the affine map includes the bias.
Three outputs, three losses
With one output and identity activation, is linear regression. If you assume with fixed variance, minimizing negative log-likelihood is equivalent to minimizing the sum of squares, up to constants and a positive factor. Define here, so .
In binary logistic regression, and . The Bernoulli distribution gives binary cross-entropy . Its derivative with respect to the logit is : the sigmoid derivative cancels the loss denominators. This cancellation is clearer in the stable form , evaluated numerically via logaddexp.
To see this step by step, and . Their product is . With one output, the column of is a weight vector. The decision boundary at threshold is the level set ; changing the threshold changes the level of even with fixed parameters. If class encoding changes to , the loss formula must change too.
For mutually exclusive classes, the layer produces logits and
With a one-hot label, only for the observed class: this is the negative log-likelihood of a categorical distribution. It also accepts nonnegative soft labels summing to one. Cross-entropy does not require probabilities from softmax, but the simplified derivative below does use that combination.
From simplex to gradient
Subtracting a common constant from all logits does not alter probabilities. In particular, subtracting their maximum before exponentiating avoids overflow, and the denominator remains at least one. To obtain a stable loss as well, use , with , instead of computing log(p) after possible underflow.
Proof
By the quotient rule, . Applying the chain rule,
The sum-one assumption matters: for weights summing to , the result would be .
∎With one-hot , : if is the correct class, , and the squared norm is at most . With finite logits all probabilities are positive, so for one does not obtain exactly ; the gradient tends to zero as the correct probability approaches one. For interior soft targets it can vanish with finite logits.
For an average of examples, call the row-wise labels and probabilities . Then . Since , the identity gives
The shapes are , and . A correct shape is a useful check, not a proof: other expressions can have the same shape and be incorrect. The differential identifies the formulas.
In general, for and , the Jacobian has entries and the chain rule gives . If the gradient is represented as a row, this is the vector-Jacobian product . Reverse mode propagates that product without constructing the full Jacobian: for the affine layer, the preceding three formulas are precisely products of that type.
Check one entry of the weight formula: . Therefore , which is entry of . Bias appears in every example of column , so contributions sum; they are already divided by in . For input , all classes of that row contribute: . Redoing these sums can reveal errors even if and every transpose seems to fit.
A useful consequence of softmax symmetry is for each example. A common shift of all logits has zero directional derivative. Do not confuse this symmetry with every gradient component being zero: classes cancel one another.
Lab: 8 × 8 digits
Train one layer on load_digits. The split is stratified and the test set does not participate in training steps. Pixels are divided by 16, the known scale of this dataset, and no statistics are fitted using the test set. The from-scratch model uses full-batch gradient descent; scikit-learn solves the same unpenalized multinomial loss. Their optimizers and stopping criteria differ, so weights and accuracies need not coincide after finitely many steps. Softmax weights also have an indeterminacy: adding the same vector to every column leaves probabilities unchanged; to compare them, center each row across classes.
Gradient descent subtracts each parameter’s gradient multiplied by the learning rate. In this lab every step uses the entire training set: there is no minibatch-selection noise. Mean loss helps compare learning rates when batch size changes, although it does not make stochastic dynamics identical. The finite-difference check compares one isolated element: a useful test, not a proof for all parameters.
import numpy as np
from sklearn.datasets import load_digits
from sklearn.model_selection import train_test_split
digits = load_digits()
X = digits.data.astype(float) / 16.0
y = digits.target
Xtr, Xte, ytr, yte = train_test_split(X, y, test_size=0.25, random_state=42, stratify=y)
print('formas', Xtr.shape, Xte.shape, 'clases', np.unique(ytr))def loss_grad(X, y, W, b):
Z = X @ W + b
shifted = Z - Z.max(axis=1, keepdims=True)
logsum = np.log(np.exp(shifted).sum(axis=1, keepdims=True))
logp = shifted - logsum
P = np.exp(logp)
loss = -logp[np.arange(len(y)), y].mean()
G = P.copy()
G[np.arange(len(y)), y] -= 1
G /= len(y)
return loss, X.T @ G, G.sum(axis=0)
W = np.zeros((Xtr.shape[1], 10))
b = np.zeros(10)
initial = loss_grad(Xtr, ytr, W, b)[0]
for step in range(120):
loss, dW, db = loss_grad(Xtr, ytr, W, b)
W -= 1.0 * dW
b -= 1.0 * db
print('pérdida inicial y final', round(initial, 4), round(loss_grad(Xtr, ytr, W, b)[0], 4))
print('precisión train/test', round(np.mean((Xtr @ W + b).argmax(axis=1) == ytr), 4),
round(np.mean((Xte @ W + b).argmax(axis=1) == yte), 4))eps = 1e-5
Wp = W.copy(); Wm = W.copy()
Wp[20, 3] += eps; Wm[20, 3] -= eps
finite = (loss_grad(Xtr, ytr, Wp, b)[0] - loss_grad(Xtr, ytr, Wm, b)[0]) / (2 * eps)
analytic = loss_grad(Xtr, ytr, W, b)[1][20, 3]
print('gradiente analítico y numérico', round(analytic, 8), round(finite, 8))
z = np.array([2., 1., 0.])
lp = z - z.max() - np.log(np.exp(z - z.max()).sum())
print('ejercicio: pérdida y gradiente', -lp[0], np.exp(lp[0]) - 1)from sklearn.linear_model import LogisticRegression
reference = LogisticRegression(penalty=None, max_iter=200, tol=1e-4)
reference.fit(Xtr, ytr)
print('precisión sklearn train/test', round(reference.score(Xtr, ytr), 4), round(reference.score(Xte, yte), 4))
Wref = reference.coef_.T
Wcenter = W - W.mean(axis=1, keepdims=True)
Wrefcenter = Wref - Wref.mean(axis=1, keepdims=True)
print('correlación de pesos centrados', round(np.corrcoef(Wcenter.ravel(), Wrefcenter.ravel())[0, 1], 4))import matplotlib.pyplot as plt
fig, axes = plt.subplots(2, 10, figsize=(12, 2.5))
v = max(np.abs(Wcenter).max(), np.abs(Wrefcenter).max())
for c in range(10):
for row, weights in enumerate((Wcenter, Wrefcenter)):
axes[row, c].imshow(weights[:, c].reshape(8, 8), cmap='coolwarm', vmin=-v, vmax=v)
axes[row, c].axis('off')
if row == 0:
axes[row, c].set_title(str(c))
fig.suptitle('Arriba: NumPy; abajo: scikit-learn, pesos centrados')
plt.tight_layout()
plt.show()Each image shows contributions to a logit, not a class-average image. The common scale permits magnitude comparison, but an optimizer that advances further can produce weights at a different scale. If training data are strictly separable, unpenalized loss can approach zero as weights grow indefinitely, without reaching a finite minimum. Perfect accuracy does not guarantee parameter convergence. Compare structure and evaluate both models on test data; do not infer generalization from the maps. Change the steps and observe loss, accuracy and correlation; do not choose hyperparameters by repeatedly inspecting the test set, reserve a validation split for that.
Exercises
Step 1 of 3. What is the derivative of p_c with respect to z_j?
softmax_cross_entropy(Z, y) for logits of shape (B, k) and integer labels of length B. Return mean loss and its gradient with respect to Z. Tests check stability and finite differences.import numpy as np
def softmax_cross_entropy(Z, y):
passA neuron composes an affine map and an activation. With examples as rows, the layer is ; softmax and cross-entropy produce error , propagated to weights and inputs through matrix products. Shapes help detect errors, while the chain rule explains why these are the products.
The same vector-Jacobian product is the building block of automatic differentiation; softmax output reappears in transformers, although there each position may have its own distribution over a vocabulary.