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:
- Inicialización: Selección aleatoria de
kcentroides iniciales. - Asignación de instancias:
- 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.
- Si no existe un clúster válido que cumpla con las restricciones, el algoritmo falla y termina sin una solución.
- Recomputación de centroides:
- Para cada clúster válido, se actualiza su centroide como la media de sus instancias asignadas.
- Repetición:
- 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 | |
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 | |
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 | |
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 | |
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 | |
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 | |