0Pricing
Learn AI with Python · Lesson

K-Means Clustering Project

Applying it to a real dataset.

K-Means Clustering Project is a free Learn AI with Python lesson on CoddyKit — 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 Learn AI with Python learning path, one of 5 lessons in the course, and your progress syncs across the web and the CoddyKit app.

1

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

2

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).

3

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())

4

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])

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()

6

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())

7

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()

8

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.

9

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.

10

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

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, and the Learn AI with Python course includes 5 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the Learn AI with Python course, upgrade to CoddyKit PRO.

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

Applying it to a real dataset. You practise Learn AI with Python 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 Learn AI with Python?

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

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 Learn AI with Python lesson?

Yes. Every Learn AI with Python 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 Learn AI with Python