Neural Network Implementation of Centroid-Based Classification
Arrays & HashingAuto-graded · 20 test casesLast updated
Derives the weight matrix and bias vector of a single-layer network that performs soft assignment to cluster centers using squared distance.
Neural Network Implementation of Centroid-Based Classification
You are given a collection of cluster centers (centroids) in multi-dimensional space. Your goal is to construct a single-layer neural network that assigns an input point to these centroids based on squared Euclidean distance.
Specifically, implement a function that builds the parameters of a linear transformation followed by softmax activation. The network should output a probability distribution where points closer to a centroid receive higher probability, controlled by a temperature parameter.
Task
Given:
- A list of
centroids, where each centroid is a list of floats representing coordinates in d-dimensional space - An input point
xas a list of floats - A
temperatureparameter (a positive float)
Compute and return a dictionary containing:
"weights": A weight matrix represented as a list of lists, where each row corresponds to one centroid"bias": A bias vector as a list of floats, one entry per centroid"probabilities": The softmax output as a list of floats summing to 1.0
The network parameters must satisfy: for each centroid index i, the logit (pre-softmax value) equals -||x - centroid_i||² / (2 * temperature) plus any constant that depends only on x (not on i).
Mathematical Background
The squared Euclidean distance between point x and centroid c_i expands as:
||x - c_i||² = ||x||² - 2·(x·c_i) + ||c_i||²
Since softmax probabilities are unchanged when the same constant is added to all logits, the ||x||² term can be ignored. The remaining terms should be computed by your linear layer.
Constraints
- 1 ≤ number of centroids ≤ 100
- 1 ≤ dimension d ≤ 100
- All coordinate values are in the range [-1000, 1000]
- 0.01 ≤ temperature ≤ 100
- Use numerically stable softmax (subtract maximum logit before exponentiating)
Examples
Example 1
Input: compute_soft_centroid_assignment([[0, 0], [2, 2]], [1, 2], 0.1)
Output: {'weights': [[0, 0], [20, 20]], 'bias': [0, -40], 'probabilities': [2.0611536181902033e-9, 0.9999999979388463]}
Example 2
Input: compute_soft_centroid_assignment([[0, 0], [2, 2]], [1, 2], 1)
Output: {'weights': [[0, 0], [2, 2]], 'bias': [0, -4], 'probabilities': [0.11920292202211755, 0.8807970779778823]}
Example 3
Input: compute_soft_centroid_assignment([[1, -1], [4, 2], [-2, 3]], [0, 0], 0.5)
Output: {'weights': [[2, -2], [8, 4], [-4, 6]], 'bias': [-2, -20, -13], 'probabilities': [0.999983283348681, 1.5229725150451643e-8, 0.000016701421593737116]}
Hints
Hint 1
The dot product x·c_i appears when expanding the squared distance formula and is the only term linear in x
Hint 2
Softmax is shift-invariant: adding the same value to all logits doesn't change the output probabilities
Hint 3
The bias term must compensate for differences in centroid magnitudes to ensure distance-based assignment
Worked solution
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Approach
The key insight is recognizing that nearest-centroid assignment can be reformulated as a linear classifier followed by softmax.
Start by expanding the squared Euclidean distance:
||x - c_i||² = ||x||² - 2(x · c_i) + ||c_i||²
Dividing by -2T and rearranging:
-||x - c_i||²/(2T) = -||x||²/(2T) + (c_i · x)/T - ||c_i||²/(2T)
The first term depends only on x, not on which centroid we're considering. Since softmax is shift-invariant (adding the same constant to all inputs doesn't change the output), we can drop this term entirely.
This leaves us with two components:
- A linear term
(c_i · x)/Twhich is exactly what a weight matrix computes via dot product - A constant per centroid
-||c_i||²/(2T)which becomes the bias
Therefore:
- Weight matrix: Each row is a centroid scaled by 1/temperature
- Bias vector: Each entry is the negative squared norm of the corresponding centroid, divided by 2·temperature
- Probabilities: Apply numerically stable softmax to the logits
The temperature parameter controls assignment sharpness: small values make the distribution concentrate on the nearest centroid (hard assignment), while large values flatten the distribution toward uniform.
Correctness
The logits equal -||x - c_i||²/(2T) up to a shared constant, so:
- The argmax identifies the nearest centroid
- The probabilities follow a Boltzmann distribution with distance-based energy
- As temperature approaches zero, all probability mass concentrates on the nearest centroid
Complexity
- Time: O(k·d) where k is the number of centroids and d is the dimension. We compute k dot products of length d, plus O(k) for softmax.
- Space: O(k·d) for the weight matrix, O(k) for bias and probabilities.
Implementation
import math
from typing import List, Dict
def compute_soft_centroid_assignment(centroids: List[List[float]], x: List[float], temperature: float) -> Dict[str, object]:
# Expand squared distance: ||x - c_i||² = ||x||² - 2(x·c_i) + ||c_i||²
# Divide by -2T: -||x - c_i||²/(2T) = -||x||²/(2T) + (x·c_i)/T - ||c_i||²/(2T)
# The first term is constant across all centroids, so softmax ignores it
weights = [[coord / temperature for coord in centroid] for centroid in centroids]
bias = [
-sum(coord * coord for coord in centroid) / (2.0 * temperature)
for centroid in centroids
]
# Compute logits: z = Wx + b
logits = [
sum(w * val for w, val in zip(weight_row, x)) + b_val
for weight_row, b_val in zip(weights, bias)
]
# Numerically stable softmax: subtract max before exp
max_logit = max(logits)
exp_values = [math.exp(z - max_logit) for z in logits]
exp_sum = sum(exp_values)
probabilities = [e / exp_sum for e in exp_values]
return {
"weights": weights,
"bias": bias,
"probabilities": probabilities,
}