Enhancing Machine Learning Expertise: Mini-Batch K-Means Clustering Explained
Introduction
Welcome back to our exploration of clustering algorithms! Today, we'll cover an improved version of the k-means algorithm — the mini-batch k-means. While related to k-means, this variant enhances computational speed and maintains exceptional clustering quality. Let's discuss its Python implementation.
Understanding the Mini-Batch Concept
In machine learning, mini-batches refer to subsets of data that are randomly selected for every algorithm iteration. This approach optimizes computational functions. Specifically for mini-batch k-means, this technique significantly accelerates the clustering process.
Generative Dataset and Preliminaries
Before delving into the mini-batch k-means implementation, we must establish preparatory functions and a working dataset. Our dataset consists of two distinct clusters. We'll calculate the Euclidean distance and randomly initialize our centroids to assign each data point to its closest centroid.
We calculate the Euclidean distance using the formula: . This formula represents the straight-line distance between two points.
This implementation of the euclidean_distance function is more versatile than the one from the previous lesson: it assumes a and b are numpy arrays with potentially multidimensional data. It calls the numpy function linalg.norm which calculates the Frobenius norm (Euclidean norm for n-dimensional space). The axis=-1 parameter means that the difference operation a - b is performed along the last axis of array, essentially allowing for multidimensional arrays to be handled.
Python Mini-Batch K-Means Algorithm
Let's put theory into practice by implementing the mini-batch k-means. The mini_batch_kMeans function accepts the following parameters:
data: Our sample dataset contains 2-dimensional coordinates representing the location of each data point.k: The number of clusters our algorithm should identify.iterations: The number of iterations that our algorithm will perform. Each iteration moves the centroids, resulting in increasingly accurate clustering with each step.batch_size: The number of data points randomly selected in each iteration. We maximize computational efficiency by not using the entire dataset in each iteration.
Our mini-batch k-means algorithm starts by initializing the centroids. Then, it enters an iterative process: in each iteration, it randomly selects a mini-batch, calculates Euclidean distances, assigns each point to the closest centroid, and recalculates the centroids based on the currently assigned points.

