Understand the idea
K-Means alternates assignments and centroid updates to reduce within-cluster squared distances. Production uses multiple initialisations and a reproducible seed. k=3 is a starting choice, not a discovered truth.
Illustrative data
| Column | Values |
|---|---|
x | 1, 1.3, 0.7, 1.2, 5, 5.3, 4.7, 5.2, 3, 3.4, 2.6, 3.1 |
y | 1, 0.7, 1.2, 1.4, 1, 0.7, 1.3, 1.4, 5, 4.8, 5.3, 5.5 |
Click the highlighted code to change the result.
scaled = StandardScaler().fit_transform(example[["x", "y"]])
example_model = KMeans(n_clusters=, n_init=20, random_state=42)
example_model.fit(scaled)
centres = example_model.cluster_centers_3 groups · inertia 0.503 · silhouette 0.864; crosses are fitted centroids. Crosses mark centroids; group IDs are not known classes.
What the syntax does
KMeans(n_clusters=3, n_init=20, random_state=42)- Creates a K-Means model that groups observations around fitted centres.
n_clusters:2,3,4n_init:"auto",10,20random_state:42,None
n_clusterssets a positive group count;n_init=20 tries twenty initialisations.- Scaling defines the distance.
- Group IDs are arbitrary and silhouette measures geometry, not truth.
model.cluster_centers_- Stores fitted centroids in the scaled coordinate system.
Supplied for this practice
These objects are prepared afresh before your editor runs.
X- Feature dataframe for the declared population, preserving row indices.
X = df.copy() scaler- Already fitted coordinate system learned from
X; transform reuses its statistics without fitting again. Fitted onX; reuse without refitting. scaled- Standardised features in the same row/column order as
X.scaled = scaler.fit_transform(X)
Outputs you create
answer- The requested result, with the values, labels and row order described by this task.
length_mm | width_cm |
|---|---|
| 1106.65 | 6.36006 |
| 1262.66 | 13.292 |
| 317.138 | 5.44237 |
| 1044.74 | 8.89315 |
| 994.12 | 7.01435 |
| 1307.79 | 12.7223 |
| 1023.11 | 13.9453 |
| 1163.63 | 6.99248 |
- Fit three K-Means clusters to
scaledCLUSTER36. - Store the fitted centroid coordinates in
answer.
answerHints
Think: Centroids live in the same coordinate system used for fitting.
Tools: KMeans, n_clusters, n_init and cluster_centers_.
Approach: Fit the declared reproducible three-centroid model to scaled values and inspect its centres.
Explained solution
model=KMeans(n_clusters=3,n_init=20,random_state=42).fit(scaled)
answer=model.cluster_centers_
Multiple starts reduce dependence on a single initialisation; the resulting centres are in standardised units.