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):

  1. Construct the k x d weight matrix W and length-k bias vector b using only centroids and temperature (T > 0, with no dependence on x) so that for every vector x in R^d and every cluster i, the pre-activation score z_i = (W x + b)[i] equals -||x - c_i||^2 / (2 * T) + s(x), where s(x) = ||x||^2 / (2 * T) depends only on x and is identical across all k clusters.
  2. Apply Softmax to z so the shared shift s(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)) As T shrinks toward 0, probability mass concentrates onto the nearest cluster center(s). Evaluate Softmax in a numerically stable way so small positive values of T do not overflow math.exp.
  3. Return a dictionary with three keys:
    • "weights": k x d list of floats representing W.
    • "bias": length-k list of floats representing b.
    • "probabilities": length-k list of floats representing p.

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,000
  • 1 <= len(x) <= 500
  • Every center in centroids must have length len(x) (otherwise raise ValueError).
  • -10^4 <= centroids[i][j], x[j] <= 10^4
  • temperature is a floating-point number; raise ValueError if temperature <= 0. Positive temperatures down to 10^-4 must not cause OverflowError.
  • Floating-point outputs are compared with relative/absolute tolerance 10^-6.

Step-by-step walkthrough

  1. Understand the goal and output format

    In standard k-means clustering, we have k cluster centers (called centroids) c_1, c_2, ..., c_k, each a vector of d numbers. Given an input vector x of d numbers, 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 + b followed directly by a Softmax layer — controlled by a positive temperature T > 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": the k x d matrix W (a list of k rows, each of length d), - "bias": the length-k vector b, - "probabilities": the length-k Softmax output list p.

  2. Expand the squared Euclidean distance

    At first glance, ||x - c_i||^2 looks quadratic in x, whereas a linear layer W x + b can only compute dot products with x plus 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||^2
    

    Look closely at how each of the three pieces depends on x and on the cluster index i: 1. ||x||^2 depends on x, but it is the exact same number for every cluster i. 2. -2 * (c_i . x) is linear in x (a dot product between c_i and x). 3. ||c_i||^2 does not depend on x at all — it is a fixed constant for cluster i.

  3. Cancel `||x||^2` using Softmax shift invariance

    We want the Softmax input for cluster i to match -||x - c_i||^2 / (2T) up to a shared shift. Dividing our expanded formula by -2T flips 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 s
    

    Why can we drop -||x||^2 / (2T)? Because Softmax is shift-invariant: adding or subtracting the exact same number s from every logit multiplies both numerator and denominator by exp(-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 layer z_i = W[i] . x + b[i] with: - Row i of W: W[i] = c_i / T (the centroid matrix C scaled by 1 / T). - Entry i of b: b[i] = -||c_i||^2 / (2T).

    This also explains the geometric meaning of both parameters: W[i] . x measures alignment with centroid c_i via a dot product, while the negative bias b[i] subtracts half the centroid's squared length so a centroid far from the origin cannot win simply by having huge coordinates.

  4. Build the linear layer and compute logits

    We write two small helpers: build_linear_layer computes W and b directly from the centroids and T, and compute_logits evaluates z_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 logits
    
  5. Make Softmax numerically stable at tiny temperatures

    When T approaches 0 (for example T = 0.001), dividing by T can produce logits like 40,000. Calling math.exp(40000) directly raises OverflowError because e^40000 exceeds 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 calling math.exp. Now: - Every shifted exponent logit - max_logit is <= 0, so math.exp(...) never exceeds 1.0 (zero chance of overflow). - At least one cluster has logit - max_logit == 0, contributing exp(0) = 1.0, so exp_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 probabilities
    
  6. Trace Example 2 and Example 1 step by step

    Let's trace centroids = [[1, 0], [3, 4]] and x = [2, 3]. First check true squared distances: - To c_0 = [1, 0]: (2 - 1)^2 + (3 - 0)^2 = 10 - To c_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!)
    
  7. Assemble the complete solution

    Finally, we validate temperature > 0 and wire the helpers together inside kmeans_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). Building weights and bias visits each of the k * d centroid coordinates once, computing W x + b performs k dot products of length d (k * d multiplications and additions), and running stable_softmax scans the k logits three times in O(k) time.
  • Space: O(k * d). Returning the k x d weight matrix W requires k * d floats, while bias, logits, shifted_exps, and probabilities each store k floats (O(k) auxiliary space).

Edge cases

  • Single cluster (k = 1): Softmax over a single logit always shifts to exp(0) / exp(0) = 1.0, returning [1.0] regardless of x or T.
  • Equidistant centroids (ties): If x has the exact same distance to m nearest centroids, their logits are identical and Softmax splits the winning probability mass evenly (1 / m each as T -> 0).
  • Duplicate centroids: Identical centroids produce identical rows in W and identical entries in b, so they always share equal probabilities.
  • Tiny temperature (T = 0.001): Raw logits scale like 1 / T and can hit tens of thousands; subtracting max(logits) prevents math.exp overflow while distant clusters safely underflow (round smoothly down to 0.0).
  • Huge temperature (T = 10^6): Dividing by a huge T pushes all logits close to 0, so exp(z_i) approaches 1 for every cluster and the output flattens toward [1/k, ..., 1/k].
  • Non-positive temperature (T <= 0): T = 0 divides by zero and T < 0 inverts distances so the farthest centroid wins; raising ValueError guards against invalid calls.

Common mistakes

  • Omitting the bias vector b: Ranking by c_i . x alone breaks whenever centroids have different lengths. For c_0 = [1, 0], c_1 = [10, 0], and x = [2, 0], c_0 is much closer (distance^2 = 1 vs 64), yet c_1 . x = 20 beats c_0 . x = 2 without the -||c_i||^2 / (2T) penalty.
  • Trying to include ||x||^2 inside b: Neural network parameters W and b depend only on the model (centroids and T), never on the runtime input x. Rely on Softmax shift invariance to drop -||x||^2 / (2T).
  • Missing the factor of 2 or flipping signs: Because ||x - c_i||^2 has -2(c_i . x) in the middle, dividing by -2T cancels the -2 on W (c_i / T) while keeping / (2T) and the minus sign on b (-||c_i||^2 / (2T)).
  • Calling math.exp(z) without subtracting max(logits): Standard 64-bit math.exp overflows around z = 709.78, which happens easily whenever T is small.
  • Transposing W into d x k instead of k x d: In z = W x + b, W must have k rows of length d so multiplying by length-d vector x yields k cluster logits.

Alternative approaches

  • Vectorized numpy matrix multiply: For large batches of inputs X (shape N x d), computing W = C / T, b = -(C ** 2).sum(axis=1) / (2 * T), and Z = X @ W.T + b runs all N points against all k centroids in one hardware-accelerated matrix multiplication (GEMM), which is much faster on GPUs than computing pairwise N x k x d differences.
  • Direct distance Softmax (for testing): Computing softmax([-||x - c_i||^2 / (2T) for c_i in centroids]) skips W and b and 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 T shrinks the gaps between all logits toward 0, flattening the distribution so every cluster's probability moves closer to uniform 1 / k and entropy (a measure of how spread out or uncertain a probability distribution is) increases. Conversely, shrinking T -> 0 magnifies 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 variance T along 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 to 1 nor 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 whenever x is closer to the origin than to c_i. For example, with c_0 = [2, 0], c_1 = [4, 0], and x = [0, 0], both logits are negative (-2/T and -8/T), so ReLU clips every output to 0 and 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 / T and b_i = -||c_i||^2 / (2T) stay tied to the underlying centroid parameters C rather than drifting independently. If we minimize the soft k-means negative log-likelihood L(x) = -T * log(sum_j exp(-||x - c_j||^2 / (2T))), the gradient with respect to centroid c_i simplifies cleanly to -p_i * (x - c_i), so gradient descent updates each centroid via c_i <- c_i + lr * p_i * (x - c_i). Each centroid moves toward x in proportion to its Softmax responsibility p_i, and as T -> 0 (p becomes one-hot) this reduces to the classic online k-means update on the winning centroid.

Follow-up questions

Similar questions

More Sealth interview questions

All 3 Sealth questions →