Python Academy · Lesson

K-Means Clustering Project

Applying it to a real dataset.

Lesson 3 of 510 steps

K-Means Clustering Project is a free Python Academy lesson on CoddyKit. This is lesson 3 of 5. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the Python Academy learning path, and your progress syncs across the web and the CoddyKit app. The Python Academy course includes 5 lessons in total.

K-Means Clustering Project

In this project, we’ll apply K-Means clustering to a real-world dataset: customer segmentation. The goal is to group customers based on their spending patterns.

K-Means Clustering Project — illustration 1

Dataset Overview

The dataset contains the following columns:

  • Customer ID: Unique identifier for each customer.
  • Age: Age of the customer.
  • Annual Income: Annual income in thousands of dollars.
  • Spending Score: A score assigned based on customer behavior and spending patterns (1–100).

Step 1: Importing the Dataset and Libraries

We’ll start by importing the necessary libraries and loading the dataset:

import pandas as pd
import matplotlib.pyplot as plt
from sklearn.cluster import KMeans

# Load dataset
data = pd.read_csv('Mall_Customers.csv')
print(data.head())

Step 2: Data Preprocessing

We’ll select relevant features for clustering and normalize the data if necessary. For this project, we’ll use Annual Income and Spending Score:

# Select relevant features
X = data[['Annual Income (k$)', 'Spending Score (1-100)']].values
print(X[:5])

Step 3: Determining the Optimal Number of Clusters

We use the elbow method to find the optimal number of clusters by plotting the within-cluster sum of squares (WCSS) for different values of K:

wcss = []
for i in range(1, 11):
    kmeans = KMeans(n_clusters=i, init='k-means++', random_state=42)
    kmeans.fit(X)
    wcss.append(kmeans.inertia_)

plt.plot(range(1, 11), wcss)
plt.title('Elbow Method')
plt.xlabel('Number of Clusters')
plt.ylabel('WCSS')
plt.show()

Step 4: Applying K-Means Clustering

Based on the elbow method, we choose the optimal number of clusters (e.g., K=5) and fit the K-Means model:

kmeans = KMeans(n_clusters=5, init='k-means++', random_state=42)
kmeans.fit(X)

# Add cluster labels to the dataset
data['Cluster'] = kmeans.labels_
print(data.head())

Step 5: Visualizing the Clusters

We can plot the clusters in a 2D space to observe their separation:

plt.scatter(X[:, 0], X[:, 1], c=kmeans.labels_, cmap='viridis')
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=200, c='red', marker='X')
plt.title('Customer Segmentation')
plt.xlabel('Annual Income (k$)')
plt.ylabel('Spending Score (1-100)')
plt.show()

Step 6: Interpreting the Clusters

Each cluster represents a group of customers with similar spending patterns. For example:

  • Cluster 1: High income, high spending.
  • Cluster 2: Low income, low spending.
  • Cluster 3: Moderate income, high spending.

Challenges in Real-World Clustering

While clustering is powerful, real-world applications face challenges like:

  • High-dimensional datasets.
  • Noisy or incomplete data.
  • Interpreting cluster results meaningfully.

Summary and Next Steps

In this project, we:

  • Explored a real-world dataset.
  • Applied K-Means clustering and visualized the results.
  • Interpreted the clusters to understand customer behavior.

Next, we will learn about dimensionality reduction techniques like PCA and t-SNE.

K-Means Clustering Project — illustration 10
Free to start

Learn Python with an AI tutor — free

Write and run real code in your browser, get instant help from a 24/7 AI tutor, and pick up where you left off on the web or in the app.

Courses
76
Lessons
320

Frequently Asked Questions

Is the “K-Means Clustering Project” lesson free?

Yes — the full text of “K-Means Clustering Project” is free to read here on the web. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Python Academy course, upgrade to CoddyKit PRO. The Python Academy course includes 5 lessons in total.

What will I learn in “K-Means Clustering Project”?

Applying it to a real dataset. You practise Python Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start Python Academy?

No prior experience is required. Python Academy on CoddyKit is structured for beginners through advanced learners, so you can start here or from the beginning and move at your own pace. This is lesson 3 of 5.

How long does the “K-Means Clustering Project” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this Python Academy lesson?

Yes. Every Python Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Introduction to Clustering Algorithms
  2. K-Means Clustering
  3. K-Means Clustering Project
  4. Dimensionality Reduction Basics
  5. Dimensionality Reduction Application
← Back to Python Academy