From aa351b0ef5eab3ee52ae14fc6cae0342157854b8 Mon Sep 17 00:00:00 2001 From: Prateek Date: Sat, 5 Sep 2026 14:38:27 +0530 Subject: [PATCH] Fix KMeans sample weight in inertia and score --- python/cuml/cuml/cluster/kmeans.pyx | 3 ++- python/cuml/tests/test_kmeans.py | 31 +++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+), 1 deletion(-) diff --git a/python/cuml/cuml/cluster/kmeans.pyx b/python/cuml/cuml/cluster/kmeans.pyx index 61b3c1d38a..581fc5039f 100644 --- a/python/cuml/cuml/cluster/kmeans.pyx +++ b/python/cuml/cuml/cluster/kmeans.pyx @@ -1053,7 +1053,8 @@ class KMeans( params, X, sample_weight, - self.cluster_centers_ + self.cluster_centers_, + normalize_weights=False, ) handle.sync() return labels, inertia diff --git a/python/cuml/tests/test_kmeans.py b/python/cuml/tests/test_kmeans.py index 938d2a7f67..1716984d19 100644 --- a/python/cuml/tests/test_kmeans.py +++ b/python/cuml/tests/test_kmeans.py @@ -165,6 +165,37 @@ def test_weighted_kmeans(nrows, ncols, nclusters, max_weight, random_state): assert diff / avg_score <= relative_tolerance +# Regression test for issue #8530 +def test_weighted_kmeans_inertia_and_score(): + X = np.array( + [ + [0.0, 0.0], + [1.0, 1.0], + [2.0, 2.0], + [10.0, 10.0], + [11.0, 11.0], + [12.0, 12.0], + ] + ) + sample_weight = np.array([1.0, 1.0, 1.0, 2.0, 2.0, 2.0]) + + model = cuml.KMeans( + n_clusters=2, + init=np.array([[1.0, 1.0], [11.0, 11.0]]), + n_init=1, + ).fit(X, sample_weight=sample_weight) + + np.testing.assert_allclose(model.inertia_, 12.0) + + score_X = np.array([[0.0, 0.0], [10.0, 10.0]]) + score_weight = np.array([2.0, 2.0]) + + np.testing.assert_allclose( + model.score(score_X, sample_weight=score_weight), + -8.0, + ) + + @pytest.mark.parametrize("nrows", [1000, 10000]) @pytest.mark.parametrize("ncols", [25]) @pytest.mark.parametrize("nclusters", [2, 5])

AltStyle によって変換されたページ (->オリジナル) /