K-Means & Mini-Batch K-Means

๐Ÿ“– Introduction

K-Means is one of the most popular unsupervised machine learning algorithms used for clustering. It groups similar data points into K distinct clusters by minimizing the distance between data points and their corresponding cluster centroids.

Mini-Batch K-Means is an optimized version of K-Means that processes small random subsets (mini-batches) of the dataset instead of the entire dataset during each iteration. This significantly reduces training time while producing clustering results similar to standard K-Means.

Information

K-Means is best suited for relatively small to medium-sized datasets, while Mini-Batch K-Means is designed for large-scale datasets where computational efficiency is important.

๐ŸŽฏ Learning Objectives

  • Understand clustering and unsupervised learning.
  • Learn how K-Means partitions data into clusters.
  • Understand the Mini-Batch K-Means optimization.
  • Compare K-Means and Mini-Batch K-Means.

๐ŸŒŸ What is Clustering?

Clustering is an unsupervised learning technique that groups similar observations together without using labeled target values.

Supervised LearningUnsupervised Learning
Uses labeled data.Uses unlabeled data.
Predicts target values.Discovers hidden groups or patterns.
Classification & Regression.Clustering & Dimensionality Reduction.

๐Ÿ“Š K-Means Algorithm

K-Means partitions the dataset into K clusters by iteratively assigning each observation to the nearest centroid and then updating the centroid positions until convergence.

Objective Function

Where:

  • K โ€” Number of clusters.
  • Cแตข โ€” Cluster i.
  • ฮผแตข โ€” Centroid of cluster i.
  • ||x-ฮผแตข||ยฒ โ€” Squared Euclidean distance between a point and its centroid.

Remember

The objective of K-Means is to minimize the Within-Cluster Sum of Squares (WCSS), also known as inertia.

โš™๏ธ How K-Means Works

๐ŸŒณ K-Means Workflow

Select K
Initialize Centroids
Assign Data Points
Update Centroids
Check Convergence
Final Clusters

๐Ÿš€ Mini-Batch K-Means

Mini-Batch K-Means improves computational efficiency by updating centroids using randomly selected mini-batches rather than the full dataset during every iteration.

Tip

Mini-Batch K-Means provides clustering quality close to standard K-Means while significantly reducing computation time on very large datasets.

๐Ÿ“Š K-Means vs Mini-Batch K-Means

FeatureK-MeansMini-Batch K-Means
Training DataEntire datasetRandom mini-batches
Training SpeedSlowerMuch Faster
Memory UsageHigherLower
Clustering AccuracyHighestVery Similar
Best ForSmall & Medium datasetsLarge datasets

๐ŸŽฏ Choosing the Number of Clusters

Elbow Method

Plot the Within-Cluster Sum of Squares (WCSS) against different values of K. The optimal number of clusters is often located at the "elbow" point where further increases in K provide diminishing improvements.

Silhouette Score

The Silhouette Score measures how similar a data point is to its own cluster compared to other clusters.

Higher values indicate better-defined clusters.

๐Ÿ“ Distance Measure

K-Means primarily uses Euclidean Distance to determine the nearest centroid.

๐ŸŽ›๏ธ Important Hyperparameters

HyperparameterDescription
n_clustersNumber of clusters.
initCentroid initialization method (e.g., K-Means++).
max_iterMaximum number of iterations.
batch_sizeMini-batch size (Mini-Batch K-Means).
random_stateControls reproducibility.

๐Ÿ“Š Evaluation Metrics

  • Within-Cluster Sum of Squares (WCSS / Inertia)
  • Silhouette Score
  • Davies-Bouldin Index
  • Calinski-Harabasz Index

โš–๏ธ Advantages and Limitations

  • Simple and easy to implement.
  • Fast convergence.
  • Efficient for large numerical datasets.
  • Mini-Batch K-Means scales to massive datasets.
  • Works well for compact, spherical clusters.
  • Requires the number of clusters to be specified beforehand.
  • Sensitive to centroid initialization.
  • Assumes clusters are roughly spherical and similar in size.
  • Sensitive to outliers.
  • Primarily designed for numerical features.

๐ŸŒ Real-World Applications

ApplicationPurpose
๐Ÿ›’ Customer SegmentationGroup customers based on purchasing behavior.
๐Ÿ–ผ๏ธ Image CompressionReduce the number of image colors.
๐Ÿ“„ Document ClusteringOrganize similar documents.
๐Ÿงฌ BioinformaticsCluster genes with similar expression patterns.
๐Ÿ“ก Network Traffic AnalysisIdentify usage patterns and anomalies.
๐Ÿ“ˆ Market ResearchDiscover hidden consumer groups.

๐Ÿ’ป Practical Example

K-Means and Mini-Batch K-Means Using Scikit-learn

from sklearn.cluster import KMeans
from sklearn.cluster import MiniBatchKMeans
import numpy as np

# Sample data
X = np.array([
    [1, 2], [1, 3], [2, 2],
    [8, 8], [9, 8], [8, 9]
])

# K-Means
kmeans = KMeans(
    n_clusters=2,
    random_state=42
)

kmeans.fit(X)

# Mini-Batch K-Means
mini = MiniBatchKMeans(
    n_clusters=2,
    batch_size=3,
    random_state=42
)

mini.fit(X)

print("K-Means Labels:", kmeans.labels_)
print("Mini-Batch Labels:", mini.labels_)
print("Cluster Centers:")
print(kmeans.cluster_centers_)

โš ๏ธ Common Mistakes

  • Choosing an inappropriate value for K.
  • Ignoring feature scaling before clustering.
  • Using K-Means on categorical features without suitable encoding.
  • Assuming clusters of arbitrary shapes can be identified accurately.
  • Ignoring the impact of outliers on centroid positions.

Best Practice

Standardize numerical features before clustering, initialize centroids using K-Means++, determine the optimal number of clusters using the Elbow Method or Silhouette Score, and choose Mini-Batch K-Means when working with very large datasets to improve training efficiency with minimal loss in clustering quality.

๐Ÿ“š Summary

Summary

K-Means is one of the most widely used unsupervised learning algorithms for clustering numerical data by minimizing the distance between observations and cluster centroids. Mini-Batch K-Means extends this approach by updating centroids using small random subsets of the data, making it significantly faster and more memory-efficient for large-scale datasets. Both algorithms are simple, scalable, and widely applied in customer segmentation, image processing, document organization, and pattern discovery.

๐Ÿ”— Further Reading