Calculus for Biological Data
A growth curve describes population size at each time. Its derivative describes how fast that size changes. An integral accumulates a rate over an interval. These two operations also explain probability densities and the gradients used to fit models.
Read powers and logarithms and random variables first.
A derivative is a local rate
Section titled “A derivative is a local rate”The derivative f'(t) is the limit of (f(t+h)-f(t))/h as h approaches zero, when that limit exists. It measures the slope at a point rather than the average slope across a long interval.
For constant proportional growth, N(t) = N(0)*exp(r*t) and N'(t) = r*N(t). The population has units of cells, while the derivative has units of cells per hour when time uses hours.
import numpy as np
initial_population = 100.0rate = 0.4time = 2.0population = initial_population * np.exp(rate * time)exact_derivative = rate * populationprint(f"Population: {population:.4f}")print(f"Derivative: {exact_derivative:.4f} cells/hour")for step in [0.1, 0.01, 0.001]: upper = initial_population * np.exp(rate * (time + step)) lower = initial_population * np.exp(rate * (time - step)) approximate = (upper - lower) / (2.0 * step) print(f"Step {step:.3f}: derivative {approximate:.4f}")Population: 222.5541Derivative: 89.0216 cells/hourStep 0.100: derivative 89.0454Step 0.010: derivative 89.0219Step 0.001: derivative 89.0216The symmetric difference approximates the local slope. Smaller steps reduce approximation error initially, but floating point cancellation eventually limits the calculation. A numerical derivative does not become more accurate indefinitely as the step shrinks.
See the local rate
Section titled “See the local rate”A secant joins two points on a curve and gives their average rate of change. A tangent touches the curve with its local slope at the chosen point. For a smooth curve, bringing the secant’s points together makes its slope approach the derivative.
from pathlib import Path
import matplotlib.pyplot as plt
curve_time = np.linspace(0.0, 4.0, 160)curve_population = initial_population * np.exp(rate * curve_time)left_time, right_time = time - 1.0, time + 1.0left_population = initial_population * np.exp(rate * left_time)right_population = initial_population * np.exp(rate * right_time)secant_slope = (right_population - left_population) / (right_time - left_time)tangent = population + exact_derivative * (curve_time - time)secant = left_population + secant_slope * (curve_time - left_time)fig, ax = plt.subplots(figsize=(7, 4))ax.plot(curve_time, curve_population, label="Growth curve")ax.plot(curve_time, tangent, "--", label="Tangent at the chosen time")ax.plot(curve_time, secant, ":", label="Secant across the interval")ax.scatter([left_time, time, right_time], [left_population, population, right_population], color="black")ax.set(xlabel="Time (hours)", ylabel="Population", ylim=(0, 550))ax.legend()fig.tight_layout()Path("outputs").mkdir(exist_ok=True)fig.savefig("outputs/derivative_geometry.png", dpi=160)plt.close(fig)print(f"Average rate across the interval: {secant_slope:.4f}")print(f"Local rate at its midpoint: {exact_derivative:.4f}")Average rate across the interval: 91.4146Local rate at its midpoint: 89.0216
Differentiate a composition
Section titled “Differentiate a composition”The chain rule gives the derivative of a function applied inside another function. For f(g(t)), multiply the outer derivative evaluated at g(t) by the inner derivative g'(t).
For exp(r*t), the outer derivative is exp(r*t) and the inner derivative is r. This supplies the factor r in the growth derivative. The same rule propagates derivatives through the layers of a neural network.
Useful rules include the derivative of t**k, which is k*t**(k-1), and the derivative of ln(t), which is 1/t for positive t. A constant has derivative zero.
To apply the chain rule to the growth model, write the inner function as u(t)=r*t and the outer function as f(u)=N(0)*exp(u). The inner derivative is r; the outer derivative is N(0)*exp(u). Multiplying them and substituting u=r*t gives N'(t)=r*N(0)*exp(r*t).
Keeping the inner and outer functions separate makes the origin of each factor visible. Omitting the inner derivative would treat a change in time as the same change in the exponent, which is incorrect unless the rate happens to equal one.
Integrals accumulate a quantity
Section titled “Integrals accumulate a quantity”Integrating a growth rate between two times gives the change in population across that interval. Integrating a probability density gives a probability instead. The units of the integrand determine the units of the integral.
from scipy.integrate import quadfrom scipy.stats import norm
def standard_normal_density(value): """Return the standard normal probability density.
Args: value: Position on the standard normal axis.
Returns: Probability density at the supplied position. """ return np.exp(-0.5 * value ** 2) / np.sqrt(2.0 * np.pi)
area, integration_error = quad(standard_normal_density, -1.0, 1.0)print(f"Probability between -1 and 1: {area:.6f}")print(f"CDF difference: {norm.cdf(1.0) - norm.cdf(-1.0):.6f}")assert np.isclose(area, norm.cdf(1.0) - norm.cdf(-1.0))Probability between -1 and 1: 0.682689CDF difference: 0.682689The integration error is a numerical estimate from the algorithm. It is not statistical uncertainty in a biological measurement.
from pathlib import Path
import matplotlib.pyplot as plt
positions = np.linspace(-4.0, 4.0, 401)density = standard_normal_density(positions)fig, ax = plt.subplots(figsize=(7, 3.8))ax.plot(positions, density)inside = (positions >= -1.0) & (positions <= 1.0)ax.fill_between(positions, density, where=inside, alpha=0.3)ax.set(xlabel="Standardized value", ylabel="Probability density")fig.tight_layout()Path("outputs").mkdir(exist_ok=True)fig.savefig("outputs/normal_integral.png", dpi=160)plt.close(fig)
Partial derivatives form a gradient
Section titled “Partial derivatives form a gradient”A model usually has several parameters. A partial derivative changes one parameter while holding the others fixed. The gradient collects those partial derivatives into a vector.
For squared error L(a,b) = mean((a+b*x-y)**2), the derivative with respect to a is 2*mean(residual). The derivative with respect to b is 2*mean(residual*x).
inputs = np.array([0.0, 1.0, 2.0])observed = np.array([1.0, 3.0, 5.0])intercept = 0.0slope = 0.0residual = intercept + slope * inputs - observedgradient = np.array([2.0 * residual.mean(), 2.0 * (residual * inputs).mean()])print("Gradient for intercept and slope:", np.round(gradient, 4))Gradient for intercept and slope: [-6. -8.6667]The negative gradient gives a local direction of decreasing loss. The step size still matters.
Check your understanding
Section titled “Check your understanding”Why does integrating a density over a wider interval never reduce the resulting probability?
A probability density is nonnegative. Expanding the interval adds nonnegative area to the integral. This argument concerns probability densities; the integral of an arbitrary signed function can decrease when the interval expands.
Further reading
Section titled “Further reading”-
The reference defines integration limits, absolute error estimates, and tolerance arguments. Use those definitions to interpret the normal-density integral.
-
Google gradient descent lesson
The lesson connects derivatives of a loss to parameter updates. Its learning-rate examples extend the regression gradient calculated here.
Continue with likelihood and estimation before using gradients in optimization.