Skip to content

Commit 1d10a34

Browse files
ratgrtensorflower-gardener
authored andcommitted
Fix RandomCentroidsInitialisation to safely handle cases where zero clusters are requested for a weight interval.
PiperOrigin-RevId: 925483764
1 parent c575e8d commit 1d10a34

2 files changed

Lines changed: 5 additions & 1 deletion

File tree

tensorflow_model_optimization/python/core/clustering/keras/clustering_centroids.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,6 @@ class LinearCentroidsInitialisation(AbstractCentroidsInitialisation):
212212
def _calculate_centroids_for_interval(self, weight_interval,
213213
number_of_clusters_for_interval):
214214
if tf.math.less_equal(number_of_clusters_for_interval, 0):
215-
# Return an empty array of centroids
216215
return tf.constant([])
217216

218217
weight_min = tf.reduce_min(weight_interval)
@@ -247,6 +246,10 @@ class RandomCentroidsInitialisation(AbstractCentroidsInitialisation):
247246

248247
def _calculate_centroids_for_interval(self, weight_interval,
249248
number_of_clusters_for_interval):
249+
if tf.math.less_equal(number_of_clusters_for_interval, 0):
250+
# Return an empty array of centroids
251+
return tf.constant([])
252+
250253
weight_min = tf.reduce_min(weight_interval)
251254
weight_max = tf.reduce_max(weight_interval)
252255
cluster_centroids = tf.random.uniform(

tensorflow_model_optimization/python/core/clustering/keras/clustering_centroids_test.py

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -192,6 +192,7 @@ def testDensityBasedClusterCentroidsWithSparsityPreservation(
192192
@parameterized.parameters(
193193
([0., 1., 2., 3., 4., 5., 6., 7., 8., 9., 10.], 5),
194194
([0., 1., 2., 3., 3.1, 3.2, 3.3, 3.4, 3.5], 3),
195+
([1.0, 2.0, 3.0], 3),
195196
([-3., -2., -1., 0., 1.1, 2.2, 3.3, 4.4, 5.5, 6.6, 7.7, 8.8, 9.], 6))
196197
def testRandomClusterCentroidsWithSparsityPreservation(
197198
self, weights, number_of_clusters):

0 commit comments

Comments
 (0)