#337 · Statistics · Medium
⊣ Solve on deep-ml.comImplement Maximum Likelihood Estimation (MLE) for the parameters of a Gaussian (normal) distribution. Given observed data, estimate the mean and variance that maximize the likelihood of observing the data.
from typing import List, Dict
def gaussian_mle(data: List[float]) -> Dict[str, float]:
n = len(data)
if n == 0:
raise ValueError("Data cannot be empty")
# MLE for mean: sample mean
mean = sum(data) / n
# MLE for variance: average squared deviation (not Bessel-corrected)
variance = sum((x - mean) ** 2 for x in data) / n
std_dev = variance ** 0.5
return {
"mean": round(mean, 4),
"variance": round(variance, 4),
"std_dev": round(std_dev, 4)
}
def gaussian_log_likelihood(
data: List[float],
mean: float,
variance: float
) -> float:
import math
if variance <= 0:
raise ValueError("Variance must be positive")
n = len(data)
ll = -n / 2 * math.log(2 * math.pi * variance)
ll -= sum((x - mean) ** 2 for x in data) / (2 * variance)
return round(ll, 4)