A clean, fully vectorized implementation of the K-Means clustering algorithm built from scratch using only NumPy, designed with a scikit-learn-compatible API (fit, predict, fit_predict).
-
Zero ML Dependencies: Implemented strictly with NumPy matrix broadcasting (
x[:, np.newaxis] - centroids)—noscikit-learnorscipyused in the core engine. - Empty Cluster Handling: Safely retains previous centroid coordinates if a cluster receives zero points during an iteration.
-
Elbow Method Utility: Built-in WCSS (Within-Cluster Sum of Squares / Inertia) evaluator to determine the optimal number of clusters (
$K$ ). -
Unit Tested: Verified with
pytestacross edge cases, output tensor shapes, and cluster separability.
numpy-kmeans-from-scratch/
├── assets/
│ ├── clustering_result.png
│ └── elbow_method.png
├── src/
│ ├── __init__.py
│ ├── kmeans.py # Core vectorized KMeans estimator
│ └── metrics.py # Elbow method WCSS computation
├── tests/
│ └── test_kmeans.py # Pytest unit test suite
├── benchmark.py # Pure Python vs. NumPy performance benchmark
├── demo.py # Synthetic dataset generation & visualization
└── README.md