MATH 4310 · Computational Bioinformatics
Neural Networks and Autoencoders
Lesson 24 · 2027-04-21 · Week 15
Core question
How can a flexible model learn, from examples, patterns in cells and sequences that are too complicated to write down by hand?
Sorted cells and a rule to learn
T cells mature in the thymus, and flow cytometry can follow them there. Fluorescent stains for two surface proteins, CD4 and CD8, give one intensity per marker for each cell, as for the blood cells of Lesson 19. The most immature thymus cells carry neither marker, cells of intermediate maturity carry both, and the most mature carry exactly one.1 Figure 24.1 shows such a sample with simulated values, one record per cell. Suppose a further stain, applied to these 400 cells only, has told us which are mature. We want a rule that reads the two intensities of a new cell and reports whether it is mature. Here is one simulated record from each of the four groups.
| CD4 intensity | CD8 intensity | Mature (1 = yes) |
|---|---|---|
| 1.41 | 0.85 | 0 |
| 3.74 | 3.73 | 0 |
| 4.31 | 0.92 | 1 |
| 0.42 | 3.94 | 1 |
Python Simulate CD4 and CD8 readings with maturity labels
import numpy as np
def thymus_cells(n_each: int, spread: float,
seed: int) -> tuple[np.ndarray, np.ndarray]:
"""Simulated (CD4, CD8) intensities; label 1 marks cells with exactly one marker."""
rng = np.random.default_rng(seed)
# neither marker, both markers, CD4 only, CD8 only
centers = np.array([[0.8, 0.7], [4.0, 3.9], [4.0, 0.8], [0.9, 3.8]])
clouds = []
for center in centers:
clouds.append(center + spread * rng.standard_normal((n_each, 2)))
return np.vstack(clouds), np.repeat([0.0, 0.0, 1.0, 1.0], n_each)
cells, mature = thymus_cells(100, 0.45, seed=24)
print("CD4, CD8, mature:")
for i in [0, 100, 200, 300]:
print(f"{cells[i, 0]:5.2f} {cells[i, 1]:5.2f} {int(mature[i])}")Figure 24.1. Simulated CD4 and CD8 intensities for 400 thymus cells. The simulation labels a cell mature when it carries exactly one marker, and draws 100 cells of each kind, although in a mouse thymus most cells carry both.1 No straight line separates the mature cells from the rest.
No such rule is given in advance, and a straight-line score of the kind earlier lessons used cannot give one (Figure 24.1). What experiments supply is examples, records whose answers are known. The models of this lesson are flexible. Fitting them to examples chooses their shape, including new coordinates in which the cells become easy to sort. Each is a statistical model in the sense of Lesson 21, with many parameters set only by the examples.
Definition 24.1 Fitting a function to examples
Input: examples \((x_1,c_1),\ldots,(x_n,c_n)\), where the row \(x_i\in\mathbb R^p\) holds \(p\) measured features and \(c_i\) is a known target; a function \(f_\theta\) with adjustable parameters \(\theta\); a loss \(\mathcal L(\theta)\ge0\) that is small when the outputs \(f_\theta(x_i)\) agree with the targets; and further examples kept aside for evaluation.
Output: parameters with small loss, and the loss on the examples kept aside.
Assumption: new examples arise in the same way as the given ones.
For DNA windows simulated from two known chains the right score can be calculated independently, so we check there first what fitting learns.
Gradient descent
Lesson 20 placed cells in the plane by repeatedly moving every point “a step against the gradient” of a cost, without saying why such a step lowers the cost. The reason holds for any loss that can be differentiated.
The partial derivative \(\partial\mathcal L/\partial\theta_j\) is the ordinary derivative with respect to \(\theta_j\) while the other parameters are held fixed, and the gradient \(\nabla\mathcal L(\theta)\) is the list of partial derivatives. For small changes \(\Delta\theta_j\) in all the parameters at once, each contributes its slope times its change, as a tangent line does for one variable: \[ \mathcal L(\theta+\Delta\theta)\approx\mathcal L(\theta)+\sum_j\frac{\partial\mathcal L}{\partial\theta_j}\,\Delta\theta_j . \] Choose every change against its own slope, \(\Delta\theta_j=-\eta\,\partial\mathcal L/\partial\theta_j\), with a small step size \(\eta>0\). The sum becomes \(-\eta\sum_j(\partial\mathcal L/\partial\theta_j)^2\), which is negative unless every slope is zero, so a small enough step of this kind lowers the loss.
Algorithm Gradient descent
Input: a function that evaluates the gradient of \(\mathcal L\), starting parameters \(\theta_{\mathrm{init}}\), a step size \(\eta>0\), a number of steps \(N\), and optionally a function of \(\theta\) to record, such as the loss.
Output: the parameters \(\theta\) after \(N\) steps and the values recorded before each update if recording was enabled.
- \(\theta\leftarrow\theta_{\mathrm{init}}\).
// set starting parameters - Initialize the
list of recorded values \(H\leftarrow[]\).
// start the history Forstep \(k=0,\ldots,N-1\):Ifa recording function is supplied, evaluate it at \(\theta\) and append its value to \(H\).// save value now- \(g\leftarrow\nabla\mathcal L(\theta)\).
// slope for each parameter - \(\theta\leftarrow\theta-\eta g\).
// step against the gradient
Returnthe updated parameters \(\theta\) and the list \(H\).// report fit and history
from collections.abc import Callable
def gradient_descent(theta: dict, gradient: Callable[[dict], dict], eta: float,
n_steps: int, record: Callable[[dict], object] | None = None
) -> tuple[dict, list]:
"""Repeat theta <- theta - eta * gradient(theta); record before each step."""
history = []
for _ in range(n_steps):
if record is not None:
history.append(record(theta))
slope = gradient(theta)
updated = {}
for name in theta:
updated[name] = theta[name] - eta * slope[name]
theta = updated
return theta, historyThese few lines fit every model in this lesson. Only the function that computes the gradient changes.
Logistic regression: a score fitted to labels
A CpG island is a stretch of DNA rich in CG pairs. Lesson 9 scored a 20-base window by adding one number for each adjacent pair of bases, numbers it derived from two Markov chains. Keep that form and suppose the numbers are unknown. Describe a window by its 16 pair counts, in a row \(x\) of features, with the label \(c=1\) for an island and \(c=0\) for background. With one weight per feature, in a column \(w\), and a constant \(b\), logistic regression outputs \[ f_\theta(x)=\sigma(xw+b),\qquad \sigma(u)=\frac{1}{1+e^{-u}},\qquad \theta=(w,b). \] The logistic function \(\sigma\) rises from 0 to 1, so the output can be read as the probability of an island. The odds of an island are \(f_\theta/(1-f_\theta)\), and solving for the weighted sum gives \[ \ln\frac{f_\theta(x)}{1-f_\theta(x)}=xw+b . \] The score \(xw+b\) is the log-odds, and each weight is the log-odds added by one more pair of its kind. The logarithm is natural, so the unit is the nat, which is \(1/\ln2\approx1.44\) bits.
A loss should be small when the model gives high probability to the observed labels. A window labeled 1 gets probability \(f_\theta(x_i)\) and a window labeled 0 gets \(1-f_\theta(x_i)\). Both cases can be written at once, \[ P(c_i\mid x_i)=f_\theta(x_i)^{c_i}\,\bigl(1-f_\theta(x_i)\bigr)^{1-c_i}, \] because an exponent of zero turns the factor that does not apply into 1. For independent windows the probability of all the labels is the product of these factors. Its logarithm is a sum, and dividing by \(-n\) gives a loss to minimize: \[ \mathcal L(\theta)=-\frac1n\sum_{i=1}^n\Bigl[c_i\ln f_\theta(x_i)+(1-c_i)\ln\bigl(1-f_\theta(x_i)\bigr)\Bigr]. \] Minimizing this log loss is maximum likelihood for the labels. Answering \(1/2\) for every window gives a loss of \(\ln2\approx0.693\), whatever the labels are.
For the gradient, write \(u=xw+b\) for one window’s score and \(\mathcal L_i\) for its term of the loss. The quotient rule gives \[ \sigma'(u)=\frac{e^{-u}}{(1+e^{-u})^2}=\sigma(u)\bigl(1-\sigma(u)\bigr), \] so \[ \frac{d\mathcal L_i}{du}=-c\,\frac{\sigma'(u)}{\sigma(u)}+(1-c)\,\frac{\sigma'(u)}{1-\sigma(u)} =-c\,\bigl(1-\sigma(u)\bigr)+(1-c)\,\sigma(u)=\sigma(u)-c . \] The slope of a window’s loss in its own score is its error, the output minus the label. The score changes by \(x_j\) per unit of \(w_j\) and by 1 per unit of \(b\), so averaging over windows,
Equation (24.1)
\[ \frac{\partial\mathcal L}{\partial w_j}=\frac1n\sum_{i=1}^n\bigl(f_\theta(x_i)-c_i\bigr)\,x_{ij}, \qquad \frac{\partial\mathcal L}{\partial b}=\frac1n\sum_{i=1}^n\bigl(f_\theta(x_i)-c_i\bigr). \]
A background window scored too high therefore pushes down the weights of the pairs it contains.
Example 24.1 One step on four windows
Use one feature, the number of CG pairs. Four windows have 0, 1, 2, and 4 CG pairs and the labels 0, 1, 0, 1, mixed so that no threshold separates them and the best weight is finite. At \(w=b=0\) every output is \(\sigma(0)=1/2\), the loss is \(\ln2=0.693\), and the errors are \(\tfrac12,-\tfrac12,\tfrac12,-\tfrac12\), so \[ \frac{\partial\mathcal L}{\partial w}=\frac14\Bigl[\tfrac12(0)-\tfrac12(1)+\tfrac12(2)-\tfrac12(4)\Bigr]=-0.375, \qquad \frac{\partial\mathcal L}{\partial b}=\frac14\Bigl[\tfrac12-\tfrac12+\tfrac12-\tfrac12\Bigr]=0 . \] With \(\eta=1\) the step gives \(w=0.375\) and \(b=0\). The outputs become \(0.500\), \(0.593\), \(0.679\), and \(0.818\), and the loss falls to \(0.639\).
Python Fit logistic regression to four CpG windows
def sigmoid(u: np.ndarray) -> np.ndarray:
"""Logistic function 1 / (1 + exp(-u))."""
return 1 / (1 + np.exp(-u))
def log_loss(f: np.ndarray, c: np.ndarray) -> float:
"""Average of -log(probability given to the true label)."""
f = np.clip(f, 1e-12, 1 - 1e-12) # keeps the logarithms finite
return float(-np.mean(c * np.log(f) + (1 - c) * np.log(1 - f)))
def logistic_output(theta: dict, X: np.ndarray) -> np.ndarray:
"""f(x) = sigmoid(x w + b) for every row of X."""
return sigmoid(X @ theta["w"] + theta["b"])
def logistic_gradient(theta: dict, X: np.ndarray, c: np.ndarray) -> dict:
"""Partial derivatives of the log loss: error times input, averaged."""
error = logistic_output(theta, X) - c
return {"w": X.T @ error / len(c), "b": float(np.mean(error))}
cg_counts = np.array([[0.0], [1.0], [2.0], [4.0]]) # one row per window
is_island = np.array([0.0, 1.0, 0.0, 1.0])
start = {"w": np.zeros(1), "b": 0.0}
def four_gradient(theta: dict) -> dict:
return logistic_gradient(theta, cg_counts, is_island)
def four_loss(theta: dict) -> float:
return log_loss(logistic_output(theta, cg_counts), is_island)
for n_steps in [1, 500]:
theta, _ = gradient_descent(start, four_gradient, eta=1.0, n_steps=n_steps)
print(f"{n_steps} steps: w = {theta['w'][0]:.3f}, b = {theta['b']:.3f}, "
f"loss = {four_loss(theta):.3f}")
four_fit = thetaAfter 500 steps the fit settles at \(w=0.842\) and \(b=-1.414\) with loss \(0.552\), so each additional CG pair multiplies the odds of an island by \(e^{0.842}\approx2.3\) (Figure 24.2, panel A).
Python Compare gradient descent at three step sizes
def four_surface(w: np.ndarray, b: np.ndarray) -> np.ndarray:
"""Log loss of the four windows on a grid of (w, b) values."""
total = np.zeros_like(w, dtype=float)
for count, label in zip(cg_counts[:, 0], is_island):
f = sigmoid(w * count + b)
total -= label * np.log(f) + (1 - label) * np.log(1 - f)
return total / len(is_island)
def weight_and_constant(theta: dict) -> tuple[float, float]:
return theta["w"][0], theta["b"]
def descent_path(eta: float, n_steps: int) -> np.ndarray:
"""The (w, b) pairs visited by gradient descent from the origin."""
_, visited = gradient_descent(start, four_gradient, eta, n_steps,
record=weight_and_constant)
return np.array(visited)
trajectory = descent_path(1.0, 80)
loss_by_step_size = {}
for eta in (0.1, 1.0, 3.0):
visited = descent_path(eta, 41)
loss_by_step_size[eta] = four_surface(visited[:, 0], visited[:, 1])Figure 24.2. Gradient descent on the four windows of the worked example. (A) Contours of the loss, with the path from w = b = 0 (square) to the minimum (red) at step size 1. (B) Loss against step for three step sizes. At 0.1 progress is slow, at 1 the fit converges, and at 3 the loss oscillates across the 40 steps shown.
Step size and mini-batches
The step size \(\eta\) has to be chosen. With \(\eta=0.1\) the loss is still far from its minimum after 40 steps, with \(\eta=1\) it has nearly arrived, and with \(\eta=3\) each step jumps across the valley and the loss never settles (panel B). Lesson 21’s forward Euler method failed in the same way with too long a time step, because gradient descent is Euler’s method for \(\dot\theta=-\nabla\mathcal L(\theta)\) with \(\eta\) as the time step (Exercise 24.3). In practice one tries a few values and watches the loss.
With millions of examples, computing every error at every step is costly. Stochastic gradient descent estimates the gradient from a small random mini-batch \(B\) of the examples, \[ \frac{\partial\mathcal L}{\partial w_j}\approx\frac1{|B|}\sum_{i\in B}\bigl(f_\theta(x_i)-c_i\bigr)\,x_{ij}. \] At each step, draw a fresh batch of example indices, average their gradient contributions at the current parameters, and use that estimate in the update. A uniformly drawn batch gives the full gradient on average, although a single step can raise the full loss. The large models at the end of this lesson are fitted this way.
Sixteen weights and Lesson 9’s table
Now fit all 16 weights to 1,000 island and 1,000 background windows simulated from Lesson 9’s two chains. Both chains choose the first base uniformly and the classes are equally common, so the log-odds of an island is the sum of that lesson’s pair scores, the logarithm of each island transition probability over the background one.
Every window has 19 pairs, so adding a number to all 16 weights and subtracting 19 times it from the constant changes no score. Only differences between weights can be learned, and we measure both tables from their CC entry.
Python Simulate windows from Lesson 9's chains and fit 16 weights
island_chain = np.array([[0.2, 0.3, 0.3, 0.2], [0.1, 0.3, 0.5, 0.1],
[0.2, 0.3, 0.3, 0.2], [0.2, 0.3, 0.3, 0.2]])
background_chain = np.array([[0.3, 0.2, 0.2, 0.3], [0.3, 0.3, 0.1, 0.3],
[0.3, 0.2, 0.2, 0.3], [0.3, 0.2, 0.2, 0.3]])
def pair_count_row(chain: np.ndarray, width: int,
rng: np.random.Generator) -> np.ndarray:
"""Simulate one window from a Markov chain and return its 16 pair counts."""
counts = np.zeros((4, 4)) # rows: first base A, C, G, T; columns: second base
previous = rng.integers(4)
for _ in range(width - 1):
current = rng.choice(4, p=chain[previous])
counts[previous, current] += 1
previous = current
return counts.ravel()
rng = np.random.default_rng(24)
island_rows = [pair_count_row(island_chain, 20, rng) for _ in range(1000)]
background_rows = [pair_count_row(background_chain, 20, rng) for _ in range(1000)]
pair_counts = np.array(island_rows + background_rows)
window_label = np.repeat([1.0, 0.0], 1000)
batch_rng = np.random.default_rng(24)
def window_gradient(theta: dict) -> dict:
return logistic_gradient(theta, pair_counts, window_label)
def batch_gradient(theta: dict) -> dict:
"""The same gradient, estimated from 50 randomly chosen windows."""
chosen = batch_rng.choice(len(window_label), size=50, replace=False)
return logistic_gradient(theta, pair_counts[chosen], window_label[chosen])
def window_loss(theta: dict) -> float:
return log_loss(logistic_output(theta, pair_counts), window_label)
zeros = {"w": np.zeros(16), "b": 0.0}
full_fit, _ = gradient_descent(zeros, window_gradient, eta=0.5, n_steps=4000)
batch_fit, _ = gradient_descent(zeros, batch_gradient, eta=0.05, n_steps=4000)
# Every window has 19 pairs, so adding one number to all 16 weights and taking
# 19 times it from the constant changes no score. Compare weights relative to CC.
lesson9_table = np.log(island_chain / background_chain)
lesson9_table = lesson9_table - lesson9_table[1, 1]
fitted_table = full_fit["w"].reshape(4, 4)
fitted_table = fitted_table - fitted_table[1, 1]
print(f"loss: full gradient {window_loss(full_fit):.3f}, "
f"mini-batches of 50 {window_loss(batch_fit):.3f}")
print(f"CG relative to CC: fitted {fitted_table[1, 2]:.2f} nats, "
f"from the chains {lesson9_table[1, 2]:.2f} nats "
f"({lesson9_table[1, 2] / np.log(2):.2f} bits)")
print(f"largest difference between the two tables: "
f"{np.max(np.abs(fitted_table - lesson9_table)):.2f} nats")Figure 24.3. Weights fitted to 2,000 simulated windows (A) and the pair scores derived from the two chains in Lesson 9 (B), each measured from its CC entry, in nats; rows give the first base of a pair and columns the second. The fit saw only labeled windows and recovers the derived contrasts up to sampling error.
Gradient descent saw labeled windows and never the chains, and its weights agree with the derived scores to within 0.27 nats (Figure 24.3). CG stands highest, 1.60 nats above CC where the chains give 1.61 nats, or 2.32 bits. A fitted weight is thus an estimate, from examples alone, of a log-odds that a derivation would give if we had one. Mini-batches of 50 windows reach nearly the same loss, 0.201 against 0.200, at one-fortieth of the arithmetic per step.
Neural networks
A rule no weighted sum can express
On the thymus cells of Figure 24.1, logistic regression fails. Gradient descent ends with weights near zero, a loss of 0.6925 where answering \(1/2\) gives 0.6931, and 51.5% of the cells correct.
Python Fit logistic regression to the thymus cells
cell_mean, cell_sd = cells.mean(axis=0), cells.std(axis=0)
scaled = (cells - cell_mean) / cell_sd # center and scale each marker
def line_gradient(theta: dict) -> dict:
return logistic_gradient(theta, scaled, mature)
line_fit, _ = gradient_descent({"w": np.zeros(2), "b": 0.0}, line_gradient,
eta=0.5, n_steps=2000)
line_output = logistic_output(line_fit, scaled)
print(f"logistic regression: weights {np.round(line_fit['w'], 2)}, "
f"loss {log_loss(line_output, mature):.4f}, "
f"{np.mean((line_output > 0.5) == (mature == 1)):.1%} correct")The reason is geometric. Idealize each marker as 0 when absent and 1 when present, and let \(u(x)=xw+b\) be any linear score. Then \[ u(1,0)+u(0,1)=w_1+w_2+2b=u(0,0)+u(1,1). \] A score that separated the classes would be positive at both single-marker cells and negative at the other two, which would make the left side positive and the right side negative.
Layers, and a network worked by hand
The remedy is to compute new coordinates for each cell first, in which a linear score does work.
Definition 24.2 Layer and neural network
A layer with \(m\) units maps a row \(x\in\mathbb R^p\) to \(h=\phi(xW+b)\in\mathbb R^m\), where \(W\in\mathbb R^{p\times m}\) is a matrix of weights, \(b\in\mathbb R^m\) is a row of constants, and \(\phi\) is a fixed function applied to each entry, nonlinear except in some output layers. A neural network is a composition of layers. With one hidden layer and a logistic output, \[ h=\phi\bigl(xW^{(1)}+b^{(1)}\bigr),\qquad f_\theta(x)=\sigma\bigl(hw^{(2)}+b^{(2)}\bigr), \] and \(\theta\) collects the weights and constants of both layers.
The output is logistic regression applied to the hidden values \(h\) in place of \(x\). Without \(\phi\) in the hidden layer, the score \((xW^{(1)}+b^{(1)})w^{(2)}+b^{(2)}\) multiplies out to a linear score in \(x\), which we have just ruled out. We use the rectified linear unit \(\phi(u)=\max(0,u)\), which replaces negative values by zero.
Example 24.2 A two-unit network for the thymus cells
Take idealized inputs \(x=(\text{CD4},\text{CD8})\) with entries 0 or 1, and \[ W^{(1)}=\begin{pmatrix}1&1\\1&1\end{pmatrix},\qquad b^{(1)}=(0,\,-1),\qquad w^{(2)}=\begin{pmatrix}4\\-8\end{pmatrix},\qquad b^{(2)}=-2 . \]
| cell | \(x\) | \(h\) | score \(hw^{(2)}+b^{(2)}\) | \(f_\theta(x)\) |
|---|---|---|---|---|
| neither marker | \((0,0)\) | \((0,0)\) | \(-2\) | 0.119 |
| CD4 only | \((1,0)\) | \((1,0)\) | \(2\) | 0.881 |
| CD8 only | \((0,1)\) | \((1,0)\) | \(2\) | 0.881 |
| both markers | \((1,1)\) | \((2,1)\) | \(-2\) | 0.119 |
In the last row, \(h_1=\max(0,2)=2\) and \(h_2=\max(0,2-1)=1\), so the score is \(4(2)-8(1)-2=-2\).
Both hidden units read only the total \(s=\text{CD4}+\text{CD8}\). The first, \(h_1=\max(0,s)\), counts the markers, and the second, \(h_2=\max(0,s-1)\), switches on only past one marker. The score \(4h_1-8h_2-2\) is therefore \(4s-2\) up to \(s=1\) and \(6-4s\) beyond it, a tent with its peak at exactly one marker. One straight line in \(s\) has no peak, and two bent pieces added together do. In the hidden coordinates the line \(4h_1-8h_2=2\) cuts off the stretch around \((1,0)\) where the single-marker cells sit (Figure 24.4, panel B).
Backpropagation
Suitable weights exist. To find them from the cells we use gradient descent again, which needs the partial derivative of the loss with respect to every weight in both layers. These come from the chain rule for derivatives. When a weight affects the loss only through a chain of intermediate quantities, its derivative is the product of the slopes along the chain.
For one cell, write \(u=xW^{(1)}+b^{(1)}\) for the inputs to the hidden units, \(h=\phi(u)\) for their values, and \(v=hw^{(2)}+b^{(2)}\) for the score, and let \(\mathcal L_i\) be the cell’s term of the loss. The output layer is logistic regression with \(h\) as its input, so the calculation behind Equation 24.1 applies unchanged. The slope with respect to the score is the error, and each output weight multiplies one hidden value: \[ \delta^{(2)}=\frac{\partial\mathcal L_i}{\partial v}=f_\theta(x)-c,\qquad \frac{\partial\mathcal L_i}{\partial w^{(2)}_k}=\delta^{(2)}\,h_k . \] A first-layer weight \(W^{(1)}_{jk}\), from input \(j\) to hidden unit \(k\), reaches the loss through the chain \[ W^{(1)}_{jk}\ \longrightarrow\ u_k\ \longrightarrow\ h_k\ \longrightarrow\ v\ \longrightarrow\ \mathcal L_i , \] whose four slopes are \(x_j\), \(\phi'(u_k)\), \(w^{(2)}_k\), and \(\delta^{(2)}\). The slope \(\phi'(u)\) is 1 for positive \(u\) and 0 for negative \(u\). At zero the two slopes differ, and the backward sweep uses 0 there. Multiplying the four, \[ \frac{\partial\mathcal L_i}{\partial W^{(1)}_{jk}}=x_j\,\delta^{(1)}_k,\qquad \delta^{(1)}_k=\delta^{(2)}\,w^{(2)}_k\,\phi'(u_k). \] In both layers the derivative for a weight is the input it multiplies times the error at the unit it feeds, and the constants follow the same rule with input 1. Panel A of Figure 24.4 gives the numbers for one cell of the hand network.
Algorithm Backpropagation for one hidden layer
Input: feature rows \(x_i\in\mathbb R^p\) and labels \(c_i\in\{0,1\}\) for cells \(i=1,\ldots,n\). The network has \(m\) hidden units and current weights and constants \(W^{(1)},b^{(1)},w^{(2)},b^{(2)}\).
Output: the gradient of the mean log loss with respect to these weights and constants.
- Initialize sums \(G_1,g_1,G_2,g_2\) to zero with the shapes of \(W^{(1)},b^{(1)},w^{(2)},b^{(2)}\), respectively.
Foreach cell \(i=1,\ldots,n\):- \(u_i\leftarrow x_i W^{(1)}+b^{(1)}\).
// compute hidden inputs - \(h_i\leftarrow\phi(u_i)\), applying the ReLU
\(\phi(t)=\max(0,t)\) to each entry.
// zero negative inputs - \(f_i\leftarrow\sigma(h_iw^{(2)}+b^{(2)})\),
where \(\sigma\) is the sigmoid.
// probability of class 1 - \(\delta_i^{(2)}\leftarrow f_i-c_i\).
// output error = f − c Foreach hidden unit \(k=1,\ldots,m\):If\(u_{ik}>0\), set \(\delta_{ik}^{(1)}\leftarrow\delta_i^{(2)}w_k^{(2)}\).// send output error backElse, set \(\delta_{ik}^{(1)}\leftarrow0\). This uses a ReLU slope of zero at \(u_{ik}=0\).// block the error
- \(G_2\leftarrow G_2+h_i^\top\delta_i^{(2)}\)
and \(g_2\leftarrow
g_2+\delta_i^{(2)}\).
// sum output-layer gradients - \(G_1\leftarrow G_1+x_i^\top\delta_i^{(1)}\) and \(g_1\leftarrow g_1+\delta_i^{(1)}\). Here \(\delta_i^{(1)}\) is the row of hidden errors \(\delta_{ik}^{(1)}\). The product \(x_i^\top\delta_i^{(1)}\) is a \(p\times m\) matrix with entries \(x_{ij}\delta_{ik}^{(1)}\), matching \(W^{(1)}\).
- \(u_i\leftarrow x_i W^{(1)}+b^{(1)}\).
Return\((G_1/n,g_1/n,G_2/n,g_2/n)\), the averages over the \(n\) cells.
The output error is computed once and reused by every first-layer weight, so one forward and one backward sweep give all the derivatives at roughly the cost of evaluating the loss twice. Nudging each weight in turn would take one more evaluation for each of the 33 parameters of the network fitted below. With more hidden layers the backward step repeats once per layer (see the collapsed block), and libraries such as PyTorch generate the calculation automatically.
Python Backpropagation for one hidden layer
def relu(u: np.ndarray) -> np.ndarray:
"""phi(u) = max(0, u), entry by entry."""
return np.maximum(u, 0)
def network_output(theta: dict, X: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Hidden values h and outputs f for every row of X."""
h = relu(X @ theta["W1"] + theta["b1"])
return h, sigmoid(h @ theta["w2"] + theta["b2"])
def network_gradient(theta: dict, X: np.ndarray, c: np.ndarray) -> dict:
"""Backpropagation for one hidden layer and the log loss."""
h, f = network_output(theta, X)
delta2 = (f - c) / len(c) # output errors, with the 1/n of the average
delta1 = np.outer(delta2, theta["w2"]) * (h > 0) # hidden errors
return {"W1": X.T @ delta1, "b1": delta1.sum(axis=0),
"w2": h.T @ delta2, "b2": float(delta2.sum())}Python Check the hand network, fit eight hidden units, and test one derivative
def random_network(n_hidden: int, seed: int) -> dict:
"""Starting weights drawn from a standard normal; constants start at zero."""
rng = np.random.default_rng(seed)
return {"W1": rng.standard_normal((2, n_hidden)), "b1": np.zeros(n_hidden),
"w2": rng.standard_normal(n_hidden), "b2": 0.0}
def cell_gradient(theta: dict) -> dict:
return network_gradient(theta, scaled, mature)
def cell_loss(theta: dict) -> float:
return log_loss(network_output(theta, scaled)[1], mature)
hand = {"W1": np.array([[1.0, 1.0], [1.0, 1.0]]), "b1": np.array([0.0, -1.0]),
"w2": np.array([4.0, -8.0]), "b2": -2.0}
corners = np.array([[0.0, 0.0], [1.0, 0.0], [0.0, 1.0], [1.0, 1.0]])
print("hand network on the four ideal cells:",
np.round(network_output(hand, corners)[1], 3))
on_off = (cells - 0.8) / 3.2 # rescaled so that absent is near 0, present near 1
hand_output = network_output(hand, on_off)[1]
print(f"hand network on the simulated cells: "
f"{np.sum((hand_output > 0.5) == (mature == 1))} of 400 correct")
trained, _ = gradient_descent(random_network(8, seed=24), cell_gradient,
eta=1.0, n_steps=2000)
trained_output = network_output(trained, scaled)[1]
print(f"fitted network: loss {cell_loss(trained):.4f}, "
f"{np.sum((trained_output > 0.5) == (mature == 1))} of 400 correct")
# Test one backpropagated derivative by changing that weight a little.
check = random_network(8, seed=0)
backpropagated = cell_gradient(check)["W1"][0, 1]
check["W1"][0, 1] += 1e-6
loss_up = cell_loss(check)
check["W1"][0, 1] -= 2e-6
loss_down = cell_loss(check)
print(f"backpropagation {backpropagated:.8f}, "
f"difference quotient {(loss_up - loss_down) / 2e-6:.8f}")
# One cell with both markers, labeled immature: forward values, then errors.
x_one, c_one = np.array([[1.0, 1.0]]), 0.0
h_one, f_one = network_output(hand, x_one)
delta2_one = f_one[0] - c_one
delta1_one = delta2_one * hand["w2"] * (h_one[0] > 0)
hidden, _ = network_output(hand, on_off)With each intensity rescaled so that an absent marker is near 0 and a present one near 1, the hand network sorts 395 of the 400 simulated cells correctly (panel B). Gradient descent from random starting weights, with eight hidden units, finds a network that sorts all 400 with loss \(0.0006\) (panel C). As a check on backpropagation, shifting one weight slightly in both directions gives a central difference quotient of \(0.06822012\), the same value as the corresponding derivative to eight decimal places.
Going deeper backpropagation through more layers
With a second hidden layer between the first and the output, a unit of the first layer reaches the loss through every unit of the second. The chain rule then adds one product of slopes per route. If the second layer has errors \(\delta^{(2)}_1,\ldots,\delta^{(2)}_m\) and the weight from first-layer unit \(k\) to second-layer unit \(l\) is \(W^{(2)}_{kl}\), the error at unit \(k\) is \[ \delta^{(1)}_k=\Bigl(\sum_{l=1}^m\delta^{(2)}_l\,W^{(2)}_{kl}\Bigr)\,\phi'(u_k). \] The sum is the row of errors multiplied by the transpose of the weight matrix, which is the product that appears in the algorithm. Each further layer repeats the step, so the backward sweep costs about as much as the forward one however deep the network is.
Training loss and held-out loss
A network with enough units can fit almost any labels, which is why the problem statement keeps examples aside. Suppose only 40 cells had been sorted, on an instrument so noisy that the clouds overlap, and we fit the same eight-unit network while following its loss on 2,000 further cells.
Python Fit the network and track training and held-out loss
few_cells, few_labels = thymus_cells(10, 1.0, seed=1)
held_cells, held_labels = thymus_cells(500, 1.0, seed=2)
few_mean, few_sd = few_cells.mean(axis=0), few_cells.std(axis=0)
few_scaled = (few_cells - few_mean) / few_sd
held_scaled = (held_cells - few_mean) / few_sd # scaled with the training values
def few_gradient(theta: dict) -> dict:
return network_gradient(theta, few_scaled, few_labels)
def both_losses(theta: dict) -> tuple[float, float]:
"""Loss on the 40 training cells and on the 2,000 held-out cells."""
return (log_loss(network_output(theta, few_scaled)[1], few_labels),
log_loss(network_output(theta, held_scaled)[1], held_labels))
_, curves = gradient_descent(random_network(8, seed=0), few_gradient,
eta=0.5, n_steps=5000, record=both_losses)
curves = np.array(curves)
best = int(np.argmin(curves[:, 1]))
print(f"training loss: {curves[0, 0]:.3f} at the start, "
f"{curves[-1, 0]:.4f} at the end")
print(f"held-out loss: lowest {curves[best, 1]:.3f} at step {best}, "
f"{curves[-1, 1]:.3f} at the end")Figure 24.5. Loss of an eight-unit network on its 40 training cells and on 2,000 cells held out of the fit, against the number of gradient steps (logarithmic axis). The training loss keeps falling while the held-out loss reaches its minimum (red) and then rises.
The training loss falls from \(0.779\) to \(0.0016\) as the network memorizes its 40 labels, including those of cells that landed in the wrong cloud by chance.2(sec. 12.4) The loss on the held-out cells reaches \(0.326\) at step 114, then more than doubles (Figure 24.5). It ends at \(0.780\), worse than the 0.693 of always answering \(1/2\), because log loss charges heavily for a confident wrong answer.
Cells used to choose when to stop form a validation set, and their lowest loss is no longer the loss on examples that played no part in the fit. A report of how well the rule works needs a third group, a test set, untouched until every choice has been made.
Key idea
A fitted model is three choices: examples, a function with adjustable parameters, and a loss. Gradient descent sets the parameters, and examples kept out of the fit show how far the result can be trusted.
Autoencoders
Most cells come with no labels, and what is wanted from them is often a position along a process. A tissue in which cells mature holds cells at every stage at once, and no measurement says how far along a cell is. Ordering cells by an inferred progress, called pseudotime, was introduced for single-cell RNA data.3
Suppose two genes are measured in 200 cells of a maturing tissue. Gene 1 rises almost steadily as a cell matures, and gene 2 peaks midway. Each simulated cell has a hidden progress \(\tau\) between 0 and 1 that sets its expected expression, to which noise is added, and no method below is shown \(\tau\) (Figure 24.6, panel A). We want one number per cell from which the cell’s state can be read back.
Lesson 15’s answer is the score on the first principal component. Here PC1 lies almost exactly along gene 1, so its score replaces each cell by a point on a straight line (panel B), which loses gene 2 and leaves 23.0% of the squared spread unexplained.
Python Simulate a curved expression profile and compute its first PC
def curved_cells(n: int, seed: int) -> tuple[np.ndarray, np.ndarray]:
"""Two-gene cells along an arc, and their hidden progress tau in [0, 1]."""
rng = np.random.default_rng(seed)
tau = np.sort(rng.uniform(0, 1, n))
angle = np.pi / 2 + 2.0 * (1 - 2 * tau) # the arc sweeps about 230 degrees
arc = 3 * np.column_stack([np.cos(angle), np.sin(angle)])
return arc + 0.3 * rng.standard_normal((n, 2)), tau
def center_and_scale(cells: np.ndarray) -> np.ndarray:
"""Center each gene, then divide both by one common scale."""
centered = cells - cells.mean(axis=0)
return centered / centered.std()
def pc1_fit(Z: np.ndarray) -> tuple[np.ndarray, np.ndarray, float]:
"""PC1 direction, PC1 scores, and the share of squared spread PC1 leaves."""
_, singular_values, Vt = np.linalg.svd(Z, full_matrices=False)
left = singular_values[1] ** 2 / np.sum(singular_values ** 2)
return Vt[0], Z @ Vt[0], left
curve_cells, tau = curved_cells(200, seed=24)
Z_curve = center_and_scale(curve_cells)
pc1_direction, pc1_scores, pc1_left = pc1_fit(Z_curve)
print(f"PC1 direction {np.round(pc1_direction, 2)}, "
f"squared spread left: {pc1_left:.1%}")Figure 24.6. Simulated cells along a curved process, both genes centered and put on one scale. (A) The cells colored by hidden progress, which only the simulation knows. (B) Each cell (black) joined to its reconstruction from one principal component (red). Every reconstruction lies on a straight line, so gene 2 is lost.
Encoder, decoder, and the linear case
An autoencoder uses each cell as its own target but passes it through fewer numbers than it has, so the fit must find the few numbers that describe a cell best.
Definition 24.3 Autoencoder
Input: centered rows \(z_1,\ldots,z_n\in\mathbb R^p\) and a code size \(r<p\). An encoder maps each row to a code \(t_i\in\mathbb R^r\), and a decoder maps the code to a reconstruction \(\hat z_i\in\mathbb R^p\). Both have adjustable parameters \(\theta\).
Output: parameters minimizing the reconstruction loss \(\mathcal L(\theta)=\frac1n\sum_{i=1}^n\|z_i-\hat z_i\|^2\).
In Lesson 15 a score was \(t_i=z_iv\) and a reconstruction was \(\hat z_i=t_iv^\top\). Let both maps be general matrices instead, \(t_i=z_iW_{\rm enc}\) and \(\hat z_i=t_iW_{\rm dec}\) with \(W_{\rm enc}\in\mathbb R^{p\times r}\) and \(W_{\rm dec}\in\mathbb R^{r\times p}\), so that the reconstructed matrix is \(\hat Z=ZW_{\rm enc}W_{\rm dec}\). Could fitting these matrices find something that PCA does not?
Theorem 24.1 A linear autoencoder recovers PCA
Let the centered matrix \(Z\) have singular values \(d_1\ge d_2\ge\cdots\), and let \(V_r\) hold its first \(r\) loading directions as columns.
- Every linear autoencoder with code size \(r\) has \(\|Z-\hat Z\|_F^2\ge\sum_{j>r}d_j^2\).
- The choice \(W_{\rm enc}=V_r\), \(W_{\rm dec}=V_r^\top\) attains this value, with the first \(r\) PCA scores as codes.
- So does \(W_{\rm enc}=V_rM\), \(W_{\rm dec}=M^{-1}V_r^\top\) for any invertible \(r\times r\) matrix \(M\), with every code multiplied by \(M\).
Proof
The matrix \(\hat Z=(ZW_{\rm enc})W_{\rm dec}\) is a product through \(r\) columns, so its rank is at most \(r\), and Lesson 15’s best low-rank result gives \[ \|Z-\hat Z\|_F^2\ \ge\ \min_{\operatorname{rank}(A)\le r}\|Z-A\|_F^2=\sum_{j>r}d_j^2 . \] The PCA choice gives \(\hat Z=ZV_rV_r^\top=Z_r\), the best rank-\(r\) matrix itself, with codes \(ZV_r\). Since \((ZV_rM)(M^{-1}V_r^\top)=ZV_rV_r^\top\), inserting \(M\) changes the codes and no reconstruction.
The best linear reconstruction therefore has the same squared error as PCA. On Lesson 15’s four samples a gradient-descent run reaches a total squared error of 6.000, the rank-one error computed by hand there, or 1.500 per sample. The codes are less settled, since part 3 leaves them free up to \(M\), which for \(r=1\) is a scale and a sign.
A nonlinear autoencoder
To follow a curve, the encoder and the decoder each get a hidden layer, so that two inputs feed eight hidden units, one code, eight more hidden units, and two outputs. The hidden layers use \(\phi=\tanh\), a smooth S-shaped function with values between \(-1\) and \(1\), which gives a smooth reconstructed curve where \(\max(0,u)\) would give corners. The code and the output have no nonlinearity.
For each cell \(i\), the forward pass applies the encoder to \(z_i\) to get \(t_i\), then applies the decoder to \(t_i\) to get \(\hat z_i\). Start the backward pass with the squared-error slope \(2(\hat z_i-z_i)\). Work backward through the decoder and the encoder, multiplying at each layer by the transpose of its weight matrix and then by the activation slopes of the preceding layer. Those slopes are \(1-h^2\) at a hidden unit with value \(h=\tanh(u)\) and \(1\) at the code. Average the weight and constant derivatives over cells and use them for the next gradient-descent update.
Python Encode and reconstruct a cell
def encode(theta: dict, Z: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Hidden values and one-number codes for every row of Z."""
h1 = np.tanh(Z @ theta["W1"] + theta["b1"])
return h1, h1 @ theta["W2"] + theta["b2"]
def decode(theta: dict, codes: np.ndarray) -> tuple[np.ndarray, np.ndarray]:
"""Hidden values and reconstructions for every code."""
h2 = np.tanh(codes @ theta["W3"] + theta["b3"])
return h2, h2 @ theta["W4"] + theta["b4"]Python Backpropagation for the autoencoder, the linear check, and two fits
def autoencoder_gradient(theta: dict, Z: np.ndarray) -> dict:
"""Backpropagation through decoder and encoder for the mean squared error."""
h1, codes = encode(theta, Z)
h2, output = decode(theta, codes)
delta4 = 2 * (output - Z) / len(Z) # errors at the output
delta3 = delta4 @ theta["W4"].T * (1 - h2 ** 2) # tanh'(u) = 1 - tanh(u)^2
delta2 = delta3 @ theta["W3"].T # the code has no nonlinearity
delta1 = delta2 @ theta["W2"].T * (1 - h1 ** 2)
# each layer: the input it multiplies, times the errors at the units it feeds
return {"W1": Z.T @ delta1, "b1": delta1.sum(axis=0),
"W2": h1.T @ delta2, "b2": delta2.sum(axis=0),
"W3": codes.T @ delta3, "b3": delta3.sum(axis=0),
"W4": h2.T @ delta4, "b4": delta4.sum(axis=0)}
def linear_gradient(theta: dict) -> dict:
"""Gradient of ||Z - Z W_enc W_dec||^2 on Lesson 15's four samples."""
codes = Z15 @ theta["enc"]
residual = codes @ theta["dec"] - Z15
return {"enc": 2 * Z15.T @ residual @ theta["dec"].T,
"dec": 2 * codes.T @ residual}
X15 = np.array([[4, 7, 5], [5, 6, 3], [7, 10, 3], [8, 9, 5]], dtype=float)
Z15 = X15 - X15.mean(axis=0)
rng = np.random.default_rng(0)
small = {"enc": 0.1 * rng.standard_normal((3, 1)),
"dec": 0.1 * rng.standard_normal((1, 3))}
linear_fit, _ = gradient_descent(small, linear_gradient, eta=0.02, n_steps=200)
squared_error = np.sum((Z15 @ linear_fit["enc"] @ linear_fit["dec"] - Z15) ** 2)
print(f"linear autoencoder on Lesson 15's four samples: squared error "
f"{squared_error:.3f} in total, {squared_error / 4:.3f} per sample")
def random_autoencoder(n_hidden: int, seed: int) -> dict:
"""Random starting weights for a 2 - n_hidden - 1 - n_hidden - 2 autoencoder."""
rng = np.random.default_rng(seed)
return {"W1": rng.standard_normal((2, n_hidden)) / np.sqrt(2),
"b1": np.zeros(n_hidden),
"W2": rng.standard_normal((n_hidden, 1)) / np.sqrt(n_hidden),
"b2": np.zeros(1),
"W3": rng.standard_normal((1, n_hidden)),
"b3": np.zeros(n_hidden),
"W4": rng.standard_normal((n_hidden, 2)) / np.sqrt(n_hidden),
"b4": np.zeros(2)}
def fit_autoencoder(Z: np.ndarray, seed: int) -> tuple[dict, np.ndarray, float]:
"""Fitted parameters, the cells' codes, and the share of squared spread left."""
def gradient(theta: dict) -> dict:
return autoencoder_gradient(theta, Z)
theta, _ = gradient_descent(random_autoencoder(8, seed), gradient,
eta=0.05, n_steps=3000)
codes = encode(theta, Z)[1]
left = np.sum((decode(theta, codes)[1] - Z) ** 2) / np.sum(Z ** 2)
return theta, codes.ravel(), left
def rank_correlation(a: np.ndarray, b: np.ndarray) -> float:
"""Correlation between the ranks of a and the ranks of b."""
return float(np.corrcoef(np.argsort(np.argsort(a)),
np.argsort(np.argsort(b)))[0, 1])
five_cells = [0, 50, 100, 150, 199] # cells are sorted by progress
print("progress tau of five cells:", np.round(tau[five_cells], 2))
runs = []
for seed in [0, 1]:
theta, codes, left = fit_autoencoder(Z_curve, seed)
runs.append((theta, codes))
print(f"autoencoder, start {seed}: squared spread left {left:.1%}, "
f"codes of the five cells {np.round(codes[five_cells], 2)}, "
f"rank correlation with tau {rank_correlation(codes, tau):+.3f}")
print(f"PC1 score: rank correlation with tau "
f"{abs(rank_correlation(pc1_scores, tau)):.3f}")Figure 24.7. The autoencoder on the cells of Figure 24.6. (A) Each cell (black) joined to its reconstruction from a one-number code (red); the reconstructions follow the curve. (B) The codes of two fits from different random starts against hidden progress. Both order the cells, in opposite directions and with uneven spacing.
From one number per cell the autoencoder reconstructs both genes, leaving 1.4% of the squared spread on these cells where PC1 left 23.0% (Figure 24.7, panel A).
Reading a latent coordinate
The code is a latent coordinate, a number that no instrument measured. Because these cells were simulated, it can be compared with \(\tau\) through the rank correlation, the correlation between the cells’ ranks by code and their ranks by \(\tau\). Both fits order the cells almost perfectly, with rank correlations of \(+0.995\) and \(-0.995\) (panel B). The PC1 score nearly matches them at 0.980, because it tracks gene 1, so on these cells the autoencoder’s gain over PC1 is the reconstruction of gene 2.
The direction of the code is arbitrary, since one fit increases with \(\tau\) and the other decreases. Its spacing is arbitrary too. At five cells about evenly spaced in \(\tau\), the first fit’s codes are \(-1.47\), \(-0.67\), \(0.09\), \(0.81\), and \(2.34\), so the last quarter of the process takes up twice as much code as any other. The decoder can undo any such stretching, the nonlinear counterpart of \(M\) in Theorem 24.1.
Nor does a code show that the tissue follows one process, because a one-unit bottleneck returns one number per cell even for cells on a branching path.
A small reconstruction error does not certify the order either. A maturing thymus cell goes from carrying neither of CD4 and CD8 to carrying both and then, in one lineage, CD4 only, a path with a sharp turn.
Python Fit cells along the thymus path, which has a sharp turn
def turning_cells(n: int, seed: int) -> tuple[np.ndarray, np.ndarray]:
"""Cells along neither -> both -> CD4 only; tau is the share of path length."""
rng = np.random.default_rng(seed)
corners = np.array([[0.8, 0.7], [4.0, 3.9], [4.0, 0.8]])
lengths = np.linalg.norm(np.diff(corners, axis=0), axis=1)
turn = lengths[0] / lengths.sum() # progress at which the path turns
tau = np.sort(rng.uniform(0, 1, n))
path = np.empty((n, 2))
for i, progress in enumerate(tau):
if progress < turn:
path[i] = corners[0] + progress / turn * (corners[1] - corners[0])
else:
share = (progress - turn) / (1 - turn)
path[i] = corners[1] + share * (corners[2] - corners[1])
return path + 0.3 * rng.standard_normal((n, 2)), tau
turn_cells, turn_tau = turning_cells(200, seed=24)
Z_turn = center_and_scale(turn_cells)
_, turn_scores, turn_left = pc1_fit(Z_turn)
print(f"PC1: squared spread left {turn_left:.1%}, rank correlation with tau "
f"{abs(rank_correlation(turn_scores, turn_tau)):.2f}")
for seed in [0, 1, 2]:
_, codes, left = fit_autoencoder(Z_turn, seed)
print(f"autoencoder, start {seed}: squared spread left {left:.1%}, "
f"rank correlation with tau {abs(rank_correlation(codes, turn_tau)):.2f}")On 200 cells simulated along that path, the same autoencoder from three starts leaves 7 to 9% of the squared spread where PC1 leaves 20.7%, yet its code orders the cells worse than the PC1 score does, with rank correlations near 0.68 against 0.73.
Caution A latent coordinate is not a measured time
Two cells with nearby codes have similar reconstructions, and how well each reconstruction matches its cell has to be checked separately. The sign of a code, its spacing, the order it gives, and the existence of a single process all need independent evidence, such as a marker of stage.
Models for sequences and cells
The models now used on sequences and cells are instances of Definition 24.1, with millions to billions of parameters and kinds of layers this lesson did not build. Five families follow, as they stood in 2026 (Figure 24.8). For one training example, write \(c\) for the target, \(\hat c=f_\theta(x)\) for the output, and \(\mathcal L_i\) for the example’s term of the loss. Each model lowers the average of \(\mathcal L_i\) by gradient steps on mini-batches, and each display keeps only the main term of the published loss.
Figure 24.8. Five model families as input, fitted function, and output against target. On the right of each strip the output is drawn in black over the target in grey, and red marks what the loss measures: the probability of the true residue, distances between atoms, and gaps between predicted and measured values. The recipe of examples, function, and loss is the same in all five.
Protein language models. ESM-2 reads a protein sequence in which a random set \(S\) of positions is hidden, and gives a probability to each amino acid at each hidden position.4 With \(\hat c_j\) the probability given to the true residue at position \(j\), \[ \mathcal L_i=-\frac1{|S|}\sum_{j\in S}\ln\hat c_j . \] This is the log loss with 20 classes in place of 2, and the sequence supplies its own labels. An earlier model of this kind scores a substitution by the difference between the log probabilities of the new and the old residue.5
Structure prediction. AlphaFold 2 reads a sequence and an alignment of its relatives and outputs a position for every atom, with measured structures as targets.6 Let \(c_{ra}\) be the position of atom \(a\) as seen from residue \(r\), so that turning or shifting the whole protein changes nothing. In simplified form, the loss is the average distance between predicted and measured positions, \[ \mathcal L_i\approx\operatorname*{mean}_{r,a}\,\bigl\|\hat c_{ra}-c_{ra}\bigr\| . \]
Sequence-to-function models. Enformer reads about 200,000 bases of DNA and predicts the signal of 5,313 human experiments \(k\) in bins \(j\) of 128 bases.7 It treats each measured signal \(c_{jk}\) as a count whose expected value is the prediction \(\hat c_{jk}\). Its loss is minus the log-probability of those counts, which apart from a constant is \[ \mathcal L_i=\sum_{j,k}\bigl(\hat c_{jk}-c_{jk}\ln\hat c_{jk}\bigr). \] AlphaGenome reads a million bases and predicts more kinds of measurement.8 The models of this family tested in 2023 explained little of the expression differences between people at one gene, and often got the direction of a variant’s effect wrong.9,10
Perturbation prediction. A proposed “virtual cell” would predict how expression changes when a gene is perturbed.11 With \(c\) the measured change in each gene’s log expression, one representative loss is the squared error \[ \mathcal L_i=\|\hat c-c\|^2 . \] In a 2025 benchmark, five foundation models and two other deep networks predicted the change after perturbing genes \(A\) and \(B\) together no better than the sum \(c_A+c_B\) of the two measured single-gene changes.12
Count autoencoders. scVI is the autoencoder of this lesson with a likelihood for counts.13 From a cell’s code \(t_i\), its decoder gives a probability \(P_\theta(x_{ig}\mid t_i)\) to the observed count of each gene \(g\): \[ \mathcal L_i=-\sum_{g}\ln P_\theta(x_{ig}\mid t_i)+D_i . \] The sum replaces squared error by minus the log-probability of the counts, and the penalty \(D_i\ge0\) keeps the codes from spreading without limit. The warning above applies to these codes.
Exercises
Exercise 24.1. Continue Example 24.1. From \(w=0.375\) and \(b=0\), compute the four errors and both partial derivatives, take one more step with \(\eta=1\), and check that the loss decreased.
Exercise 24.2. For the hand network of Example 24.2 and a cell with CD4 only whose label is 1, compute the forward values \(u\), \(h\), and \(f_\theta(x)\), then the errors \(\delta^{(2)}\) and \(\delta^{(1)}\) produced by the backward sweep, and from them the derivative of the cell’s loss with respect to each entry of \(W^{(1)}\). Which first-layer weights does a gradient step leave unchanged?
Exercise 24.3. For the quadratic loss \(\mathcal L(\theta)=\tfrac\kappa2(\theta-\theta^*)^2\) with curvature \(\kappa>0\), show that gradient descent gives \(\theta_{k+1}-\theta^*=(1-\eta\kappa)(\theta_k-\theta^*)\), and state for which step sizes the steps converge. Which quantity in Lesson 21’s analysis of Euler’s method plays the role of \(\kappa\)?
Exercise 24.4. A colleague fits a one-number autoencoder to cells from a tissue. For each claim, say whether the fit supports it and what further evidence it would need. (a) Two cells with nearly equal codes have similar measured expression. (b) A cell with code 1.0 is twice as far along as a cell with code 0.5.
References 15 sources
Cited in the text
Also drawn on