A mixture of linear experts models a scalar target with K linear-Gaussian experts and a softmax gate:
p(y∣x,z=k)=N(y∣wk⊤x,σk2),p(z=k∣x)=softmaxk(Vx)
Fit it with EM. Implement fit_mole(X, y, V0, W0, sigma2_0, n_iter, gate_steps, gate_lr):
X: inputs of shape (N, D) (the caller includes any bias column); y: shape (N,).
V0, W0: initial gate and expert weights, both (K, D) (row k is vk or wk); sigma2_0: initial variances, shape (K,).
Each of the n_iter iterations does, in order:
- E-step: responsibilities rnk∝πnkN(yn∣wk⊤xn,σk2) with πnk=softmaxk(Vxn), normalised over k.
- Experts: for every k, wk solves the weighted least-squares system (X⊤RkX+10−8I)wk=X⊤Rky with Rk=diag(r1k,…,rNk); then σk2=∑nrnk(yn−wk⊤xn)2/∑nrnk using the new wk, floored at 10−6.
- Gate:
gate_steps steps of gradient ascent on N1∑n,krnklogπnk, whose gradient with respect to V is N1(R−Π)⊤X (with R and Π the N×K matrices of rnk and πnk under the current V); each step is V←V+gate_lr×gradient, recomputing Π before every step.
Return (V, W, sigma2, trace) where trace holds the mean log-likelihood N1∑nlog∑kπnkN(yn∣wk⊤xn,σk2) evaluated before the first iteration and after each iteration (length n_iter + 1). Compute it with log-sum-exp.