A centroid is the arithmetic mean of the data points assigned to a cluster. It represents the cluster’s center and provides the reference point for similarity in k-means. section 8.2
K-means uses centroids through an iterative workflow:
- Assign each data point to its closest centroid using straight-line, or Euclidean, distance. section 8.2.1
- Recompute each centroid as the mean of the points assigned to its cluster. section 8.2.1
- Repeat assignment and recomputation until centroids stop changing or a maximum step count is reached. section 8.2.1
- Scale features before clustering so variables with larger magnitudes do not dominate centroid distances. section 8.2.1
Four-cluster traffic analysis
With k = 4, k-means maps each row of df_features_one_hot_enc to one of four clusters. A run produced clusters containing 110,085, 42,279, 7,328, and 2 points; smaller clusters can receive closer analysis, while centroid calculations remain sensitive to outliers. section 8.2.4
Listing 8.16 Applying k-means to df_features_one_hot_enc
km = KMeans(n_clusters = 4) #1 km.fit(df_features_one_hot_enc) #2 df_features_one_hot_enc['cluster'] = km.labels_ #3 df_features_one_hot_enc.head()
The listing shows how to create four centroids with KMeans, fit them to the feature table, and attach the resulting cluster labels. section 8.2.4






