Implement EM for Full-Covariance Gaussian Mixtures

Quick Overview

Implement expectation maximization for a Gaussian mixture with full covariance matrices in NumPy, as separate E-step, M-step and fitting functions with an exact initialization and stopping rule. It tests numerically stable density evaluation, covariance regularization and careful control of the EM loop.

Implement EM for Full-Covariance Gaussian Mixtures

Role: Machine Learning Engineer

Category: Machine Learning

Difficulty: hard

Interview Round: Other

Given data `X` of shape `(n, d)` and initial means `means_init` of shape `(k, d)`, fit a `k`-component Gaussian mixture with full covariance matrices using expectation maximization (EM). Implement `e_step`, `m_step` and `fit_gmm` with these signatures: ```python def e_step(X, weights, means, covariances): """Return (resp, ll).""" def m_step(X, resp, reg_covar): """Return (weights, means, covariances).""" def fit_gmm(X, means_init, reg_covar=1e-6, tol=1e-3, max_iter=100): """Return the result dictionary described below.""" ``` The functions must behave as follows. - `e_step` returns `(resp, ll)`. `resp` is the `(n, k)` matrix of posterior probabilities of each component for each point, and `ll` is a Python `float`: the mean over samples of the log mixture density, $\frac{1}{n}\sum_{i=1}^{n} \log \sum_{j=1}^{k} w_j \, \mathcal{N}(x_i \mid \mu_j, \Sigma_j)$, computed in a numerically stable way. - `m_step` returns `(weights, means, covariances)`. With $N_j = \sum_i r_{ij}$, the weights are $w_j = N_j / n$, the means are $\mu_j = \frac{1}{N_j}\sum_i r_{ij} x_i$, and the covariances are $\Sigma_j = \frac{1}{N_j}\sum_i r_{ij}(x_i - \mu_j)(x_i - \mu_j)^\top + \lambda I$, where $\lambda$ is `reg_covar`. - `fit_gmm` initializes by assigning each point to its nearest row of `means_init` (squared Euclidean distance, ties go to the lowest index) and calling `m_step` on the resulting one-hot responsibilities. - Iterations are numbered from $t = 1$. In each iteration, run `e_step` and record `ll`. If $t \ge 2$ and $|\ell_t - \ell_{t-1}| < \mathrm{tol}$, stop with `converged=True`. Otherwise, if $t$ equals `max_iter`, stop with `converged=False`. Otherwise run `m_step` and start the next iteration. - The returned parameters are the ones used in the final E-step. No M-step runs after the loop stops. `fit_gmm` returns this dictionary (array shapes in the comments): ```python { "weights": (k,), # sums to 1 "means": (k, d), "covariances": (k, d, d), "resp": (n, k), # from the final E-step "labels": (n,), # argmax of resp per row "log_likelihoods": (n_iter,), # np.ndarray, one mean ll per E-step "converged": bool, "n_iter": int, # number of E-steps run } ``` ```hint Where underflow hides In many dimensions, or for a point far from every component, a Gaussian density can round to exactly 0 in float64. Decide which quantities you can keep as logarithms until the last moment. ``` ```hint Avoid forming inverses Look for one factorization of each covariance matrix that gives you both the log-determinant and the Mahalanobis distance. ``` ```hint Loop order Trace which parameters you hold at the moment the loop stops. The returned `resp`, the parameters and the last log-likelihood must all come from the same E-step. ``` ### Constraints & Assumptions - `X` is a float array of shape `(n, d)` and `means_init` has shape `(k, d)`. - Weights, means and covariances have shapes `(k,)`, `(k, d)` and `(k, d, d)`. - NumPy and SciPy are available. - Choosing `k` and random initialization are out of scope. The initial means are given. ### What a Strong Answer Covers - Component log-densities computed without explicit inverses or determinants, with responsibilities and the mean log-likelihood normalized through a log-sum-exp. - M-step updates for weights, means and responsibility-weighted covariances that match the formulas, with `reg_covar` added to every covariance, including in the initial M-step. - Initialization from hard nearest-mean assignments that follows the lowest-index tie rule. - A loop whose stopping checks run before the M-step, so the returned parameters, `resp`, `labels`, `n_iter` and the history agree with each other. - Edge cases such as an initial mean that no point is nearest to, and the cost of one iteration. ### Follow-up Questions - Why can't you compute the Gaussian densities directly and then normalize them? - What does `reg_covar` protect against, and what are its side effects? - How would you choose the number of components and make the fit less sensitive to initialization?

Overview: Implement expectation maximization for a Gaussian mixture with full covariance matrices in NumPy, as separate E-step, M-step and fitting functions with an exact initialization and stopping rule. It tests numerically stable density evaluation, covariance regularization and careful control of the EM loop.

PracHub logo
General
Nov 24, 2026
hardMachine Learning EngineerOtherMachine Learning
0
0

Given data X of shape (n, d) and initial means means_init of shape (k, d), fit a k-component Gaussian mixture with full covariance matrices using expectation maximization (EM). Implement e_step, m_step and fit_gmm with these signatures:

def e_step(X, weights, means, covariances):
    """Return (resp, ll)."""

def m_step(X, resp, reg_covar):
    """Return (weights, means, covariances)."""

def fit_gmm(X, means_init, reg_covar=1e-6, tol=1e-3, max_iter=100):
    """Return the result dictionary described below."""

The functions must behave as follows.

  • e_step returns (resp, ll) . resp is the (n, k) matrix of posterior probabilities of each component for each point, and ll is a Python float : the mean over samples of the log mixture density, 1n∑i=1nlog⁡∑j=1kwj N(xi∣μj,Σj)\frac{1}{n}\sum_{i=1}^{n} \log \sum_{j=1}^{k} w_j \, \mathcal{N}(x_i \mid \mu_j, \Sigma_j) , computed in a numerically stable way.
  • m_step returns (weights, means, covariances) . With Nj=∑irijN_j = \sum_i r_{ij} , the weights are wj=Nj/nw_j = N_j / n , the means are μj=1Nj∑irijxi\mu_j = \frac{1}{N_j}\sum_i r_{ij} x_i , and the covariances are Σj=1Nj∑irij(xi−μj)(xi−μj)⊤+λI\Sigma_j = \frac{1}{N_j}\sum_i r_{ij}(x_i - \mu_j)(x_i - \mu_j)^\top + \lambda I , where λ\lambda is reg_covar .
  • fit_gmm initializes by assigning each point to its nearest row of means_init (squared Euclidean distance, ties go to the lowest index) and calling m_step on the resulting one-hot responsibilities.
  • Iterations are numbered from t=1t = 1 . In each iteration, run e_step and record ll . If t≥2t \ge 2 and ∣ℓt−ℓt−1∣<tol|\ell_t - \ell_{t-1}| < \mathrm{tol} , stop with converged=True . Otherwise, if tt equals max_iter , stop with converged=False . Otherwise run m_step and start the next iteration.
  • The returned parameters are the ones used in the final E-step. No M-step runs after the loop stops.

fit_gmm returns this dictionary (array shapes in the comments):

{
    "weights": (k,),               # sums to 1
    "means": (k, d),
    "covariances": (k, d, d),
    "resp": (n, k),                # from the final E-step
    "labels": (n,),                # argmax of resp per row
    "log_likelihoods": (n_iter,),  # np.ndarray, one mean ll per E-step
    "converged": bool,
    "n_iter": int,                 # number of E-steps run
}

Constraints & Assumptions

  • X is a float array of shape (n, d) and means_init has shape (k, d) .
  • Weights, means and covariances have shapes (k,) , (k, d) and (k, d, d) .
  • NumPy and SciPy are available.
  • Choosing k and random initialization are out of scope. The initial means are given.

What a Strong Answer Covers Guidance

  • Component log-densities computed without explicit inverses or determinants, with responsibilities and the mean log-likelihood normalized through a log-sum-exp.
  • M-step updates for weights, means and responsibility-weighted covariances that match the formulas, with reg_covar added to every covariance, including in the initial M-step.
  • Initialization from hard nearest-mean assignments that follows the lowest-index tie rule.
  • A loop whose stopping checks run before the M-step, so the returned parameters, resp , labels , n_iter and the history agree with each other.
  • Edge cases such as an initial mean that no point is nearest to, and the cost of one iteration.

Follow-up Questions Guidance

  • Why can't you compute the Gaussian densities directly and then normalize them?
  • What does reg_covar protect against, and what are its side effects?
  • How would you choose the number of components and make the fit less sensitive to initialization?