Skip to content

Commit 6e568f5

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

2 files changed

Lines changed: 5 additions & 0 deletions

File tree

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

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -247,6 +247,10 @@ class RandomCentroidsInitialisation(AbstractCentroidsInitialisation):
247247

248248
def _calculate_centroids_for_interval(self, weight_interval,
249249
number_of_clusters_for_interval):
250+
if tf.math.less_equal(number_of_clusters_for_interval, 0):
251+
# Return an empty array of centroids
252+
return tf.constant([])
253+
250254
weight_min = tf.reduce_min(weight_interval)
251255
weight_max = tf.reduce_max(weight_interval)
252256
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)