Skip to content

N clusters medoids fix #129

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 19, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion sklearn_extra/cluster/_k_medoids.py
Original file line number Diff line number Diff line change
Expand Up @@ -412,7 +412,7 @@ def _initialize_medoids(self, D, n_clusters, random_state_):

if self.init == "random": # Random initialization
# Pick random k medoids as the initial ones.
medoids = random_state_.choice(len(D), n_clusters)
medoids = random_state_.choice(len(D), n_clusters, replace=False)
elif self.init == "k-medoids++":
medoids = self._kpp_init(D, n_clusters, random_state_)
elif self.init == "heuristic": # Initialization by heuristic
Expand Down
20 changes: 19 additions & 1 deletion sklearn_extra/cluster/tests/test_k_medoids.py
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,24 @@ def test_kmedoid_results(method, init, dtype):
assert dtype is np.dtype(km.transform(X_cc.astype(dtype)).dtype).type


@pytest.mark.parametrize("method", ["alternate", "pam"])
@pytest.mark.parametrize(
"init", ["random", "heuristic", "build", "k-medoids++"]
)
def test_kmedoid_nclusters(method, init):
n_clusters = 50

km = KMedoids(
n_clusters=n_clusters,
init=init,
method=method,
max_iter=1,
random_state=rng,
)
km.fit(X_cc)
assert len(np.unique(km.medoid_indices_)) == n_clusters


def test_clara_results():
expected = np.hstack([np.zeros(50), np.ones(50)])
km = CLARA(n_clusters=2)
Expand Down Expand Up @@ -113,7 +131,7 @@ def test_random_deterministic():
D = euclidean_distances(X)

medoids = KMedoids(init="random")._initialize_medoids(D, 4, rng)
assert_array_equal(medoids, [47, 117, 67, 103])
assert_array_equal(medoids, [114, 62, 33, 107])


def test_heuristic_deterministic():
Expand Down