⚡️ Speed up function kmeans_clustering by 2,821%
#254
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
📄 2,821% (28.21x) speedup for
kmeans_clusteringinsrc/statistics/clustering.py⏱️ Runtime :
475 milliseconds→16.3 milliseconds(best of145runs)📝 Explanation and details
The optimized code achieves a 28x speedup (2821%) by replacing nested Python loops with vectorized NumPy operations. Here's why it's faster:
Key Optimizations
1. Vectorized Distance Calculation
2. Vectorized Label Assignment
labels = np.argmin(distances, axis=1)finds all minimum distances in one operation3. Vectorized Centroid Updates
mean()operationPerformance Impact
The optimization excels with larger datasets:
The line profiler shows the optimized version spends most time (38.5%) on the
X[mask].mean()operation and distance calculations (23.2%), both of which are highly optimized C operations. The original spent 60%+ of time on raw Python loops for distance calculations.This optimization is particularly valuable in hot paths where k-means runs repeatedly (hyperparameter tuning, batch processing) or with high-dimensional data, as evidenced by the massive speedups in large-scale test cases.
✅ Correctness verification report:
🌀 Click to see Generated Regression Tests
To edit these changes
git checkout codeflash/optimize-kmeans_clustering-mkafkgr5and push.