kmeans.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. # LICENSE HEADER MANAGED BY add-license-header
  2. #
  3. # Copyright 2018 Kornia Team
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License");
  6. # you may not use this file except in compliance with the License.
  7. # You may obtain a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS,
  13. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  14. # See the License for the specific language governing permissions and
  15. # limitations under the License.
  16. #
  17. # based on https://github.com/subhadarship/kmeans_pytorch
  18. from __future__ import annotations
  19. import torch
  20. from kornia.core import Tensor
  21. from kornia.core.check import KORNIA_CHECK, KORNIA_CHECK_SHAPE
  22. from kornia.geometry.linalg import euclidean_distance
  23. class KMeans:
  24. """Implements the kmeans clustering algorithm with euclidean distance as similarity measure.
  25. Args:
  26. num_clusters: number of clusters the data has to be assigned to
  27. cluster_centers: tensor of starting cluster centres can be passed instead of num_clusters
  28. tolerance: float value. the algorithm terminates if the shift in centers is less than tolerance
  29. max_iterations: number of iterations to run the algorithm for
  30. seed: number to set torch manual seed for reproducibility
  31. Example:
  32. >>> kmeans = kornia.contrib.KMeans(3, None, 10e-4, 100, 0)
  33. >>> kmeans.fit(torch.rand((1000, 5)))
  34. >>> predictions = kmeans.predict(torch.rand((10, 5)))
  35. """
  36. def __init__(
  37. self,
  38. num_clusters: int,
  39. cluster_centers: Tensor | None,
  40. tolerance: float = 10e-4,
  41. max_iterations: int = 0,
  42. seed: int | None = None,
  43. ) -> None:
  44. KORNIA_CHECK(num_clusters != 0, "num_clusters can't be 0")
  45. # cluster_centers should have only 2 dimensions
  46. if cluster_centers is not None:
  47. KORNIA_CHECK_SHAPE(cluster_centers, ["C", "D"])
  48. self.num_clusters = num_clusters
  49. self._cluster_centers = cluster_centers
  50. self.tolerance = tolerance
  51. self.max_iterations = max_iterations
  52. self._final_cluster_assignments: None | Tensor = None
  53. self._final_cluster_centers: None | Tensor = None
  54. if seed is not None:
  55. torch.manual_seed(seed)
  56. @property
  57. def cluster_centers(self) -> Tensor:
  58. if isinstance(self._final_cluster_centers, Tensor):
  59. return self._final_cluster_centers
  60. if isinstance(self._cluster_centers, Tensor):
  61. return self._cluster_centers
  62. else:
  63. raise TypeError("Model has not been fit to a dataset")
  64. @property
  65. def cluster_assignments(self) -> Tensor:
  66. if isinstance(self._final_cluster_assignments, Tensor):
  67. return self._final_cluster_assignments
  68. else:
  69. raise TypeError("Model has not been fit to a dataset")
  70. def _initialise_cluster_centers(self, X: Tensor, num_clusters: int) -> Tensor:
  71. """Chooses num_cluster points from X as the initial cluster centers.
  72. Args:
  73. X: 2D input tensor to be clustered
  74. num_clusters: number of desired cluster centers
  75. Returns:
  76. 2D Tensor with num_cluster rows
  77. """
  78. num_samples: int = len(X)
  79. perm = torch.randperm(num_samples, device=X.device)
  80. idx = perm[:num_clusters]
  81. initial_state = X[idx]
  82. return initial_state
  83. def _pairwise_euclidean_distance(self, data1: Tensor, data2: Tensor) -> Tensor:
  84. """Compute pairwise squared distance between 2 sets of vectors.
  85. Args:
  86. data1: 2D tensor of shape N, D
  87. data2: 2D tensor of shape C, D
  88. Returns:
  89. 2D tensor of shape N, C
  90. """
  91. # N*1*D
  92. A = data1[:, None, ...]
  93. # 1*C*D
  94. B = data2[None, ...]
  95. distance = euclidean_distance(A, B)
  96. return distance
  97. def fit(self, X: Tensor) -> None:
  98. """Fit iterative KMeans clustering till a threshold for shift in cluster centers or a maximum no of iterations
  99. have reached.
  100. Args:
  101. X: 2D input tensor to be clustered
  102. """ # noqa: D205
  103. # X should have only 2 dimensions
  104. KORNIA_CHECK_SHAPE(X, ["N", "D"])
  105. if self._cluster_centers is None:
  106. self._cluster_centers = self._initialise_cluster_centers(X, self.num_clusters)
  107. else:
  108. # X and cluster_centers should have same number of columns
  109. KORNIA_CHECK(
  110. X.shape[1] == self._cluster_centers.shape[1],
  111. f"Dimensions at position 1 of X and cluster_centers do not match. \
  112. {X.shape[1]} != {self._cluster_centers.shape[1]}",
  113. )
  114. # X = X.to(self.device)
  115. current_centers = self._cluster_centers
  116. previous_centers: Tensor | None = None
  117. iteration: int = 0
  118. while True:
  119. # find distance between X and current_centers
  120. distance: Tensor = self._pairwise_euclidean_distance(X, current_centers)
  121. cluster_assignment = distance.argmin(-1)
  122. previous_centers = current_centers.clone()
  123. for index in range(self.num_clusters):
  124. selected = torch.nonzero(cluster_assignment == index).squeeze()
  125. selected = torch.index_select(X, 0, selected)
  126. # edge case when a certain cluster centre has no points assigned to it
  127. # just choose a random point as it's update
  128. if selected.shape[0] == 0:
  129. selected = X[torch.randint(len(X), (1,), device=X.device)]
  130. current_centers[index] = selected.mean(dim=0)
  131. # sum of distance of how much the newly computed clusters have moved from their previous positions
  132. center_shift = torch.sum(torch.sqrt(torch.sum((current_centers - previous_centers) ** 2, dim=1)))
  133. iteration = iteration + 1
  134. if self.tolerance is not None and center_shift**2 < self.tolerance:
  135. break
  136. if self.max_iterations != 0 and iteration >= self.max_iterations:
  137. break
  138. self._final_cluster_assignments = cluster_assignment
  139. self._final_cluster_centers = current_centers
  140. def predict(self, x: Tensor) -> Tensor:
  141. """Find the cluster center closest to each point in x.
  142. Args:
  143. x: 2D tensor
  144. Returns:
  145. 1D tensor containing cluster id assigned to each data point in x
  146. """
  147. # x and cluster_centers should have same number of columns
  148. KORNIA_CHECK(
  149. x.shape[1] == self.cluster_centers.shape[1],
  150. f"Dimensions at position 1 of x and cluster_centers do not match. \
  151. {x.shape[1]} != {self.cluster_centers.shape[1]}",
  152. )
  153. distance = self._pairwise_euclidean_distance(x, self.cluster_centers)
  154. cluster_assignment = distance.argmin(-1)
  155. return cluster_assignment