K-Means Clustering in Python (scikit-learn Example)

For k means clustering in Python, scale your features, then fit scikit-learn’s KMeans with the number of clusters you want. It assigns every row to the nearest cluster center:

from sklearn.cluster import KMeans
labels = KMeans(n_clusters=3, n_init="auto").fit_predict(X_scaled)

I used Python 3.12.5 and scikit-learn 1.9.1 on 300 made-up store customers, each with an annual spend in dollars and a number of visits per year.

We’ll fit the model and read the centers in dollars, choose k with the elbow method and silhouette scores, label new customers, and plot the clusters.

K means clustering in Python with scikit-learn

K-means uses distances, so a feature measured in thousands of dollars would swamp one measured in visits. StandardScaler fixes that before fitting:

import numpy as np

rng = np.random.default_rng(42)
# three kinds of shoppers: (annual spend in USD, visits per year)
occasional = rng.normal([400, 6], [120, 2], size=(100, 2))
regular = rng.normal([1500, 24], [250, 4], size=(100, 2))
loyal = rng.normal([3600, 52], [400, 6], size=(100, 2))
X = np.vstack([occasional, regular, loyal]).clip(min=1)

from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
X_scaled = scaler.fit_transform(X)            # put dollars and visits on the same scale

kmeans = KMeans(n_clusters=3, n_init="auto", random_state=0)
labels = kmeans.fit_predict(X_scaled)

centers = scaler.inverse_transform(kmeans.cluster_centers_)
for i, (spend, visits) in enumerate(centers):
    print(f"cluster {i}: {np.sum(labels == i):>3} customers | avg spend ${spend:>8,.2f} | {visits:4.1f} visits/yr")
print("inertia:", round(kmeans.inertia_, 2))

Output:

cluster 0: 100 customers | avg spend $1,514.71 | 23.9 visits/yr
cluster 1: 100 customers | avg spend $3,555.57 | 51.8 visits/yr
cluster 2: 100 customers | avg spend $  398.23 |  5.9 visits/yr
inertia: 28.38
Command Prompt output of scikit-learn KMeans clustering 300 customers into three groups with average spend and visits
Three clean groups: occasional, regular and loyal shoppers, with their average spend in dollars.

inverse_transform turns the scaled centers back into dollars and visits, which is what you’d show a manager. The same scaling step matters in PCA in Python.

How do you choose the number of clusters?

You have to pick k yourself. Two common checks are the elbow method (inertia, lower is tighter) and the silhouette score (closer to 1 is better separated):

# X = customer data from the first example

from sklearn.cluster import KMeans
from sklearn.metrics import silhouette_score
from sklearn.preprocessing import StandardScaler

X_scaled = StandardScaler().fit_transform(X)
print(" k   inertia   silhouette")
for k in range(1, 9):
    km = KMeans(n_clusters=k, n_init="auto", random_state=0).fit(X_scaled)
    sil = silhouette_score(X_scaled, km.labels_) if k > 1 else float("nan")
    print(f"{k:>2} {km.inertia_:>9.2f}   {sil:>8.3f}")

Output:

 k   inertia   silhouette
 1    600.00        nan
 2    106.40      0.731
 3     28.38      0.774
 4     20.58      0.650
 5     17.00      0.648
 6     14.29      0.516
 7     12.31      0.510
 8     10.14      0.532
Command Prompt table of k-means inertia and silhouette scores for k from 1 to 8 in Python
Inertia drops sharply until k = 3 and then flattens, and the silhouette score peaks at 3.

Inertia always falls as k grows, so look for the bend, not the minimum. When the two methods disagree, I go with the k that makes business sense.

Assign new data to clusters

Once the model is fitted, predict() places new rows in the nearest cluster. Scale them with the same scaler first:

# X = customer data from the first example

from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler().fit(X)
kmeans = KMeans(n_clusters=3, n_init="auto", random_state=0).fit(scaler.transform(X))

names = {}
for i, (spend, _) in enumerate(scaler.inverse_transform(kmeans.cluster_centers_)):
    names[i] = "occasional" if spend < 1000 else "regular" if spend < 2500 else "loyal"

new_customers = np.array([[250.00, 4], [1800.00, 20], [4200.00, 60]])
for row, label in zip(new_customers, kmeans.predict(scaler.transform(new_customers))):
    print(f"${row[0]:>8,.2f}, {row[1]:>2.0f} visits -> cluster {label} ({names[label]})")

Output:

$  250.00,  4 visits -> cluster 2 (occasional)
$1,800.00, 20 visits -> cluster 0 (regular)
$4,200.00, 60 visits -> cluster 1 (loyal)
Command Prompt output of Python k-means predicting clusters for three new customers with friendly cluster names
Each new customer lands in the group you’d expect.

Cluster numbers are arbitrary and can change between runs, so I name them from their centers rather than hard-coding “cluster 2 = loyal”.

Plot the k-means clusters

With two features, a scatter plot shows the result directly. The red X marks are the cluster centers:

# X = customer data from the first example

import matplotlib.pyplot as plt
from sklearn.cluster import KMeans
from sklearn.preprocessing import StandardScaler

scaler = StandardScaler()
kmeans = KMeans(n_clusters=3, n_init="auto", random_state=0)
labels = kmeans.fit_predict(scaler.fit_transform(X))
centers = scaler.inverse_transform(kmeans.cluster_centers_)

plt.figure(figsize=(8, 5))
plt.scatter(X[:, 0], X[:, 1], c=labels, cmap="viridis", s=18, alpha=0.8)
plt.scatter(centers[:, 0], centers[:, 1], c="red", marker="X", s=200, label="cluster centers")
plt.xlabel("Annual spend (USD)"); plt.ylabel("Visits per year")
plt.title("K-means clustering of 300 store customers (k = 3)")
plt.legend(); plt.tight_layout()
plt.show()
Matplotlib scatter plot of k-means clusters of store customers by annual spend and visits with red cluster centers
Three groups of customers, each colored by cluster, with the centers in red.

K-means tips and limitations

  • Always scale features with different units.
  • Set random_state for repeatable results; n_init="auto" runs several starts and keeps the best.
  • K-means assumes round, similar-sized clusters. For odd shapes, try DBSCAN.
  • Outliers pull centers around, so look at your data before clustering.

More machine learning guides in Python:

Frequently asked questions

How do I do k means clustering in Python?

Scale your data with StandardScaler, then use KMeans(n_clusters=k, n_init="auto").fit_predict(X_scaled) from scikit-learn.

Do I need to scale data for k-means?

Yes, when features use different units. Otherwise the largest-valued feature dominates the distances.

How do I pick k?

Use the elbow method on inertia and compare silhouette scores, then sanity-check the groups.

What does inertia mean?

The sum of squared distances from each point to its cluster center. Lower means tighter clusters.

Why do my cluster numbers change?

Labels are arbitrary. Set random_state and name clusters from their centers.

Where is KMeans documented?

See K-means in the scikit-learn user guide.