Understand the Python Code
We already built a K-Means model. Now let's understand exactly what each important line of Python code does.
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.
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.
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.
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.
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.
So:
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.
What does n_clusters=2 mean?
We are telling K-Means:
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.
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.
Internally, K-Means repeatedly assigns points to nearby centroids and moves the centroids until the solution becomes stable.
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:
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.
Represents the average position of the customers assigned to Cluster 0.
Represents the average position of the customers assigned to Cluster 1.
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.
The Whole Code in Plain English
We need numerical arrays.
We need the K-Means algorithm.
X contains our customer data.
Tell K-Means that K is 2.
Learn the clusters.
Find each point's cluster.
Find the cluster centers.
Don't Forget Feature Scaling
Our example uses spending and purchases, but these features have very different numerical scales.
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.
Understand the job of each line.
You don't need to memorize the entire code. Understand the workflow and what each important command produces.