MACHINE LEARNING • LESSON 11

Build K-Means With Python

Now that we understand how K-Means works, let's build a real K-Means clustering model using Python and scikit-learn.

THE SIMPLE IDEA

Give K-Means data → choose K → fit the model → get clusters.

In Python, scikit-learn provides the KMeans class. We give it our data, tell it how many clusters we want, and let it find the groups.

01

Install scikit-learn

K-Means is available in the scikit-learn Python library.

pip install scikit-learn

If you are working inside a Jupyter Notebook, you can also use:

!pip install scikit-learn
02

Import KMeans

First, import the KMeans class.

from sklearn.cluster import KMeans

Now Python knows that we want to use the K-Means algorithm from scikit-learn.

KMeans is the Python class that creates our clustering model.
03

Create Some Data

Let's create a small customer dataset.

We will use two features:

FEATURE 1 Annual Spending
FEATURE 2 Number of Purchases
import numpy as np

X = np.array([
    [1000, 2],
    [1200, 3],
    [1100, 2],
    [10000, 15],
    [11000, 17],
    [10500, 16]
])

Each row represents one customer.

CUSTOMER [1000, 2]

₹1,000 spending and 2 purchases.

CUSTOMER [10000, 15]

₹10,000 spending and 15 purchases.

04

Choose the Number of Clusters

We learned earlier that K tells K-Means how many clusters to create.

Let's choose:

K = 2

In Python:

model = KMeans(
    n_clusters=2,
    random_state=42
)

Here:

n_clusters=2 Create 2 clusters.
random_state=42 Makes the random initialization reproducible.
05

Train the K-Means Model

Now we give our data to the model.

model.fit(X)

This is where K-Means actually performs the clustering.

Customer Data model.fit(X) Clusters
fit() tells the K-Means model to learn the cluster structure from the data.
06

Get the Cluster Labels

After fitting the model, we can see which cluster each data point belongs to.

labels = model.labels_

print(labels)

You might get something similar to:

[1 1 1 0 0 0]

This means:

CLUSTER 1 First 3 customers

[1000, 2], [1200, 3], [1100, 2]

CLUSTER 0 Last 3 customers

[10000, 15], [11000, 17], [10500, 16]

The numbers 0 and 1 are just cluster identifiers. Cluster 1 is not automatically "better" than Cluster 0.
07

Get the Cluster Centers

K-Means also gives us the center of each cluster.

print(model.cluster_centers_)

These are called centroids.

Each centroid represents the average position of the data points in that cluster.

CLUSTER CENTER Spending ≈ ₹1,100

Represents the lower-spending customers.

CLUSTER CENTER Spending ≈ ₹10,500

Represents the higher-spending customers.

COMPLETE CODE

Build the Complete Model

Now let's put everything together.

import numpy as np
from sklearn.cluster import KMeans

# Customer data
X = np.array([
    [1000, 2],
    [1200, 3],
    [1100, 2],
    [10000, 15],
    [11000, 17],
    [10500, 16]
])

# Create the model
model = KMeans(
    n_clusters=2,
    random_state=42
)

# Train the model
model.fit(X)

# Get cluster labels
labels = model.labels_

# Get cluster centers
centers = model.cluster_centers_

print("Labels:")
print(labels)

print("Centers:")
print(centers)
UNDERSTAND THE FLOW

What Did We Actually Do?

1 Import KMeans
2 Prepare Data
3 Choose K
4 fit(X)
5 Get Labels

That's the basic K-Means workflow in Python.

IMPORTANT

Feature Scaling Can Matter

K-Means uses distance to decide which points are close to each other.

Therefore, features with very different scales can affect the result.

For example:

ANNUAL SPENDING 1,000 – 11,000
PURCHASES 2 – 17

Spending has much larger numerical values than purchases. In a real machine-learning workflow, we would usually consider scaling the features before applying K-Means.

Because K-Means is distance-based, feature scaling is often important.
REMEMBER THIS

K-Means in Python is only a few important steps.

Prepare your features, create a KMeans model, choose K, call fit(), and then inspect the cluster labels and cluster centers.

1 Prepare X
2 Choose K
3 fit(X)
4 Get Labels
QUICK CHECK

Check Your Understanding

Which library provides KMeans? Scikit-learn.
What does n_clusters=2 mean? Create 2 clusters.
What does fit(X) do? It learns the cluster structure from the data.
What does model.labels_ contain? The cluster assigned to each data point.
What does cluster_centers_ contain? The centroid of each cluster.
Why can scaling matter? K-Means uses distances, so features with very different scales can affect the clustering.
NEXT TOPIC

Understand the Python Code

Next, we'll break the K-Means Python code down line by line so you understand exactly what every part does.