The Best-Fitting Bell Curve

Bayesian InferenceMedium+20 XP+20

The Best-Fitting Bell Curve

A sensor's readings are assumed to come from a normal distribution with an unknown mean μ\muμ and variance σ2\sigma^2σ2. Maximum likelihood estimation (MLE) picks the μ\muμ and σ2\sigma^2σ2 that make the observed readings most probable, using the data alone — no prior.

For a single reading xxx, the normal density is

f(x)=12πσ2  e−(x−μ)22σ2f(x) = \frac{1}{\sqrt{2\pi\sigma^2}}\; e^{-\frac{(x-\mu)^2}{2\sigma^2}}f(x)=2πσ2​1​e−2σ2(x−μ)2​

The readings are independent, so the likelihood of the whole dataset is the product of their densities. A product of hundreds of small numbers is too small for a float to hold, so instead we maximise the log-likelihood, the sum of the logs, which peaks at exactly the same place:

ℓ(μ,σ2)=∑i=1nln⁡f(xi)\ell(\mu, \sigma^2) = \sum_{i=1}^{n} \ln f(x_i)ℓ(μ,σ2)=i=1∑n​lnf(xi​)

For the normal distribution the peak is known exactly:

μ^=1n∑i=1nxi,σ^2=1n∑i=1n(xi−μ^)2\hat\mu = \frac{1}{n}\sum_{i=1}^{n} x_i, \qquad \hat\sigma^2 = \frac{1}{n}\sum_{i=1}^{n} (x_i - \hat\mu)^2μ^​=n1​i=1∑n​xi​,σ^2=n1​i=1∑n​(xi​−μ^​)2

Task: write normal_mle(data) that returns [mu_hat, var_hat, log_lik]: the two estimates, then the log-likelihood at the peak, ℓ(μ^,σ^2)\ell(\hat\mu, \hat\sigma^2)ℓ(μ^​,σ^2). Use the natural logarithm and round each value to 4 decimal places. data always holds at least two different values.

Notice that σ^2\hat\sigma^2σ^2 is Chapter 4's population variance, applied to the sample. The same idea, maximising a log-likelihood, is what's going on underneath the loss functions you'll train models with later.

Examples

data = [2.0, 4.0, 6.0]
returns [4.0, 2.6667, -5.7281]
data = [21.5, 19.0, 20.5, 22.0, 18.5, 20.5]
returns [20.3333, 1.5556, -9.8391]

Hints

Solve it to unlock the solution

Once your code passes every test, a reference solution shows up here so you can compare it with yours.

solution.py
CtrlEnterto run