Skip to content

Optimize K-means - #433

Open
andrewdalpino wants to merge 2 commits into
masterfrom
optimize-k-means
Open

Optimize K-means#433
andrewdalpino wants to merge 2 commits into
masterfrom
optimize-k-means

Conversation

@andrewdalpino

Copy link
Copy Markdown
Member

KMeans inertia() recomputes distances already computed in predictSample — src/Clusterers/KMeans.php:366. Reuse the per-batch distance matrix for both assignment and loss. ~2× epoch cost.

mean stddev
before 1.494s ±23.98%
after 1.167s ±20.84%
Δ −21.86%  

@andrewdalpino
andrewdalpino requested review from a team and a lite review from Copilot August 22, 2026 18:53

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

This PR optimizes KMeans training by reusing per-batch centroid distance computations for both cluster assignment and inertia (loss) calculation, reducing redundant kernel distance evaluations during mini-batch updates.

Changes:

  • Precompute a per-batch distance matrix and reuse it for both label assignment (argmin) and inertia accumulation.
  • Refactor predictSample() to use a new centroidDistances() helper and update inertia() to operate on distance rows.
  • Add a PhpBench storage XML benchmark output file.

Reviewed changes

Copilot reviewed 1 out of 1 changed files in this pull request and generated 1 comment.

File Description
src/Clusterers/KMeans.php Reuses computed centroid distances for assignments and inertia; introduces centroidDistances() and updates inertia() signature.
.phpbench/storage/7ea/8/16/13527d6169bfd8433ae290209f045b245f19565d.xml Adds a generated benchmark artifact containing environment metadata.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread src/Clusterers/KMeans.php
@andrewdalpino andrewdalpino added the optimization Make something perform faster label Aug 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

optimization Make something perform faster

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants