Seeded Two-Round K-Means with Spread-Out Starting Centers
Arrays & HashingAuto-graded · 17 test casesLast updated
Simulate k-means++ seeding with a fixed RNG protocol, then run two assign/update rounds and report clusters, centroids and final squared error.
You are given a list of points in d-dimensional space and a number of clusters k. Simulate a short k-means run: pick starting centers with a distance-weighted random rule, then run exactly two assign-and-update rounds, then report the squared error.
The random choices must follow the protocol below exactly, so every correct solution produces the same output for the same seed.
Seeding the centers
Create a generator with Python's standard random.Random(seed). Call rng.randrange(...) and rng.random() only as described here, in this order.
- First center: call
rng.randrange(n), wherenis the number of points, and take the point at that index. - Each further center, until
kcenters are chosen:- For every point, compute its weight: the smallest squared Euclidean distance from that point to any center chosen so far.
- Let
totalbe the sum of all weights. - If
total > 0, drawthreshold = rng.random() * total. Walk through the points in index order, keeping a running sum of weights. Choose the first index wherethreshold < running_sum. If no index qualifies because of rounding, choose the last index. - If
total == 0, do not call the generator. Call an index "used" if its point has the same coordinates as any center chosen so far. Choose the smallest index that is not used. If every index is used, choose index0. - Append a copy of the chosen point as the next center.
Record the list of chosen centers, in the order chosen, as the sampled centers.
The two rounds
Repeat the following twice, starting from the sampled centers:
- Assign: send each point to the center with the smallest squared Euclidean distance. If two centers are tied, pick the one with the lower index. Within each cluster, keep the points in their original input order.
- Update: replace each center with the coordinate-wise mean of its cluster. If a cluster is empty, keep that center unchanged.
After each round, record the clusters (a list of k lists of points) and the centers after the update.
Final error
After the second round, compute the sum, over all points, of the squared distance to the nearest of the final centers.
Return value
Return a dictionary with these keys:
"sampledCenters": list ofkpoints, the centers from seeding."iterations": list of two dictionaries, one per round, each with"clusters": list ofklists of points, indexed by center, from that round's assign step;"centroids": list ofkpoints, the centers after that round's update step.
"sse": the final squared error as a number.
Constraints
1 <= k <= len(points)pointsis non-empty, and every point has the same dimensiond >= 1.- Coordinates are finite numbers.
- Points may repeat.
- Use squared distances throughout, computed by summing over coordinates in order. Do not take square roots.
- Compare results as exact values from the described procedure. Do not use another random source or a different order of random calls.
Examples
Example 1
Input: run_seeded_kmeans_two_rounds([[0, 0], [0, 2], [2, 0], [2, 2], [8, 8], [8, 10], [10, 8], [10, 10]], 2, 42)
Output: {'sampledCenters': [[0, 2], [2, 2]], 'iterations': [{'clusters': [[[0, 0], [0, 2]], [[2, 0], [2, 2], [8, 8], [8, 10], [10, 8], [10, 10]]], 'centroids': [[0, 1], [6.666666666666667, 6.333333333333333]]}, {'clusters': [[[0, 0], [0, 2], [2, 0], [2, 2]], [[8, 8], [8, 10], [10, 8], [10, 10]]], 'centroids': [[1, 1], [9, 9]]}], 'sse': 16}
Hints
Hint 1
Keep the random calls exactly as specified: one randrange for the first center, then one random() per further center, and none at all when the total weight is zero.
Hint 2
For the weighted pick, build the running sum of weights and take the first index where the threshold is strictly less than that sum. Python's min over a range of indices already breaks distance ties toward the lower index.
Hint 3
Write one helper for squared distance and reuse it for seeding, assignment and the final error. Remember that an empty cluster keeps its previous center.
Worked solution
Medium Try it yourself first — then compare your approach, complexity and edge cases.
Approach
This is a direct simulation, and the main task is to follow the specified procedure exactly.
- Seeding. Create
random.Random(seed). The first center is the point atrng.randrange(n). For each further center:- Compute each point's weight, which is its smallest squared distance to the chosen centers.
- Draw
threshold = rng.random() * total. - Take the first index whose running weight sum exceeds the threshold. This is inverse-CDF sampling proportional to the weights, so points far from existing centers are more likely to be chosen.
- If every weight is zero, all remaining points coincide with chosen centers. In that case, skip the random draw and deterministically take the first point not already used, or index 0 if all are used.
- Rounds. Do two rounds. In each, assign every point to its nearest center.
minover center indices returns the lowest index on ties. Then replace each center with its cluster mean, or keep it if the cluster is empty. Record the clusters and updated centers. - Error. Sum, over all points, the squared distance to the nearest final center.
Why it is correct
- Fixing the RNG type and the order and number of random calls makes the sampled centers the same for everyone.
- Nearest-center assignment with a lowest-index tie-break is deterministic.
- The mean is the standard update for squared distance, and keeping the old center for an empty cluster avoids dividing by zero.
- The final error uses the same squared distance as the rest of the procedure.
Complexity
- Seeding: each of the
k - 1rounds scans all points against up tokcenters, so O(n·k²·d). - Each assign/update round: O(n·k·d).
- Final error: O(n·k·d).
- Total time is O(n·k²·d). Space is O(n·d + k·d) beyond the output.
Reference solution
import random
from typing import Dict, List
def run_seeded_kmeans_two_rounds(points: List[List[float]], k: int, seed: int) -> Dict:
dim = len(points[0])
def sqdist(a, b):
return sum((a[d] - b[d]) ** 2 for d in range(dim))
rng = random.Random(seed)
centers = [list(points[rng.randrange(len(points))])]
while len(centers) < k:
weights = [min(sqdist(p, c) for c in centers) for p in points]
total = sum(weights)
if total == 0:
used = [i for i, p in enumerate(points) if p in centers]
next_index = next((i for i in range(len(points)) if i not in used), 0)
else:
threshold = rng.random() * total
cumulative = 0.0
next_index = len(points) - 1
for i, w in enumerate(weights):
cumulative += w
if threshold < cumulative:
next_index = i
break
centers.append(list(points[next_index]))
sampled_centers = [c[:] for c in centers]
iterations = []
for _ in range(2):
clusters = [[] for _ in range(k)]
for p in points:
idx = min(range(k), key=lambda j: sqdist(p, centers[j]))
clusters[idx].append(list(p))
updated = []
for j, cluster in enumerate(clusters):
if cluster:
updated.append([sum(q[d] for q in cluster) / len(cluster) for d in range(dim)])
else:
updated.append(centers[j][:])
centers = updated
iterations.append({"clusters": clusters, "centroids": [c[:] for c in centers]})
sse = sum(min(sqdist(p, c) for c in centers) for p in points)
return {"sampledCenters": sampled_centers, "iterations": iterations, "sse": sse}