Express Soft K-Means Assignment as a Single Linear Layer
Easy · Machine Learning · Machine Learning Engineer · Onsite
Problem Statement
Hard k-means clustering maps a d-dimensional feature vector x to whichever cluster center c_i (0 <= i < k) has the smallest squared Euclidean distance:
||x - c_i||^2 = sum_{j=0}^{d-1} (x[j] - c_i[j])^2
Implement kmeans_mlp_soft_assignment(centroids, x, temperature) to express a smooth, temperature-controlled version of this assignment step as a single affine neural layer z = W x + b followed directly by a Softmax activation (a network with zero hidden layers):
- Construct the
k x dweight matrixWand length-kbias vectorbusing onlycentroidsandtemperature(T > 0, with no dependence onx) so that for every vectorxinR^dand every clusteri, the pre-activation scorez_i = (W x + b)[i]equals-||x - c_i||^2 / (2 * T) + s(x), wheres(x) = ||x||^2 / (2 * T)depends only onxand is identical across allkclusters. - Apply Softmax to
zso the shared shifts(x)cancels out and the resulting probabilities equal:text p_i = exp(-||x - c_i||^2 / (2 * T)) / sum_{m=0}^{k-1} exp(-||x - c_m||^2 / (2 * T))AsTshrinks toward0, probability mass concentrates onto the nearest cluster center(s). Evaluate Softmax in a numerically stable way so small positive values ofTdo not overflowmath.exp. - Return a dictionary with three keys:
"weights":k x dlist of floats representingW."bias": length-klist of floats representingb."probabilities": length-klist of floats representingp.
Raise ValueError if temperature <= 0 or if any center in centroids does not have the same length as x.
Examples
Example 1
Input:
centroids = [[1, 0], [3, 4]]
x = [2, 3]
temperature = 0.25
Output:
{
"weights": [[4.0, 0.0], [12.0, 16.0]],
"bias": [-2.0, -50.0],
"probabilities": [1.12535162055095e-07, 0.9999998874648379]
}
Explanation: x = [2, 3] has squared distance (2 - 1)^2 + (3 - 0)^2 = 10 to c_0 = [1, 0] and (2 - 3)^2 + (3 - 4)^2 = 2 to c_1 = [3, 4]. Scaling each center by 1 / T = 4 gives W = [[4.0, 0.0], [12.0, 16.0]], and -||c_i||^2 / (2 * T) gives b = [-2.0, -50.0]. The logits are z = [6.0, 22.0] (a gap of 16.0), so at low temperature T = 0.25 nearly 100% of the probability goes to cluster 1.
Example 2
Input:
centroids = [[1, 0], [3, 4]]
x = [2, 3]
temperature = 4.0
Output:
{
"weights": [[0.25, 0.0], [0.75, 1.0]],
"bias": [-0.125, -3.125],
"probabilities": [0.2689414213699951, 0.7310585786300049]
}
Explanation: With the same points at a higher temperature T = 4.0, the linear parameters shrink to W = [[0.25, 0.0], [0.75, 1.0]] and b = [-0.125, -3.125]. The logits z = [0.375, 1.375] differ by 1.0, yielding a softer [0.2689, 0.7311] split that still favors the nearer center c_1.
Example 3
Input:
centroids = [[-2, 0], [1, 2], [4, -2]]
x = [1, 0]
temperature = 0.5
Output:
{
"weights": [[-4.0, 0.0], [2.0, 4.0], [8.0, -4.0]],
"bias": [-4.0, -5.0, -20.0],
"probabilities": [0.0066920305894733485, 0.9931854005948175, 0.00012256881570915678]
}
Explanation: Squared distances from x = [1, 0] to the three centers are 9, 4, and 13. At T = 0.5 (2 * T = 1.0), W x + b produces logits [-8.0, -3.0, -12.0], giving over 99.3% probability to the closest center c_1 = [1, 2].
Constraints
1 <= len(centroids) <= 1,0001 <= len(x) <= 500- Every center in
centroidsmust have lengthlen(x)(otherwise raiseValueError). -10^4 <= centroids[i][j], x[j] <= 10^4temperatureis a floating-point number; raiseValueErroriftemperature <= 0. Positive temperatures down to10^-4must not causeOverflowError.- Floating-point outputs are compared with relative/absolute tolerance
10^-6.
Step-by-step walkthrough
Understand the goal and output format
In standard k-means clustering, we have
kcluster centers (called centroids)c_1, c_2, ..., c_k, each a vector ofdnumbers. Given an input vectorxofdnumbers, hard k-means picks whichever centroid minimizes the squared Euclidean distance||x - c_i||^2(the sum of squared coordinate differences).Our goal is to compute a smooth, probabilistic version of that assignment using a single-layer neural network — a linear layer
z = W x + bfollowed directly by a Softmax layer — controlled by a positive temperatureT > 0:Input x (length d) | v +-------------------------------+ | Linear layer: z = W x + b | W has shape (k x d), b has length k +-------------------------------+ | logits z = [z_1, ..., z_k] v +-------------------------------+ | Softmax: p_i = exp(z_i) / sum | p has length k, entries >= 0, sum(p) = 1 +-------------------------------+ | v Cluster probabilities [p_1, ..., p_k] (concentrates on nearest c_i as T -> 0)The function returns a dictionary with three keys: -
"weights": thek x dmatrixW(a list ofkrows, each of lengthd), -"bias": the length-kvectorb, -"probabilities": the length-kSoftmax output listp.Expand the squared Euclidean distance
At first glance,
||x - c_i||^2looks quadratic inx, whereas a linear layerW x + bcan only compute dot products withxplus constants. Expanding the squared distance reveals why a linear layer is actually enough:||x - c_i||^2 = sum over j of (x[j] - c_i[j])^2 = sum over j of (x[j]^2 - 2 * c_i[j] * x[j] + c_i[j]^2) = ||x||^2 - 2 * (c_i . x) + ||c_i||^2Look closely at how each of the three pieces depends on
xand on the cluster indexi: 1.||x||^2depends onx, but it is the exact same number for every clusteri. 2.-2 * (c_i . x)is linear inx(a dot product betweenc_iandx). 3.||c_i||^2does not depend onxat all — it is a fixed constant for clusteri.Cancel `||x||^2` using Softmax shift invariance
We want the Softmax input for cluster
ito match-||x - c_i||^2 / (2T)up to a shared shift. Dividing our expanded formula by-2Tflips every sign:-||x - c_i||^2 / (2T) = (c_i / T) . x - ||c_i||^2 / (2T) - ||x||^2 / (2T) \___________/ \______________/ \____________/ W[i] . x + b[i] - shared shift sWhy can we drop
-||x||^2 / (2T)? Because Softmax is shift-invariant: adding or subtracting the exact same numbersfrom every logit multiplies both numerator and denominator byexp(-s), which cancels completely:exp(z_i - s) / sum_j exp(z_j - s) = (exp(-s) * exp(z_i)) / (exp(-s) * sum_j exp(z_j)) = exp(z_i) / sum_j exp(z_j)Dropping the shared
-||x||^2 / (2T)term leaves a pure linear layerz_i = W[i] . x + b[i]with: - RowiofW:W[i] = c_i / T(the centroid matrixCscaled by1 / T). - Entryiofb:b[i] = -||c_i||^2 / (2T).This also explains the geometric meaning of both parameters:
W[i] . xmeasures alignment with centroidc_ivia a dot product, while the negative biasb[i]subtracts half the centroid's squared length so a centroid far from the origin cannot win simply by having huge coordinates.Build the linear layer and compute logits
We write two small helpers:
build_linear_layercomputesWandbdirectly from the centroids andT, andcompute_logitsevaluatesz_i = W[i] . x + b[i]for each cluster.from typing import List, Tuple def build_linear_layer( centroids: List[List[float]], dim: int, temperature: float ) -> Tuple[List[List[float]], List[float]]: """Construct W (k x d) and b (length k) from cluster centroids and temperature T.""" # weights: k x d matrix where row i is centroid c_i scaled by 1 / T weights: List[List[float]] = [] # bias: length-k list where entry i is -||c_i||^2 / (2 * T) bias: List[float] = [] for centroid in centroids: if len(centroid) != dim: raise ValueError("every centroid must have the same dimension as x") weight_row: List[float] = [] squared_norm = 0.0 for coord in centroid: weight_row.append(coord / temperature) squared_norm += coord * coord weights.append(weight_row) # Penalize half the squared length of c_i so longer centroids do not win by norm alone. bias.append(-squared_norm / (2.0 * temperature)) return weights, bias def compute_logits( weights: List[List[float]], bias: List[float], x: List[float] ) -> List[float]: """Compute linear layer outputs z = W x + b (one logit per cluster).""" # logits: length-k list where logits[i] = -||x - c_i||^2 / (2T) + ||x||^2 / (2T) logits: List[float] = [] for i in range(len(weights)): dot_product = 0.0 for j in range(len(x)): dot_product += weights[i][j] * x[j] logits.append(dot_product + bias[i]) return logitsMake Softmax numerically stable at tiny temperatures
When
Tapproaches0(for exampleT = 0.001), dividing byTcan produce logits like40,000. Callingmath.exp(40000)directly raisesOverflowErrorbecausee^40000exceeds floating-point limits (~1.8 * 10^308).We reuse Softmax's shift invariance one more time: subtract
max_logit = max(logits)from every logit before callingmath.exp. Now: - Every shifted exponentlogit - max_logitis<= 0, somath.exp(...)never exceeds1.0(zero chance of overflow). - At least one cluster haslogit - max_logit == 0, contributingexp(0) = 1.0, soexp_sum >= 1.0(zero chance of dividing by zero).import math from typing import List def stable_softmax(logits: List[float]) -> List[float]: """Convert raw logits into a probability distribution without exp() overflow.""" if not logits: return [] # Subtracting max_logit makes the largest exponent 0 (exp(0) = 1.0), which prevents # OverflowError at tiny temperatures while canceling out identically in Softmax. max_logit = max(logits) shifted_exps: List[float] = [] exp_sum = 0.0 for logit in logits: exp_val = math.exp(logit - max_logit) shifted_exps.append(exp_val) exp_sum += exp_val probabilities: List[float] = [] for exp_val in shifted_exps: probabilities.append(exp_val / exp_sum) return probabilitiesTrace Example 2 and Example 1 step by step
Let's trace
centroids = [[1, 0], [3, 4]]andx = [2, 3]. First check true squared distances: - Toc_0 = [1, 0]:(2 - 1)^2 + (3 - 0)^2 = 10- Toc_1 = [3, 4]:(2 - 3)^2 + (3 - 4)^2 = 2(closer!)Case A: T = 4.0 (Example 2) W[0] = [1/4, 0/4] = [0.25, 0.0], b[0] = -(1 + 0) / 8 = -0.125 W[1] = [3/4, 4/4] = [0.75, 1.0], b[1] = -(9 + 16) / 8 = -3.125 z[0] = 0.25*2 + 0.0*3 - 0.125 = 0.375 z[1] = 0.75*2 + 1.0*3 - 3.125 = 1.375 (logit gap z[1] - z[0] = 1.0, matching -(2 - 10)/(2*4) = 1.0) max_logit = 1.375 -> shifted = [-1.0, 0.0] -> exps = [exp(-1), 1.0] probabilities = [0.2689414..., 0.7310585...] Case B: T = 0.25 (Example 1) W[0] = [4.0, 0.0], b[0] = -2.0 W[1] = [12.0, 16.0], b[1] = -50.0 z[0] = 4*2 + 0*3 - 2 = 6.0, z[1] = 12*2 + 16*3 - 50 = 22.0 (16x smaller T -> 16x larger logit gap!) max_logit = 22.0 -> shifted = [-16.0, 0.0] -> exps = [exp(-16), 1.0] probabilities = [1.12535e-7, 0.999999887...] (almost 100% on nearest centroid c_1!)Assemble the complete solution
Finally, we validate
temperature > 0and wire the helpers together insidekmeans_mlp_soft_assignment.from typing import Any, Dict, List, Optional, Set, Tuple import math def build_linear_layer( centroids: List[List[float]], dim: int, temperature: float ) -> Tuple[List[List[float]], List[float]]: """Construct W (k x d) and b (length k) from cluster centroids and temperature T.""" # weights: k x d matrix where row i is centroid c_i scaled by 1 / T weights: List[List[float]] = [] # bias: length-k list where entry i is -||c_i||^2 / (2 * T) bias: List[float] = [] for centroid in centroids: if len(centroid) != dim: raise ValueError("every centroid must have the same dimension as x") weight_row: List[float] = [] squared_norm = 0.0 for coord in centroid: weight_row.append(coord / temperature) squared_norm += coord * coord weights.append(weight_row) # Penalize half the squared length of c_i so longer centroids do not win by norm alone. bias.append(-squared_norm / (2.0 * temperature)) return weights, bias def compute_logits( weights: List[List[float]], bias: List[float], x: List[float] ) -> List[float]: """Compute linear layer outputs z = W x + b (one logit per cluster).""" # logits: length-k list where logits[i] = -||x - c_i||^2 / (2T) + ||x||^2 / (2T) logits: List[float] = [] for i in range(len(weights)): dot_product = 0.0 for j in range(len(x)): dot_product += weights[i][j] * x[j] logits.append(dot_product + bias[i]) return logits def stable_softmax(logits: List[float]) -> List[float]: """Convert raw logits into a probability distribution without exp() overflow.""" if not logits: return [] # Subtracting max_logit makes the largest exponent 0 (exp(0) = 1.0), which prevents # OverflowError at tiny temperatures while canceling out identically in Softmax. max_logit = max(logits) shifted_exps: List[float] = [] exp_sum = 0.0 for logit in logits: exp_val = math.exp(logit - max_logit) shifted_exps.append(exp_val) exp_sum += exp_val probabilities: List[float] = [] for exp_val in shifted_exps: probabilities.append(exp_val / exp_sum) return probabilities def kmeans_mlp_soft_assignment( centroids: List[List[float]], x: List[float], temperature: float ) -> Dict[str, object]: # Temperature T <= 0 would either divide by zero or invert nearest-centroid order. if temperature <= 0: raise ValueError("temperature must be positive") # Phase 1: Map centroids into linear layer parameters W = C / T and b_i = -||c_i||^2 / (2T). weights, bias = build_linear_layer(centroids, len(x), temperature) # Phase 2: Run the forward pass z = W x + b followed by numerically stable Softmax. logits = compute_logits(weights, bias, x) probabilities = stable_softmax(logits) return { "weights": weights, "bias": bias, "probabilities": probabilities, }✅ Submit now — all tests should pass.
Intuition & how it works
Think of a linear neural network layer as a row of template detectors: each neuron stores a cluster center (called a centroid, a point representing the middle of a cluster) and scores an input x by taking a dot product (multiplying matching coordinates and adding them up). A raw dot product alone is unfair because a centroid with huge coordinates produces huge dot products even when it is far away — so we attach a negative bias (a per-neuron constant offset) equal to half the centroid's squared length to level the playing field. We then pass those scores (logits, the raw unnormalized scores coming out of a linear layer) into Softmax (a function exp(z_i) / sum_j exp(z_j) that turns arbitrary scores into positive probabilities summing to 1), scaled by a temperature T (a positive dial controlling how sharply probabilities concentrate on the top score).
Why does a naive translation fail? A single linear layer inside an MLP (multilayer perceptron, a feedforward neural network made of linear layers and nonlinear activations) can only compute linear expressions W x + b, so it cannot compute the quadratic term ||x||^2 inside the squared Euclidean distance ||x - c_i||^2 = ||x||^2 - 2(c_i . x) + ||c_i||^2 (where ||v||^2 is the sum of squared coordinates of v). Trying to bake ||x||^2 into b is impossible because b must be fixed before seeing x, while dropping the bias b altogether picks distant centroids with large norms over nearby ones. The key insight is shift invariance (adding the exact same number to every input of Softmax leaves its output probabilities completely unchanged): because -||x||^2 / (2T) is identical across all k clusters, Softmax cancels it out automatically!
Here is a concrete walkthrough with two centroids c_0 = [1, 0] and c_1 = [3, 4], input x = [2, 3], and temperature T = 4.0:
1. Build linear layer parameters (W[i] = c_i / T, b[i] = -||c_i||^2 / (2T)):
Cluster 0: W[0] = [0.25, 0.0], b[0] = -(1^2 + 0^2) / 8 = -0.125
Cluster 1: W[1] = [0.75, 1.0], b[1] = -(3^2 + 4^2) / 8 = -3.125
2. Compute logits z = W x + b:
z[0] = (0.25*2 + 0.0*3) - 0.125 = 0.375
z[1] = (0.75*2 + 1.0*3) - 3.125 = 1.375
(Check: -||x - c_0||^2 / 8 = -1.25 and -||x - c_1||^2 / 8 = -0.25; both have gap +1.0!)
3. Apply stable Softmax (subtract max_logit = 1.375):
exps = [exp(0.375 - 1.375), exp(1.375 - 1.375)] = [exp(-1), 1.0] = [0.3679, 1.0]
probabilities = [0.3679 / 1.3679, 1.0 / 1.3679] = [0.2689, 0.7311]
Cluster 1 is much closer (distance^2 = 2 vs 10), so it receives 73.1% of the probability at T = 4.0 — and 99.999989% when T drops to 0.25.
Complexity
Let k be the number of centroids and d be the dimension (length) of x and each centroid.
- Time:
O(k * d). Buildingweightsandbiasvisits each of thek * dcentroid coordinates once, computingW x + bperformskdot products of lengthd(k * dmultiplications and additions), and runningstable_softmaxscans theklogits three times inO(k)time. - Space:
O(k * d). Returning thek x dweight matrixWrequiresk * dfloats, whilebias,logits,shifted_exps, andprobabilitieseach storekfloats (O(k)auxiliary space).
Edge cases
- Single cluster (
k = 1): Softmax over a single logit always shifts toexp(0) / exp(0) = 1.0, returning[1.0]regardless ofxorT. - Equidistant centroids (ties): If
xhas the exact same distance tomnearest centroids, their logits are identical and Softmax splits the winning probability mass evenly (1 / meach asT -> 0). - Duplicate centroids: Identical centroids produce identical rows in
Wand identical entries inb, so they always share equal probabilities. - Tiny temperature (
T = 0.001): Raw logits scale like1 / Tand can hit tens of thousands; subtractingmax(logits)preventsmath.expoverflow while distant clusters safely underflow (round smoothly down to0.0). - Huge temperature (
T = 10^6): Dividing by a hugeTpushes all logits close to0, soexp(z_i)approaches1for every cluster and the output flattens toward[1/k, ..., 1/k]. - Non-positive temperature (
T <= 0):T = 0divides by zero andT < 0inverts distances so the farthest centroid wins; raisingValueErrorguards against invalid calls.
Common mistakes
- Omitting the bias vector
b: Ranking byc_i . xalone breaks whenever centroids have different lengths. Forc_0 = [1, 0],c_1 = [10, 0], andx = [2, 0],c_0is much closer (distance^2 = 1vs64), yetc_1 . x = 20beatsc_0 . x = 2without the-||c_i||^2 / (2T)penalty. - Trying to include
||x||^2insideb: Neural network parametersWandbdepend only on the model (centroids andT), never on the runtime inputx. Rely on Softmax shift invariance to drop-||x||^2 / (2T). - Missing the factor of
2or flipping signs: Because||x - c_i||^2has-2(c_i . x)in the middle, dividing by-2Tcancels the-2onW(c_i / T) while keeping/ (2T)and the minus sign onb(-||c_i||^2 / (2T)). - Calling
math.exp(z)without subtractingmax(logits): Standard 64-bitmath.expoverflows aroundz = 709.78, which happens easily wheneverTis small. - Transposing
Wintod x kinstead ofk x d: Inz = W x + b,Wmust havekrows of lengthdso multiplying by length-dvectorxyieldskcluster logits.
Alternative approaches
- Vectorized
numpymatrix multiply: For large batches of inputsX(shapeN x d), computingW = C / T,b = -(C ** 2).sum(axis=1) / (2 * T), andZ = X @ W.T + bruns allNpoints against allkcentroids in one hardware-accelerated matrix multiplication (GEMM), which is much faster on GPUs than computing pairwiseN x k x ddifferences. - Direct distance Softmax (for testing): Computing
softmax([-||x - c_i||^2 / (2T) for c_i in centroids])skipsWandband gives the exact same probabilities, making it an ideal reference oracle for unit tests.
Follow-up questions
- What happens to the predicted cluster probabilities as you raise or lower the temperature parameter? Dividing by a larger
Tshrinks the gaps between all logits toward0, flattening the distribution so every cluster's probability moves closer to uniform1 / kand entropy (a measure of how spread out or uncertain a probability distribution is) increases. Conversely, shrinkingT -> 0magnifies logit gaps toward infinity, concentrating probability mass into a hard one-hot assignment on the nearest centroid. Statistically, these probabilities are the exact cluster responsibilities of an equal-weight Gaussian Mixture Model (a probabilistic model where each cluster generates points from a bell-curve distribution) with varianceTalong every coordinate. - Why does swapping Softmax for a ReLU activation break the geometric meaning of the cluster scores? ReLU (Rectified Linear Unit, defined as
max(0, z)) outputs independent non-negative numbers that neither sum to1nor form a probability distribution. Worse, ReLU is not shift-invariant, so dropping-||x||^2 / (2T)changes which neurons fire:z_i = (||x||^2 - ||x - c_i||^2) / (2T)is negative wheneverxis closer to the origin than toc_i. For example, withc_0 = [2, 0],c_1 = [4, 0], andx = [0, 0], both logits are negative (-2/Tand-8/T), so ReLU clips every output to0and completely loses track of which centroid is nearest! - How could you train the cluster centers incrementally from streaming data via gradient descent? You can use online learning (updating parameters incrementally after each data point or mini-batch) and backpropagation (computing gradients of a loss function via the chain rule), provided
W = C / Tandb_i = -||c_i||^2 / (2T)stay tied to the underlying centroid parametersCrather than drifting independently. If we minimize the soft k-means negative log-likelihoodL(x) = -T * log(sum_j exp(-||x - c_j||^2 / (2T))), the gradient with respect to centroidc_isimplifies cleanly to-p_i * (x - c_i), so gradient descent updates each centroid viac_i <- c_i + lr * p_i * (x - c_i). Each centroid moves towardxin proportion to its Softmax responsibilityp_i, and asT -> 0(pbecomes one-hot) this reduces to the classic online k-means update on the winning centroid.
Follow-up questions
- What happens to the predicted cluster probabilities as you raise or lower the temperature parameter?
- Why does swapping Softmax for a ReLU activation break the geometric meaning of the cluster scores?
- How could you train the cluster centers incrementally from streaming data via gradient descent?
Similar questions
- Decode Delimited and Ambiguous Morse Strings
- Single-Cluster K-Means Centroid
- Low-Latency Tree Ensemble Inference
- Select Score Cutoff for Target Precision
- Payment Fraud Detection Under Class Imbalance and Drift
- Diagnosing and Fixing Overfitting in Supervised Learning