Skip to content

COP-KMeans

Descripción General

COP-KMeans (Constrained K-Means) es un algoritmo clásico de clustering con restricciones propuesto por Wagstaff et al. (2001). Se basa en el algoritmo K-Means tradicional, pero incorpora información adicional en forma de restricciones de tipo must-link (ML) y cannot-link (CL) para guiar el proceso de particionado de los datos.

Las restricciones ML indican que dos instancias deben estar en el mismo clúster, mientras que las CL indican que dos instancias no deben estar en el mismo clúster. Estas restricciones se consideran duras (hard constraints), es decir, el algoritmo solamente considera válidas aquellas asignaciones que las satisfacen por completo.

Funcionamiento del Algoritmo

El algoritmo sigue la estructura general del K-Means clásico, con la diferencia de que incorpora un paso de validación de restricciones en la fase de asignación. Los pasos básicos son:

  1. Inicialización: Selección aleatoria de k centroides iniciales.
  2. Asignación de instancias:
  3. Cada instancia se asigna al centroide más cercano si y solo si no viola ninguna restricción (ML o CL) con las instancias previamente asignadas.
  4. Si no existe un clúster válido que cumpla con las restricciones, el algoritmo falla y termina sin una solución.
  5. Recomputación de centroides:
  6. Para cada clúster válido, se actualiza su centroide como la media de sus instancias asignadas.
  7. Repetición:
  8. Se repiten los pasos de asignación y actualización de centroides hasta la convergencia (sin cambios en las asignaciones) o un número máximo de iteraciones.

Formalización

  • Dado un conjunto de datos: $$ X = {x_1, x_2, \dots, x_n} \subset \mathbb{R}^d $$
  • Un número de clústers: $$ k $$
  • Dos conjuntos de restricciones: $$ ML \subset X \times X $$ $$ CL \subset X \times X $$

El objetivo es encontrar una partición \( C = \{C_1, \dots, C_k\} \) tal que:

  • Se minimice la suma de errores cuadráticos intra-clúster: \( \sum_{i=1}^{k} \sum_{x \in C_i} \| x - \mu_i \|^2 \) donde \( \mu_i \) es el centroide de \( C_i \),
  • respetando las restricciones en \( ML \cup CL \).

API

Bases: BaseEstimator

Constrained Partitioning K-Means (COP-KMeans) estimator.

KMeans estimator is a clustering algorithm that aims to partition n observations into k clusters in which each observation belongs to the cluster with the nearest mean, serving as a prototype of the cluster. This results in a partitioning of the data space into Voronoi cells.

Attributes:

Name Type Description
n_clusters int

The number of clusters to form as well as the number of centroids to generate.

init

str, optional): Method for initialization, defaults to 'random' choose k observations (rows) at random from data for the initial centroids. 'custom' use custom_initial_centroids as initial centroids.

max_iter int

Maximum number of iterations of the k-means algorithm for a single run.

tol float

Relative tolerance with regards to Frobenius norm of the difference in the cluster centers of two consecutive iterations to declare convergence.

custom_initial_centroids ndarray

Custom initial centroids to be used in the initialization. Only used if init='custom'.

Source code in clustlib/kmean/copkmeans.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
class COPKMeans(BaseEstimator):
    """Constrained Partitioning K-Means (COP-KMeans) estimator.

    KMeans estimator is a clustering algorithm that aims to partition n observations
    into k clusters in which each observation belongs to the cluster with the nearest
    mean, serving as a prototype of the cluster. This results in a partitioning of
    the data space into Voronoi cells.

    Attributes:
        n_clusters (int, optional): The number of clusters to form as well as the
            number of centroids to generate.
        init (:str, optional): Method for initialization, defaults to 'random' choose
            k observations (rows) at random from data for the initial centroids.
            'custom' use custom_initial_centroids as initial centroids.
        max_iter (int, optional): Maximum number of iterations of the k-means algorithm
            for a single run.
        tol (float, optional): Relative tolerance with regards to Frobenius norm of the
            difference in the cluster centers of two consecutive iterations to declare
            convergence.
        custom_initial_centroids (numpy.ndarray, optional): Custom initial centroids to
            be used in the initialization. Only used if init='custom'.

    """

    def __init__(
        self,
        constraints: Sequence[Sequence],
        n_clusters=8,
        init="random",
        distance="euclidean",
        max_iter=300,
        tol=1e-10,
        custom_initial_centroids=None,
    ):
        self.n_clusters = n_clusters
        self._centroids_distance = np.zeros((self.n_clusters, self.n_clusters))
        self.init = init
        self.max_iter = max_iter
        self.tol = tol
        self.custom_initial_centroids = custom_initial_centroids
        self.centroids = None
        self.distance = match_distance(distance)
        self._labels = None
        self.constraints = SimpleConstraints(constraints)

    def initialize_bounds(self):
        """Initialize the lower and upper bounds for each instance.

        Calculate the distance to each of the centroids in the
        cluster. After that, it will assign the closest centroid to each instance and
        apply the constraints to make sure that the instances respect the limitations.

        In case of conflict, the instance that is closer to the centroid will be kept,
        and the other will be moved to the next closest centroid.

        Note:
            This method applies the constraints in a soft manner. Which means that the
            instances might be missclassified after the initialization.

        Args:
            dataset (ndarray): Training instances to cluster.

        Returns:
            numpy.ndarray: Lower bounds for each instance.
            numpy.ndarray: Upper bounds for each instance.

        """
        logger.debug("Initializing bounds for COPKMeans")
        lower_bounds = np.zeros((self.X.shape[0], self.n_clusters))
        upper_bounds = np.zeros((self.X.shape[0]))

        # Initialize lower and upper bounds
        for instance_index, instance in enumerate(self.X):
            for centroid_index, centroid in enumerate(self.centroids):
                lower_bounds[instance_index, centroid_index] = np.linalg.norm(
                    instance - centroid
                )

            # Get the closest centroid to the instance
            self._labels[instance_index] = lower_bounds[instance_index, :].argmin()

            upper_bounds[instance_index] = np.min(
                lower_bounds[instance_index, self._labels[instance_index]]
            )

        # Apply the constraints to the newly created bounds and labels
        for instance_index in range(self.X.shape[0]):
            constraints = self.constraints[instance_index]
            ml_constraints = np.argwhere(constraints > 0).flatten()
            cl_constraints = np.argwhere(constraints < 0).flatten()

            for (
                ml_constraint
            ) in ml_constraints:  # Soft ML constraints, it can be violated
                if self._labels[ml_constraint] != self._labels[instance_index]:
                    if upper_bounds[instance_index] > upper_bounds[ml_constraint]:
                        self._labels[instance_index] = self._labels[ml_constraint]
                        upper_bounds[instance_index] = lower_bounds[
                            instance_index, self._labels[ml_constraint]
                        ]
                    else:
                        self._labels[ml_constraint] = self._labels[instance_index]
                        upper_bounds[ml_constraint] = lower_bounds[
                            ml_constraint, self._labels[instance_index]
                        ]

            for cl_constraint in cl_constraints:
                if self._labels[cl_constraint] == self._labels[instance_index]:
                    if upper_bounds[instance_index] > upper_bounds[cl_constraint]:
                        lower_bounds[
                            instance_index, self._labels[instance_index]
                        ] = np.inf
                        new_centroid = lower_bounds[instance_index, :].argmin()
                        self._labels[instance_index] = new_centroid
                        upper_bounds[instance_index] = lower_bounds[
                            instance_index, new_centroid
                        ]
                    else:
                        lower_bounds[
                            cl_constraint, self._labels[cl_constraint]
                        ] = np.inf
                        new_centroid = lower_bounds[cl_constraint, :].argmin()
                        self._labels[cl_constraint] = new_centroid
                        upper_bounds[cl_constraint] = lower_bounds[
                            cl_constraint, new_centroid
                        ]

        return lower_bounds, upper_bounds

    def _fit(self):
        """Fit the model to the data."""
        self._lower_bounds, self._upper_bounds = self.initialize_bounds()

        logger.debug("Starting the iterations for COPKMeans")

        start = time()
        iteration = 0
        while not self.stop_criteria(iteration):
            iteration += 1
            logger.debug(f"Iteration {iteration} of {self.max_iter} for COPKMeans")

            self.update()

        logger.debug(f"COPKMeans finished after {time() - start:.2f}")

    def get_centroids(self, idx):
        """Get the valid centroids for the instance.

        This method checks the constraints for the instance and returns the valid
        centroids.

        Args:
            idx(int): The index of the instance to check.

        Returns:
            numpy.ndarray: The valid centroids for the instance.

        """
        constraints = self.constraints[idx]
        ml = np.argwhere(constraints > 0).flatten()
        cl = np.argwhere(constraints < 0).flatten()

        if ml is not None and len(ml) > 0:
            logger.debug(f"Instance {idx} has must-be-link constraints: {len(ml)}")
            labels = np.unique(self._labels[ml])
            return labels

        if cl is not None and len(cl) > 0:
            labels = np.unique(self._labels[cl])
            valid_centroids = np.delete(np.arange(self.n_clusters), labels)
            return valid_centroids

        return np.arange(self.n_clusters)

    def update_label(self, idx):
        """Update the instances labels.

        This method follows the Elkan's algorithm to update the labels of the instances.

        Args:
            idx (int): The index of the instance to update.

        """
        instance = np.copy(self.X[idx])
        valid_centroids = self.get_centroids(idx)

        if len(valid_centroids) == 0:
            raise ValueError("Invalid set of centroids")

        self._lower_bounds[
            idx, np.isin(np.arange(self.n_clusters), valid_centroids, invert=True)
        ] = np.inf

        if len(valid_centroids) == 1:
            centroid = valid_centroids[0]
            distance = self.distance(instance - self.centroids[centroid])
            self._labels[idx] = centroid
            self._upper_bounds[idx] = distance
            self._lower_bounds[idx, centroid] = distance
            return

        current_distance = self._upper_bounds[idx]
        current_centroid = self._labels[idx]
        closest_centroid = self._centroids_distance[current_centroid, :].argmin()
        min_distance = self._centroids_distance[current_centroid, closest_centroid]

        if current_centroid == closest_centroid:
            # The centroid is choosing itself again, we should update the instance
            # to keep him off
            self._centroids_distance[current_centroid, closest_centroid] = np.inf
            closest_centroid = self._centroids_distance[current_centroid, :].argmin()
            min_distance = self._centroids_distance[current_centroid, closest_centroid]

        if current_distance > 0.5 * min_distance:
            # Set the instance to the current centroid
            logger.debug(f"Instance {idx} is too far from {current_centroid}")
            for centroid_index in valid_centroids:
                logger.debug(f"Checking candidate {centroid_index} for instance {idx}")
                candidate = self.centroids[centroid_index]
                current = self.centroids[self._labels[idx]]

                # Check if the current distance must be updated
                if self.should_check_centroid(self._labels[idx], centroid_index, idx):
                    logger.debug(
                        f"Checking instance {idx} with centroid {centroid_index} "
                        f"and current centroid {self._labels[idx]}"
                    )
                    distance_to_candidate = self.distance(instance - candidate)
                    distance_to_current_centroid = self.distance(instance - current)

                    if distance_to_candidate < distance_to_current_centroid:
                        logger.debug(f"Updating instance {idx} to {centroid_index}")
                        self._labels[idx] = centroid_index
                        self._upper_bounds[idx] = distance_to_candidate

                    self._lower_bounds[idx, centroid_index] = distance_to_candidate
                    self._lower_bounds[idx, current_centroid] = current_distance

    def _update(self):
        """Update.

        Get the instances belonging to each cluster and update the centroids,
        and upper and lower bounds.

        Args:
            X (numpy.ndarray): Training instances to cluster.

        """
        old = np.copy(self.centroids)

        for label in range(self.n_clusters):
            self.centroids[label] = np.copy(
                self.X[np.where(self._labels == label)].mean(axis=0)
            )
            logger.debug(f"Centroid {label} updated to {self.centroids[label]}")

            intracentroid_diff = self.centroids - self.centroids[label]
            self._centroids_distance[:, label] = self.distance(
                intracentroid_diff, axis=1
            )

        if self._delta is None:
            self._delta = self.calculte_delta(old)

        self.update_bounds()

    def update_bounds(self):
        """Update lower and upper bounds for each instance.

        Args:
            X (numpy.ndarray): Training instances to cluster.

        """
        distance = self.distance(self._delta, axis=1)

        logger.debug(f"Updating bounds with delta: {distance}")

        for centroids_index in range(self.n_clusters):
            members = np.where(self._labels == centroids_index)
            self._upper_bounds[members] += distance[centroids_index]
            self._lower_bounds[members, :] -= distance[centroids_index]

        for idx in range(self.X.shape[0]):
            self.update_label(idx)

    def should_check_centroid(self, centroid_index, candidate_centroid, idx):
        """Check if the candidate centroid is a valid option for the instance.

        Args:
            centroid_index (int):The current centroid index.
            candidate_centroid (int): The candidate centroid index.
            idx (int): The instance index.

        Returns:
            boolean: True if the candidate centroid is a valid option for the
            instance, False otherwise.

        """
        half_distance = (
            0.5 * self._centroids_distance[centroid_index, candidate_centroid]
        )
        return (
            self._upper_bounds[idx] > self._lower_bounds[idx, candidate_centroid]
        ) and (self._upper_bounds[idx] > half_distance)

get_centroids(idx)

Get the valid centroids for the instance.

This method checks the constraints for the instance and returns the valid centroids.

Parameters:

Name Type Description Default
idx(int)

The index of the instance to check.

required

Returns:

Type Description

numpy.ndarray: The valid centroids for the instance.

Source code in clustlib/kmean/copkmeans.py
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def get_centroids(self, idx):
    """Get the valid centroids for the instance.

    This method checks the constraints for the instance and returns the valid
    centroids.

    Args:
        idx(int): The index of the instance to check.

    Returns:
        numpy.ndarray: The valid centroids for the instance.

    """
    constraints = self.constraints[idx]
    ml = np.argwhere(constraints > 0).flatten()
    cl = np.argwhere(constraints < 0).flatten()

    if ml is not None and len(ml) > 0:
        logger.debug(f"Instance {idx} has must-be-link constraints: {len(ml)}")
        labels = np.unique(self._labels[ml])
        return labels

    if cl is not None and len(cl) > 0:
        labels = np.unique(self._labels[cl])
        valid_centroids = np.delete(np.arange(self.n_clusters), labels)
        return valid_centroids

    return np.arange(self.n_clusters)

initialize_bounds()

Initialize the lower and upper bounds for each instance.

Calculate the distance to each of the centroids in the cluster. After that, it will assign the closest centroid to each instance and apply the constraints to make sure that the instances respect the limitations.

In case of conflict, the instance that is closer to the centroid will be kept, and the other will be moved to the next closest centroid.

Note

This method applies the constraints in a soft manner. Which means that the instances might be missclassified after the initialization.

Parameters:

Name Type Description Default
dataset ndarray

Training instances to cluster.

required

Returns:

Type Description

numpy.ndarray: Lower bounds for each instance.

numpy.ndarray: Upper bounds for each instance.

Source code in clustlib/kmean/copkmeans.py
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
def initialize_bounds(self):
    """Initialize the lower and upper bounds for each instance.

    Calculate the distance to each of the centroids in the
    cluster. After that, it will assign the closest centroid to each instance and
    apply the constraints to make sure that the instances respect the limitations.

    In case of conflict, the instance that is closer to the centroid will be kept,
    and the other will be moved to the next closest centroid.

    Note:
        This method applies the constraints in a soft manner. Which means that the
        instances might be missclassified after the initialization.

    Args:
        dataset (ndarray): Training instances to cluster.

    Returns:
        numpy.ndarray: Lower bounds for each instance.
        numpy.ndarray: Upper bounds for each instance.

    """
    logger.debug("Initializing bounds for COPKMeans")
    lower_bounds = np.zeros((self.X.shape[0], self.n_clusters))
    upper_bounds = np.zeros((self.X.shape[0]))

    # Initialize lower and upper bounds
    for instance_index, instance in enumerate(self.X):
        for centroid_index, centroid in enumerate(self.centroids):
            lower_bounds[instance_index, centroid_index] = np.linalg.norm(
                instance - centroid
            )

        # Get the closest centroid to the instance
        self._labels[instance_index] = lower_bounds[instance_index, :].argmin()

        upper_bounds[instance_index] = np.min(
            lower_bounds[instance_index, self._labels[instance_index]]
        )

    # Apply the constraints to the newly created bounds and labels
    for instance_index in range(self.X.shape[0]):
        constraints = self.constraints[instance_index]
        ml_constraints = np.argwhere(constraints > 0).flatten()
        cl_constraints = np.argwhere(constraints < 0).flatten()

        for (
            ml_constraint
        ) in ml_constraints:  # Soft ML constraints, it can be violated
            if self._labels[ml_constraint] != self._labels[instance_index]:
                if upper_bounds[instance_index] > upper_bounds[ml_constraint]:
                    self._labels[instance_index] = self._labels[ml_constraint]
                    upper_bounds[instance_index] = lower_bounds[
                        instance_index, self._labels[ml_constraint]
                    ]
                else:
                    self._labels[ml_constraint] = self._labels[instance_index]
                    upper_bounds[ml_constraint] = lower_bounds[
                        ml_constraint, self._labels[instance_index]
                    ]

        for cl_constraint in cl_constraints:
            if self._labels[cl_constraint] == self._labels[instance_index]:
                if upper_bounds[instance_index] > upper_bounds[cl_constraint]:
                    lower_bounds[
                        instance_index, self._labels[instance_index]
                    ] = np.inf
                    new_centroid = lower_bounds[instance_index, :].argmin()
                    self._labels[instance_index] = new_centroid
                    upper_bounds[instance_index] = lower_bounds[
                        instance_index, new_centroid
                    ]
                else:
                    lower_bounds[
                        cl_constraint, self._labels[cl_constraint]
                    ] = np.inf
                    new_centroid = lower_bounds[cl_constraint, :].argmin()
                    self._labels[cl_constraint] = new_centroid
                    upper_bounds[cl_constraint] = lower_bounds[
                        cl_constraint, new_centroid
                    ]

    return lower_bounds, upper_bounds

should_check_centroid(centroid_index, candidate_centroid, idx)

Check if the candidate centroid is a valid option for the instance.

Parameters:

Name Type Description Default
centroid_index int

The current centroid index.

required
candidate_centroid int

The candidate centroid index.

required
idx int

The instance index.

required

Returns:

Name Type Description
boolean

True if the candidate centroid is a valid option for the

instance, False otherwise.

Source code in clustlib/kmean/copkmeans.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
def should_check_centroid(self, centroid_index, candidate_centroid, idx):
    """Check if the candidate centroid is a valid option for the instance.

    Args:
        centroid_index (int):The current centroid index.
        candidate_centroid (int): The candidate centroid index.
        idx (int): The instance index.

    Returns:
        boolean: True if the candidate centroid is a valid option for the
        instance, False otherwise.

    """
    half_distance = (
        0.5 * self._centroids_distance[centroid_index, candidate_centroid]
    )
    return (
        self._upper_bounds[idx] > self._lower_bounds[idx, candidate_centroid]
    ) and (self._upper_bounds[idx] > half_distance)

update_bounds()

Update lower and upper bounds for each instance.

Parameters:

Name Type Description Default
X ndarray

Training instances to cluster.

required
Source code in clustlib/kmean/copkmeans.py
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
def update_bounds(self):
    """Update lower and upper bounds for each instance.

    Args:
        X (numpy.ndarray): Training instances to cluster.

    """
    distance = self.distance(self._delta, axis=1)

    logger.debug(f"Updating bounds with delta: {distance}")

    for centroids_index in range(self.n_clusters):
        members = np.where(self._labels == centroids_index)
        self._upper_bounds[members] += distance[centroids_index]
        self._lower_bounds[members, :] -= distance[centroids_index]

    for idx in range(self.X.shape[0]):
        self.update_label(idx)

update_label(idx)

Update the instances labels.

This method follows the Elkan's algorithm to update the labels of the instances.

Parameters:

Name Type Description Default
idx int

The index of the instance to update.

required
Source code in clustlib/kmean/copkmeans.py
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
def update_label(self, idx):
    """Update the instances labels.

    This method follows the Elkan's algorithm to update the labels of the instances.

    Args:
        idx (int): The index of the instance to update.

    """
    instance = np.copy(self.X[idx])
    valid_centroids = self.get_centroids(idx)

    if len(valid_centroids) == 0:
        raise ValueError("Invalid set of centroids")

    self._lower_bounds[
        idx, np.isin(np.arange(self.n_clusters), valid_centroids, invert=True)
    ] = np.inf

    if len(valid_centroids) == 1:
        centroid = valid_centroids[0]
        distance = self.distance(instance - self.centroids[centroid])
        self._labels[idx] = centroid
        self._upper_bounds[idx] = distance
        self._lower_bounds[idx, centroid] = distance
        return

    current_distance = self._upper_bounds[idx]
    current_centroid = self._labels[idx]
    closest_centroid = self._centroids_distance[current_centroid, :].argmin()
    min_distance = self._centroids_distance[current_centroid, closest_centroid]

    if current_centroid == closest_centroid:
        # The centroid is choosing itself again, we should update the instance
        # to keep him off
        self._centroids_distance[current_centroid, closest_centroid] = np.inf
        closest_centroid = self._centroids_distance[current_centroid, :].argmin()
        min_distance = self._centroids_distance[current_centroid, closest_centroid]

    if current_distance > 0.5 * min_distance:
        # Set the instance to the current centroid
        logger.debug(f"Instance {idx} is too far from {current_centroid}")
        for centroid_index in valid_centroids:
            logger.debug(f"Checking candidate {centroid_index} for instance {idx}")
            candidate = self.centroids[centroid_index]
            current = self.centroids[self._labels[idx]]

            # Check if the current distance must be updated
            if self.should_check_centroid(self._labels[idx], centroid_index, idx):
                logger.debug(
                    f"Checking instance {idx} with centroid {centroid_index} "
                    f"and current centroid {self._labels[idx]}"
                )
                distance_to_candidate = self.distance(instance - candidate)
                distance_to_current_centroid = self.distance(instance - current)

                if distance_to_candidate < distance_to_current_centroid:
                    logger.debug(f"Updating instance {idx} to {centroid_index}")
                    self._labels[idx] = centroid_index
                    self._upper_bounds[idx] = distance_to_candidate

                self._lower_bounds[idx, centroid_index] = distance_to_candidate
                self._lower_bounds[idx, current_centroid] = current_distance