Cluster points based on similarity. Args: similarity (np.ndarray): The similarity matrix. sim_bound (float): The similarity threshold for clustering. Returns: list: A list of clusters.
(similarity: np.ndarray, sim_bound: float = 0.65)
| 249 | |
| 250 | |
| 251 | def get_cluster(similarity: np.ndarray, sim_bound: float = 0.65): |
| 252 | """ |
| 253 | Cluster points based on similarity. |
| 254 | |
| 255 | Args: |
| 256 | similarity (np.ndarray): The similarity matrix. |
| 257 | sim_bound (float): The similarity threshold for clustering. |
| 258 | |
| 259 | Returns: |
| 260 | list: A list of clusters. |
| 261 | """ |
| 262 | num_points = similarity.shape[0] |
| 263 | clusters = [] |
| 264 | sim_copy = deepcopy(similarity) |
| 265 | added = [False] * num_points |
| 266 | while True: |
| 267 | max_avg_dist = sim_bound |
| 268 | best_cluster = None |
| 269 | best_point = None |
| 270 | |
| 271 | for c in clusters: |
| 272 | for point_idx in range(num_points): |
| 273 | if added[point_idx]: |
| 274 | continue |
| 275 | avg_dist = average_distance(sim_copy, point_idx, c) |
| 276 | if avg_dist > max_avg_dist: |
| 277 | max_avg_dist = avg_dist |
| 278 | best_cluster = c |
| 279 | best_point = point_idx |
| 280 | |
| 281 | if best_point is not None: |
| 282 | best_cluster.append(best_point) |
| 283 | added[best_point] = True |
| 284 | similarity[best_point, :] = 0 |
| 285 | similarity[:, best_point] = 0 |
| 286 | else: |
| 287 | if similarity.max() < sim_bound: |
| 288 | break |
| 289 | i, j = np.unravel_index(np.argmax(similarity), similarity.shape) |
| 290 | clusters.append([int(i), int(j)]) |
| 291 | added[i] = True |
| 292 | added[j] = True |
| 293 | similarity[i, :] = 0 |
| 294 | similarity[:, i] = 0 |
| 295 | similarity[j, :] = 0 |
| 296 | similarity[:, j] = 0 |
| 297 | return clusters |
no test coverage detected