0Pricing
Learn AI with Python · Lesson

K-Means Clustering

Step-by-step understanding.

K-Means Clustering is a free Learn AI with Python lesson on CoddyKit — lesson 2 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

K-Means is one of the most popular clustering algorithms. It partitions data into a predefined number of clusters (K) by minimizing the intra-cluster distances.

It works iteratively to find the best cluster assignments and centroids.

K-Means Clustering — illustration 1

2

How K-Means Works

K-Means operates in the following steps:

  1. Initialize K random centroids.
  2. Assign each data point to the nearest centroid.
  3. Recalculate centroids as the mean of all points in a cluster.
  4. Repeat steps 2 and 3 until centroids stabilize or a maximum number of iterations is reached.

3

Choosing the Number of Clusters

The value of K is a critical parameter. Common methods to choose K include:

  • Elbow Method: Plot the within-cluster sum of squares (WCSS) for different K values and look for the 'elbow point.'
  • Silhouette Score: Measures how well-separated the clusters are.

4

Example Dataset for K-Means

Let’s consider a dataset with points distributed in 2D space. Each point has:

  • X: Coordinate on the horizontal axis.
  • Y: Coordinate on the vertical axis.

K-Means will group these points into clusters based on their proximity.

5

Implementing K-Means in Python

We’ll use the KMeans class from the scikit-learn library to implement the algorithm:

from sklearn.cluster import KMeans
import numpy as np

# Example dataset
X = np.array([[1, 2], [1, 4], [1, 0], [4, 2], [4, 4], [4, 0]])

# K-Means model
kmeans = KMeans(n_clusters=2, random_state=0)
kmeans.fit(X)

print("Cluster Centers:", kmeans.cluster_centers_)
print("Labels:", kmeans.labels_)

6

Visualizing Clusters

We can visualize the clusters by plotting the data points and centroids:

import matplotlib.pyplot as plt

# Scatter plot of data points
plt.scatter(X[:, 0], X[:, 1], c=kmeans.labels_, cmap='viridis')

# Plot cluster centers
plt.scatter(kmeans.cluster_centers_[:, 0], kmeans.cluster_centers_[:, 1], s=200, c='red', marker='X')
plt.title('K-Means Clustering')
plt.show()

7

Advantages of K-Means

K-Means has several benefits:

  • Simple and easy to implement.
  • Efficient for large datasets.
  • Works well when clusters are clearly defined.

8

Limitations of K-Means

Some limitations of K-Means include:

  • Sensitivity to the initial placement of centroids.
  • Difficulty in handling non-spherical clusters.
  • Sensitivity to outliers and noisy data.

9

10

Summary and Next Steps

In this lesson, we covered:

  • How K-Means clustering works.
  • Choosing the number of clusters using methods like the elbow method.
  • Implementing and visualizing K-Means in Python.

Next, we will apply K-Means to a real-world dataset to gain practical experience.

K-Means Clustering — illustration 10

Frequently asked questions

Is the “K-Means Clustering” lesson free?

Yes — the full text of “K-Means Clustering” 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”?

Step-by-step understanding. 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 2 of 5, so you can start here or from the beginning and move at your own pace.

How long does the “K-Means Clustering” 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