|
| 1 | +""" |
| 2 | +Compatibility layer for handling different package versions. |
| 3 | +This module provides uniform interfaces for functionality that might |
| 4 | +depend on specific versions of packages or alternative implementations. |
| 5 | +""" |
| 6 | +import numpy as np |
| 7 | +import warnings |
| 8 | +from packaging import version |
| 9 | + |
| 10 | +# Check if scikit-learn-extra's KMedoids is usable |
| 11 | +# with the current NumPy version |
| 12 | +SKLEARN_EXTRA_AVAILABLE = False |
| 13 | +try: |
| 14 | + import sklearn_extra |
| 15 | + from sklearn_extra.cluster import KMedoids as SklearnExtraKMedoids |
| 16 | + SKLEARN_EXTRA_AVAILABLE = True |
| 17 | + |
| 18 | + # Check if NumPy version is compatible with sklearn_extra |
| 19 | + if version.parse(np.__version__) >= version.parse('2.0.0'): |
| 20 | + warnings.warn( |
| 21 | + "You are using NumPy >= 2.0.0 with scikit-learn-extra which may " |
| 22 | + "cause compatibility issues. If you encounter errors, consider " |
| 23 | + "using the built-in KMedoids implementation in ATHENA.") |
| 24 | +except ImportError: |
| 25 | + SklearnExtraKMedoids = None |
| 26 | + |
| 27 | + |
| 28 | +# Implementation based on scikit-learn's KMeans but adapted for KMedoids |
| 29 | +class KMedoids: |
| 30 | + """ |
| 31 | + K-Medoids clustering. |
| 32 | + |
| 33 | + A custom implementation that doesn't rely on scikit-learn-extra, thus |
| 34 | + ensuring compatibility with NumPy 2.0+. |
| 35 | + |
| 36 | + Parameters |
| 37 | + ---------- |
| 38 | + n_clusters : int, default=8 |
| 39 | + The number of clusters to form as well as the number of medoids to generate. |
| 40 | + |
| 41 | + init : {'k-medoids++', 'random'} or array of shape (n_clusters, n_features), default='k-medoids++' |
| 42 | + Method for initialization. |
| 43 | + |
| 44 | + max_iter : int, default=300 |
| 45 | + Maximum number of iterations of the k-medoids algorithm for a single run. |
| 46 | + |
| 47 | + random_state : int, RandomState instance or None, default=None |
| 48 | + Determines random number generation for centroid initialization. |
| 49 | + """ |
| 50 | + |
| 51 | + def __init__(self, |
| 52 | + n_clusters=8, |
| 53 | + init='k-medoids++', |
| 54 | + max_iter=300, |
| 55 | + random_state=None): |
| 56 | + self.n_clusters = n_clusters |
| 57 | + self.init = init |
| 58 | + self.max_iter = max_iter |
| 59 | + self.random_state = random_state |
| 60 | + self.cluster_centers_ = None |
| 61 | + self.labels_ = None |
| 62 | + self.inertia_ = None |
| 63 | + self.n_iter_ = 0 |
| 64 | + |
| 65 | + def _init_medoids(self, X): |
| 66 | + """Initialize the medoids.""" |
| 67 | + rng = np.random.RandomState(self.random_state) |
| 68 | + n_samples = X.shape[0] |
| 69 | + |
| 70 | + if isinstance(self.init, str) and self.init == 'random': |
| 71 | + # Random selection |
| 72 | + indices = rng.permutation(n_samples)[:self.n_clusters] |
| 73 | + self.cluster_centers_ = X[indices].copy() |
| 74 | + elif isinstance(self.init, str) and self.init == 'k-medoids++': |
| 75 | + # Implementation of k-medoids++ initialization |
| 76 | + # Choose the first medoid randomly |
| 77 | + indices = np.zeros(self.n_clusters, dtype=int) |
| 78 | + indices[0] = rng.randint(n_samples) |
| 79 | + |
| 80 | + # Calculate distances to the first medoid |
| 81 | + distances = np.sum((X - X[indices[0]])**2, axis=1) |
| 82 | + |
| 83 | + # Choose remaining medoids |
| 84 | + for i in range(1, self.n_clusters): |
| 85 | + # Choose point with probability proportional to distance squared |
| 86 | + probs = distances / np.sum(distances) |
| 87 | + indices[i] = rng.choice(n_samples, p=probs) |
| 88 | + |
| 89 | + # Update distances |
| 90 | + new_dist = np.sum((X - X[indices[i]])**2, axis=1) |
| 91 | + distances = np.minimum(distances, new_dist) |
| 92 | + |
| 93 | + self.cluster_centers_ = X[indices].copy() |
| 94 | + else: |
| 95 | + # Use provided initial medoids |
| 96 | + self.cluster_centers_ = np.asarray(self.init, dtype=X.dtype) |
| 97 | + |
| 98 | + def fit(self, X): |
| 99 | + """Compute k-medoids clustering.""" |
| 100 | + X = np.asarray(X) |
| 101 | + self._init_medoids(X) |
| 102 | + |
| 103 | + best_labels = None |
| 104 | + best_inertia = float('inf') |
| 105 | + best_centers = None |
| 106 | + |
| 107 | + for i in range(self.max_iter): |
| 108 | + # Assign each point to closest medoid |
| 109 | + distances = np.zeros((X.shape[0], self.n_clusters)) |
| 110 | + for j in range(self.n_clusters): |
| 111 | + distances[:, j] = np.sum((X - self.cluster_centers_[j])**2, |
| 112 | + axis=1) |
| 113 | + |
| 114 | + labels = np.argmin(distances, axis=1) |
| 115 | + |
| 116 | + # Update medoids |
| 117 | + old_centers = self.cluster_centers_.copy() |
| 118 | + |
| 119 | + # For each cluster, update medoid to be the point minimizing inertia |
| 120 | + for j in range(self.n_clusters): |
| 121 | + cluster_points = X[labels == j] |
| 122 | + if len(cluster_points) > 0: |
| 123 | + # Compute pairwise distances within cluster |
| 124 | + inertias = np.zeros(len(cluster_points)) |
| 125 | + for k, point in enumerate(cluster_points): |
| 126 | + inertias[k] = np.sum( |
| 127 | + np.sum((cluster_points - point)**2, axis=1)) |
| 128 | + |
| 129 | + # Choose point with minimal inertia as new medoid |
| 130 | + min_idx = np.argmin(inertias) |
| 131 | + self.cluster_centers_[j] = cluster_points[min_idx].copy() |
| 132 | + |
| 133 | + # Compute inertia |
| 134 | + inertia = 0 |
| 135 | + for j in range(self.n_clusters): |
| 136 | + cluster_points = X[labels == j] |
| 137 | + if len(cluster_points) > 0: |
| 138 | + inertia += np.sum( |
| 139 | + np.sum((cluster_points - self.cluster_centers_[j])**2, |
| 140 | + axis=1)) |
| 141 | + |
| 142 | + # Store best result |
| 143 | + if inertia < best_inertia: |
| 144 | + best_inertia = inertia |
| 145 | + best_labels = labels |
| 146 | + best_centers = self.cluster_centers_.copy() |
| 147 | + |
| 148 | + # Check for convergence |
| 149 | + center_shift = np.sum( |
| 150 | + np.sqrt(np.sum((old_centers - self.cluster_centers_)**2, |
| 151 | + axis=1))) |
| 152 | + if center_shift < 1e-4: |
| 153 | + break |
| 154 | + |
| 155 | + self.labels_ = best_labels |
| 156 | + self.cluster_centers_ = best_centers |
| 157 | + self.inertia_ = best_inertia |
| 158 | + self.n_iter_ = i + 1 |
| 159 | + |
| 160 | + return self |
| 161 | + |
| 162 | + def predict(self, X): |
| 163 | + """Predict the closest cluster for each sample in X.""" |
| 164 | + X = np.asarray(X) |
| 165 | + distances = np.zeros((X.shape[0], self.n_clusters)) |
| 166 | + for j in range(self.n_clusters): |
| 167 | + distances[:, j] = np.sum((X - self.cluster_centers_[j])**2, axis=1) |
| 168 | + |
| 169 | + return np.argmin(distances, axis=1) |
| 170 | + |
| 171 | + |
| 172 | +# Export the appropriate KMedoids implementation |
| 173 | +if SKLEARN_EXTRA_AVAILABLE and version.parse( |
| 174 | + np.__version__) < version.parse('2.0.0'): |
| 175 | + # Use sklearn-extra's implementation when available and NumPy < 2.0 |
| 176 | + KMedoids = SklearnExtraKMedoids |
| 177 | +# Otherwise use our implementation which is compatible with NumPy 2.0+ |
0 commit comments