Module contents
Lesson 1 of 22Review 60 min

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 x∈Rd\vb{x}\in\R^d, computes z=w⊤x+bz=\vb{w}\T\vb{x}+b and returns a=ϕ(z)a=\phi(z), where ϕ\phi 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: w\vb{w} determines how each feature contributes and bb shifts the threshold. Before training them, examine their geometry.

InteractiveThe neuron as a boundary
  • Probability at least 0.5
  • Probability below 0.5
  • Reference normal
Each grid point is colored by σ(z)\sigma(z); stronger color means the probability is farther from 0.5. The model uses w=cw0\vb{w}=c\vb{w}_0 and b=cb0b=cb_0: scaling both preserves the boundary and changes confidence outside it.
−0.6
1.00
Reference normal w0\vb{w}_0(1.20, 0.80)
Distance to origin0.42
Point logit zz0.80
Probability σ(z)\sigma(z)69.0 %
Move weights and bias: the boundary contains points with zero logit. Scale both weights and bias to preserve it and observe how probabilities change.

For w≠0\vb{w}\ne\vb{0}, points satisfying w⊤x+b=0\vb{w}\T\vb{x}+b=0 form a hyperplane with normal w\vb{w}. The closest point to the origin is −bw/∥w∥2-b\vb{w}/\norm{\vb{w}}^2: it lies on the plane and any other point on the plane differs from it in a direction perpendicular to w\vb{w}. By Pythagoras, the minimum distance is ∣b∣/∥w∥\abs{b}/\norm{\vb{w}}. If w=0\vb{w}=0, there is no hyperplane: the equation holds everywhere if b=0b=0 and nowhere if b≠0b\ne0.

The sigmoid σ(z)=1/(1+e−z)\sigmoid(z)=1/(1+e^{-z}) equals 1/21/2 at the boundary. Multiplying both parameters by c>0c>0 preserves the set z=0z=0, but changes σ(cz)\sigmoid(cz) outside it: with large cc it approaches an abrupt decision. Multiplying only w\vb{w} while b≠0b\ne0 shifts the boundary. Model probability is not necessarily a calibrated frequency on new data.

A convention for the whole batch

On paper, each example xi\vb{x}_i is a column vector. To compute many at once we stack their transposes as rows: the batch convention uses X∈RB×d\mat{X}\in\R^{B\times d}, W∈Rd×k\mat{W}\in\R^{d\times k} and b∈Rk\vb{b}\in\R^k. Then

Z=XW+1Bb⊤∈RB×k,zic=∑j=1dXijWjc+bc.\mat{Z}=\mat{X}\mat{W}+\vb{1}_B\vb{b}\T\in\R^{B\times k},\qquad z_{ic}=\sum_{j=1}^d X_{ij}W_{jc}+b_c.

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. BB is batch size, dd the number of inputs and kk 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 (k,d)(k,d) and computes X @ weight.T + bias: this is the transpose of our W\mat{W}, not a different model. Matrix multiplication determines shapes; the affine map includes the bias.

InteractiveBuild the gradients

For Z=XW+bZ = XW + b, call G=∂L/∂ZG = \partial L/\partial Z. Dimensions BB, dd and kk represent batch, features and outputs.

X
(B, d)
G
(B, k)

Inner dimensions: d and B.

Incompatible: inner dimension d on the left differs from B on the right.

Letters represent distinct dimensions to check structure. If some coincide numerically, more products may also fit. Shape is necessary, not a proof of uniqueness: derive the gradient using the chain rule.

Target gradient
Target shape: (d,k)(d, k)
Combine shapes and transposes to reconstruct products that appear when propagating a derivative. Then check the derivation: a compatible shape is necessary, not sufficient.

Three outputs, three losses

With one output and identity activation, y^i=zi\hat y_i=z_i is linear regression. If you assume yi∣xi∼N(zi,σ2)y_i\mid\vb{x}_i\sim\Normal(z_i,\sigma^2) with fixed variance, minimizing negative log-likelihood is equivalent to minimizing the sum of squares, up to constants and a positive factor. Define L=12B∑i(zi−yi)2L=\frac{1}{2B}\sum_i(z_i-y_i)^2 here, so ∂L/∂zi=(zi−yi)/B\partial L/\partial z_i=(z_i-y_i)/B.

In binary logistic regression, pi=σ(zi)p_i=\sigmoid(z_i) and yi∈{0,1}y_i\in\{0,1\}. The Bernoulli distribution gives binary cross-entropy −yilog⁡pi−(1−yi)log⁡(1−pi)-y_i\log p_i-(1-y_i)\log(1-p_i). Its derivative with respect to the logit is pi−yip_i-y_i: the sigmoid derivative cancels the loss denominators. This cancellation is clearer in the stable form log⁡(1+ezi)−yizi\log(1+e^{z_i})-y_i z_i, evaluated numerically via logaddexp.

To see this step by step, σ′(z)=p(1−p)\sigmoid'(z)=p(1-p) and ∂ℓ/∂p=−y/p+(1−y)/(1−p)\partial\ell/\partial p=-y/p+(1-y)/(1-p). Their product is −y(1−p)+(1−y)p=p−y-y(1-p)+(1-y)p=p-y. With one output, the column of W\mat{W} is a weight vector. The decision boundary at threshold 1/21/2 is the level set z=0z=0; changing the threshold changes the level of zz even with fixed parameters. If class encoding changes to {−1,1}\{-1,1\}, the loss formula must change too.

For k≥2k\ge2 mutually exclusive classes, the layer produces logits zcz_c and

pc=ezc∑j=1kezj,ℓ(z,y)=−∑c=1kyclog⁡pc.p_c=\frac{e^{z_c}}{\sum_{j=1}^k e^{z_j}},\qquad \ell(\vb{z},\vb{y})=-\sum_{c=1}^k y_c\log p_c.

With a one-hot label, yc=1y_c=1 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

InteractiveError in the simplex
  • Predicted distribution p
  • Gradient p − y, projected onto the triangle

The arrow is the barycentric image of p − y: its drawn length is not the Euclidean norm in three dimensions. For finite logits, p lies in the interior and the gradient is nonzero. It approaches zero as the correct probability tends to 1; its norm never exceeds √2.

2.0
1.0
0.0
Correct class
Classpp − y
10.66524−0.33476
20.244730.24473
30.090030.09003
Gradient norm0.42434 / √2
Loss0.408
Change logits and target class. Probabilities sum to one; the error vector is p minus the label. With finite logits and a one-hot label, exact agreement is reached only in the limit.

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 log⁡∑jezj=m+log⁡∑jezj−m\log\sum_j e^{z_j}=m+\log\sum_j e^{z_j-m}, with m=max⁡jzjm=\max_jz_j, instead of computing log(p) after possible underflow.

Proof

By the quotient rule, ∂pc/∂zj=pc(δcj−pj)\partial p_c/\partial z_j=p_c(\delta_{cj}-p_j). Applying the chain rule,

∂ℓ∂zj=−∑cycpcpc(δcj−pj)=−yj+pj∑cyc=pj−yj.\frac{\partial\ell}{\partial z_j} =-\sum_c\frac{y_c}{p_c}p_c(\delta_{cj}-p_j) =-y_j+p_j\sum_c y_c=p_j-y_j.

The sum-one assumption matters: for weights summing to ss, the result would be spj−yjsp_j-y_j.

∎

With one-hot y\vb{y}, ∥p−y∥2≤2\norm{\vb{p}-\vb{y}}_2\le\sqrt2: if tt is the correct class, ∑j≠tpj2≤(∑j≠tpj)2=(1−pt)2\sum_{j\ne t}p_j^2\le(\sum_{j\ne t}p_j)^2=(1-p_t)^2, and the squared norm is at most 2(1−pt)2≤22(1-p_t)^2\le2. With finite logits all probabilities are positive, so for k≥2k\ge2 one does not obtain exactly p=y\vb{p}=\vb{y}; 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 BB examples, call the row-wise labels Y\mat{Y} and probabilities P\mat{P}. Then G=∂L/∂Z=(P−Y)/B\mat{G}=\partial L/\partial\mat{Z}=(\mat{P}-\mat{Y})/B. Since dZ=dXW+XdW+1Bdb⊤d\mat{Z}=d\mat{X}\mat{W}+\mat{X}d\mat{W}+\vb{1}_B d\vb{b}\T, the identity dL=∑icGic dZicdL=\sum_{ic}G_{ic}\,dZ_{ic} gives

∂L∂W=X⊤G,∂L∂b=G⊤1B,∂L∂X=GW⊤.\frac{\partial L}{\partial\mat{W}}=\mat{X}\T\mat{G},\qquad \frac{\partial L}{\partial\vb{b}}=\mat{G}\T\vb{1}_B,\qquad \frac{\partial L}{\partial\mat{X}}=\mat{G}\mat{W}\T.

The shapes are (d,B)(B,k)=(d,k)(d,B)(B,k)=(d,k), (k,B)(B,1)=(k,1)(k,B)(B,1)=(k,1) and (B,k)(k,d)=(B,d)(B,k)(k,d)=(B,d). 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 u=f(x)\vb{u}=f(\vb{x}) and L=g(u)L=g(\vb{u}), the Jacobian JfJ_f has entries ∂ui/∂xj\partial u_i/\partial x_j and the chain rule gives ∇xL=Jf⊤∇uL\nabla_xL=J_f\T\nabla_uL. If the gradient is represented as a row, this is the vector-Jacobian product ∇uL⊤Jf\nabla_uL\T J_f. 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: ∂zic/∂Wjr=Xijδcr\partial z_{ic}/\partial W_{jr}=X_{ij}\delta_{cr}. Therefore ∂L/∂Wjr=∑iGirXij\partial L/\partial W_{jr}=\sum_i G_{ir}X_{ij}, which is entry (j,r)(j,r) of X⊤G\mat{X}\T\mat{G}. Bias brb_r appears in every example of column rr, so contributions sum; they are already divided by BB in G\mat{G}. For input XijX_{ij}, all classes of that row contribute: ∂L/∂Xij=∑cGicWjc\partial L/\partial X_{ij}=\sum_cG_{ic}W_{jc}. Redoing these sums can reveal errors even if B=d=kB=d=k and every transpose seems to fit.

A useful consequence of softmax symmetry is ∑cGic=0\sum_c G_{ic}=0 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.

[ ]Data and reproducible splitBrowser
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))
[ ]Stable softmax and gradients from scratchBrowser
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))
[ ]A derivative versus finite differencesBrowser
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)
[ ]Comparison with scikit-learnBrowser
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))
[ ]Weights as imagesBrowser
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

QuizOne batch, ten classes
If X has shape (64, 20), there are 10 classes and Z = XW + b, what are the shapes of W, b, the weight gradient and the bias gradient respectively?
NumericLoss for one logit vector
For logits (2, 1, 0) and a label in the first class, calculate natural-log cross-entropy for one sample.
NumericGradient of the correct class
With the same logits (2, 1, 0) and label in the first class, calculate the derivative of the loss with respect to the first logit.
ProofDerive the rule without memorizing it
Prove: For a target distribution y summing to one, show that the derivative of cross-entropy with respect to z_j is p_j - y_j.
0
Let p = softmax(z), with finite logits.

Step 1 of 3. What is the derivative of p_c with respect to z_j?

CodeStable loss and gradient
Implement 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):
  pass
Shift+Enter to run
Key idea

A neuron composes an affine map and an activation. With examples as rows, the layer is XW+b\mat{X}\mat{W}+\vb{b}; softmax and cross-entropy produce error P−Y\mat{P}-\mat{Y}, 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.