def log_components(x, w, mus, sigmas):
"""log(w_k N(x; mu_k, sigma_k^2)) for every component k; shape (k, len(x))."""
return (np.log(w)[:, None] - 0.5 * np.log(2 * np.pi * sigmas[:, None] ** 2)
- (x - mus[:, None]) ** 2 / (2 * sigmas[:, None] ** 2))
def log_mix(x, w, mus, sigmas):
"""Log-density of the mixture sum_k w_k N(mu_k, sigma_k^2), computed stably."""
c = log_components(x, w, mus, sigmas)
c_max = c.max(axis=0)
return c_max + np.log(np.exp(c - c_max).sum(axis=0))
def kl(log_a, log_b, x):
"""D_KL(A||B) by quadrature on the grid x; in nats."""
return integrate.trapezoid(np.exp(log_a) * (log_a - log_b), x)