MACHINE LEARNING • LESSON 11

Understand the Python Code

We already built a K-Means model. Now let's understand exactly what each important line of Python code does.

THE SIMPLE IDEA

Every line has a specific job.

We import K-Means, prepare our data, create the model, choose the number of clusters, train the model, and then read the clusters and their centers.

COMPLETE CODE

First, Look at the Full Code

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)

Now let's break this code into small pieces.

STEP 1

Import NumPy

import numpy as np

NumPy is a Python library used for working with numerical data and arrays.

We use it here to create our dataset.

CODE np.array(...)
MEANING Create a numerical array
NumPy is handling the numerical data. It is not performing the K-Means clustering.
STEP 2

Import KMeans

from sklearn.cluster import KMeans

This imports the KMeans algorithm from scikit-learn.

After this line, we can create a K-Means model in Python.

scikit-learn cluster KMeans
STEP 3

Create the Dataset

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

The variable X contains our input data.

Each row represents one customer.

CUSTOMER SPENDING PURCHASES
1 1000 2
2 1200 3
3 1100 2
4 10000 15
5 11000 17
6 10500 16

So:

Rows = Customers Column 1 = Spending Column 2 = Purchases
STEP 4

Create the K-Means Model

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

This creates a K-Means model.

We have not trained it yet.

Creating the model and training the model are two different steps.

What does n_clusters=2 mean?

K = 2

We are telling K-Means:

"Create two clusters."
IMPORTANT PARAMETER

What Is random_state=42?

random_state=42

K-Means uses random initialization when starting its cluster centers.

Setting random_state gives us reproducible results.

The number 42 is not special. You could use another fixed number.

WITHOUT FIXED RANDOM STATE Results can vary
WITH random_state=42 Easier to reproduce
STEP 5

Train the Model

model.fit(X)

This is one of the most important lines.

fit() tells K-Means to learn the cluster structure from our data.

X model.fit(X) Learned Clusters

Internally, K-Means repeatedly assigns points to nearby centroids and moves the centroids until the solution becomes stable.

STEP 6

Get the Cluster Labels

labels = model.labels_

After training, labels_ tells us which cluster each data point was assigned to.

For example, we might get:

[1 1 1 0 0 0]

This corresponds to:

CUSTOMER LABEL
Customer 1 1
Customer 2 1
Customer 3 1
Customer 4 0
Customer 5 0
Customer 6 0
0 and 1 are simply cluster IDs. They don't mean good, bad, high, or low.
STEP 7

Get the Cluster Centers

centers = model.cluster_centers_

cluster_centers_ contains the centroid of every cluster.

A centroid represents the average position of the data points belonging to that cluster.

CLUSTER 0 Center

Represents the average position of the customers assigned to Cluster 0.

CLUSTER 1 Center

Represents the average position of the customers assigned to Cluster 1.

STEP 8

Print the Results

print("Labels:")
print(labels)

print("Centers:")
print(centers)

print() simply displays the values in the terminal or notebook.

Labels:
[1 1 1 0 0 0]

Centers:
[[10500.    16. ]
 [ 1100.     2.33]]

The exact ordering of cluster labels can vary, so don't depend on Cluster 0 always being the lower-spending group or Cluster 1 always being the higher-spending group.

PUT IT TOGETHER

The Whole Code in Plain English

1 Import NumPy

We need numerical arrays.

2 Import KMeans

We need the K-Means algorithm.

3 Create X

X contains our customer data.

4 Create model

Tell K-Means that K is 2.

5 model.fit(X)

Learn the clusters.

6 model.labels_

Find each point's cluster.

7 cluster_centers_

Find the cluster centers.

REAL-WORLD NOTE

Don't Forget Feature Scaling

Our example uses spending and purchases, but these features have very different numerical scales.

SPENDING 1,000 → 11,000
PURCHASES 2 → 17

Because K-Means uses distances, the spending feature can dominate the distance calculation.

In a real project, you would usually scale the numerical features before clustering when their scales differ substantially.

The code is simple. Getting the data preparation right is the harder and more important part.
REMEMBER THIS

Understand the job of each line.

You don't need to memorize the entire code. Understand the workflow and what each important command produces.

1 Import
2 Prepare X
3 Create Model
4 fit(X)
5 Read Results
QUICK CHECK

Check Your Understanding

What does X contain? The input features used for clustering.
What does n_clusters=2 mean? K-Means should create two clusters.
What does fit(X) do? It learns the cluster structure from X.
What does labels_ tell us? Which cluster each data point belongs to.
What does cluster_centers_ contain? The centroid of every cluster.
Why can feature scaling matter? K-Means uses distance, so large-scale features can dominate.
LESSON 11 COMPLETE

You Now Understand K-Means

You learned what clustering is, how K-Means works, how to choose K, how to build K-Means in Python, and how to understand the important Python code.