Contents
Deep Breakdown
What it tells me (Situation Awareness): The derivative of the natural log is the reciprocal function . The absolute value sign extends the domain to (where is defined) without changing the formula. In DA/DS: appears in log-likelihoods, cross-entropy loss, KL divergence, information gain (decision trees), and any model using maximum likelihood estimation. The gradient of the log-likelihood always passes through this formula. Chain rule extension: , which appears when differentiating log-likelihoods of parametric distributions.
Flowchart
Real-world use
Where it is used
Cross-entropy gradient: ; MLE score equations; entropy gradient; log-likelihood of normal, Poisson, Bernoulli distributions; decision tree information gain (mutual information); log-sum-exp differentiation; KL divergence gradient.
Problem it solves
Any loss function involving a logarithm requires this derivative for gradient computation. The binary cross-entropy loss gradient uses directly.
How it solves the problem
Proof: since , differentiate both sides: , so .
Example in a business
A DS fits a Poisson regression for count data (e.g., number of purchases per customer). Log-likelihood: where . Score: — uses directly.
The formula, piece by piece
- : natural logarithm of absolute value; extends to negative
- : the derivative; same for and (note: for )
- Chain rule: ; the "logarithmic derivative" of
- Score function:
- Cross-entropy gradient: ; and
- Integral: — logarithm is the antiderivative of
- Higher derivatives: ;
The formula in words
"The rate of change of the natural log is the reciprocal. A 1% change in changes by approximately — logarithms measure relative/proportional changes." Tiny examples: (chain rule; gives same result). . (cross-entropy gradient at single sample with ground truth 1).
Critical Concepts
- Log-likelihood gradient = score: . The expectation of the score is zero: — the foundation of the Fisher information.
- Logarithmic differentiation technique: to differentiate complex products/quotients , take , differentiate both sides: , giving .
- Information theory connection: entropy gradient uses . This is used in decision tree split criteria (information gain).
- Numerical log-gradient: in practice, compute for numerical stability, then use for the gradient — or use autograd tools.
Direct can overflow when ; add clip.
Step-by-step calculation (tiny example)
Gradient of binary cross-entropy: with , .
Step 1: With : .
Step 2: Differentiate using : .
Step 3: Interpretation: at (predicted probability 0.7 for true class), the gradient is . A small increase decreases loss: consistent with gradient descent pushing .
Step 4: Full cross-entropy gradient at , : .
Code examples
Beginner example (Python)
import numpy as np
def log_derivative(x: float) -> float:
"""d/dx(ln|x|) = 1/x."""
return 1 / x
def cross_entropy_gradient(p: float, y: int) -> float:
"""Gradient of binary CE: dL/dp = -y/p + (1-y)/(1-p). Uses d/dp(log p) = 1/p."""
p = np.clip(p, 1e-9, 1 - 1e-9)
return -y / p + (1 - y) / (1 - p) # Numerical verification
x_vals = np.array([0.5, 1.0, 2.0, 4.0, 10.0])
h = 1e-7
print("d/dx(ln|x|) = 1/x verification")
print(f"{'x':>6} {'1/x':>10} {'numerical':>12} {'match':>7}")
for x in x_vals:
analytic = log_derivative(x)
numerical = (np.log(abs(x + h)) - np.log(abs(x - h))) / (2 * h)
match = abs(analytic - numerical) < 1e-5
print(f"{x:>6.1f} {analytic:>10.6f} {numerical:>12.6f} {str(match):>7}") # Cross-entropy gradient
print("\nCross-entropy gradient dL/dp at y=1")
for p in [0.1, 0.5, 0.7, 0.9, 0.99]:
grad = cross_entropy_gradient(p, y=1)
print(f" p={p:.2f}: dL/dp = {grad:.4f} {'(large penalty)' if p < 0.3 else ''}")Beginner example (R)
# d/dx(ln|x|) = 1/x
log_deriv <- function(x) 1 / x # Cross-entropy gradient: d/dp(-y*log(p) - (1-y)*log(1-p)) = -y/p + (1-y)/(1-p)
ce_gradient <- function(p, y) { p <- pmax(pmin(p, 1 - 1e-9), 1e-9) -y / p + (1 - y) / (1 - p)
} # Verify numerically
x_vals <- c(0.5, 1.0, 2.0, 4.0, 10.0)
h <- 1e-7
cat(sprintf("%-6s %-10s %-12s\n", "x", "1/x", "numerical"))
for (x in x_vals) { analytic <- log_deriv(x)
numerical <- (log(abs(x + h)) - log(abs(x - h))) / (2 * h)
cat(sprintf("%-6.1f %-10.6f %-12.6f\n", x, analytic, numerical))
}Professional example (Python)
import numpy as np
from sklearn.datasets import make_classification
from sklearn.preprocessing import StandardScaler
from sklearn.metrics import roc_auc_score
np.random.seed(42) # -- Logistic regression gradient: d/dp(-log p) = 1/p in action ---------------
X_raw, y = make_classification( n_samples=800, n_features=6, n_informative=4, random_state=42 )
scaler = StandardScaler()
X = np.hstack([np.ones((len(y), 1)), scaler.fit_transform(X_raw)])
N, D = X.shape
def sigmoid(z: np.ndarray) -> np.ndarray:
return 1 / (1 + np.exp(-np.clip(z, -500, 500)))
def log_loss(w: np.ndarray) -> float:
"""Binary cross-entropy: -sum(y*log(p) + (1-y)*log(1-p)) / N."""
p = sigmoid(X @ w)
p = np.clip(p, 1e-9, 1 - 1e-9)
return float(-np.mean(y * np.log(p) + (1 - y) * np.log(1 - p)))
def log_loss_gradient(w: np.ndarray) -> np.ndarray:
"""Gradient via d/dp(-log p) = 1/p: dL/dw = X^T (p - y) / N Derivation: dL/dp = -y/p + (1-y)/(1-p); dp/dw = p(1-p)*x; chain rule gives p-y. """
p = sigmoid(X @ w)
return X.T @ (p - y) / N # Gradient descent on log-loss
w = np.zeros(D)
LEARNING_RATE = 0.5
losses = []
for step in range(300):
losses.append(log_loss(w))
w -= LEARNING_RATE * log_loss_gradient(w)
p_final = sigmoid(X @ w)
auc = roc_auc_score(y, p_final)
print("Logistic Regression via d/dx(ln x) = 1/x gradient")
print(f"{'Step':>6} {'Log-loss':>10}")
for step in [0, 49, 99, 199, 299]:
print(f"{step+1:>6} {losses[step]:>10.5f}")
print(f"\nFinal AUC: {auc:.4f}")
print(f"\nKey: d/dp(-log p) = 1/p -> gradient of CE = X^T(p-y)/N")
print(f"This is the log derivative d/dx(ln x) = 1/x applied to the likelihood.")Source: 1300 p. 220