Mastering K-means Clustering with Python: From Theory to Practical Implementation

Introduction

Welcome to our exploration of Unsupervised Learning and Clustering. In this lesson, we'll delve into K-means clustering, clarify its underlying principles, and navigate through the implementation of the K-means clustering algorithm in Python.

Understanding Unsupervised Learning

Unsupervised Learning uses a dataset without labels to identify inherent patterns. Unlike Supervised Learning, which leverages known outcomes from data for label prediction, Unsupervised Learning operates independently. One application is market basket analysis, which predicts customer purchases based on associated buying behaviors.

K-means Clustering: Theory and Implementation Overview

Let's encapsulate the essence of K-means clustering: this iterative algorithm partitions a group of data points into a predefined number of clusters based on their inherent distances from each other. The K in K-means denotes the number of clusters. K-means clustering operates based on a set metric, the most common of which is the Euclidean distance.

In subsequent sections, we'll adopt a hands-on approach to implement K-means clustering in Python. We'll be using libraries like numpy for numerical operations and matplotlib for visualizations. Let's get started!

Initializing and Preparing for K-means Clustering

First, we initiate the lesson by loading the necessary libraries and defining our data points:

Python
import numpy as np
import matplotlib.pyplot as plt

np.random.seed(0)
x1 = np.random.normal(loc=5, scale=1, size=(100, 2))
x2 = np.random.normal(loc=10, scale=2, size=(100, 2))
x = np.concatenate([x1, x2])

plt.scatter(x[:,0], x[:,1], label='True Position')
plt.show()

Next, we ready our dataset for K-means clustering. Here, we plot the data points, indicate the number of clusters, and initialize the centroids. Additionally, we introduce helper functions for computing Euclidean distances and assigning centroids.

Python
k = 3
centroids = x[np.random.choice(range(x.shape[0]), size=k, replace=False), :]

def calc_distance(X1, X2):
    return (sum((X1 - X2)**2))**0.5

def find_closest_centroids(ic, X):
    assigned_centroid = []
    for i in X:
        distance=[]
        for j in ic:
            distance.append(calc_distance(i, j))
        assigned_centroid.append(np.argmin(distance))
    return assigned_centroid
Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal