Skip to content

BisectingKmeans - intertia per cluster #27236

Closed

Description

@EdouardYvinec

Describe the bug

Hi,

I have been using the sklearn package recently for some simple clustering. It appears to me that there is a typo in the BisectingKMeans class. In the _inertia_per_cluster method, we need to compute the inertia per-cluster. However, in the current version of the package we have the following:

inertia_per_cluster = np.empty(centers.shape[1])
for label in range(centers.shape[0]):
  inertia_per_cluster[label] = ...

This will through an error unless the centers form a squared matrix, i.e. if we have the same number of clusters as we have scalar features... In order to solve this, we could simply replace the line 276 in the corresponding file with:

inertia_per_cluster = np.empty(centers.shape[0]) # <- instead of [1]

Steps/Code to Reproduce

import numpy as np
from sklearn.cluster import BisectingKMeans

lut_size = 4
w = np.random.normal(size=(128,))
kmeans = BisectingKMeans(
    n_clusters=lut_size, random_state=0
).fit(w.reshape(-1, 1))

Expected Results

no error should be thrown

Actual Results

IndexError: index 1 is out of bounds for axis 0 with size 1

Versions

Python dependencies:
      sklearn: 1.3.0
          pip: 23.2.1
   setuptools: 68.0.0
        numpy: 1.25.2
        scipy: 1.11.2
       Cython: None
       pandas: 2.0.3
   matplotlib: 3.7.2
       joblib: 1.3.2
threadpoolctl: 3.2.0

Activity

  1. added
    Needs Triage
    on Aug 30, 2023
  2. jeremiedbb commented on Aug 30, 2023

    @jeremiedbb
    Member

    Thanks for the report @EdouardYvinec. To be more precise, this function is only called after a bisection so there are always exactly 2 clusters, meaning that the issue only happens when n_features=1. I opened #27243 to fix it.

  3. removed
    Needs Triage
    on Aug 30, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions