The nearest class mean (NCM) classifier assigns to the class whose mean is closest. With a learned linear map (shape ) the squared distance is , and the class posterior is a softmax over negative half distances:
Implement:
ncm_proba(X, means, W): X is (N, D), means is (C, D), W is (K, D). Return the (N, C) posterior matrix (use a stable softmax).ncm_nll_grad(X, y, means, W): return (nll, grad) where nll is the mean negative log-likelihood as a float and grad is its gradient with respect to W, same shape as W. The means are fixed (not learned).ncm_fit(X, y, means, W0, lr, n_iter): plain gradient descent on the mean NLL starting from W0 (do not modify it in place): n_iter steps of . Return (W, losses) where losses lists the mean NLL before each step (length n_iter).Labels are integers .