Skip to content

Commit 86eea0d

Browse files
committed
silhouette(): fix empty clusters case
fixes #241
1 parent a2ccfd6 commit 86eea0d

File tree

2 files changed

+10
-2
lines changed

2 files changed

+10
-2
lines changed

src/silhouette.jl

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -82,8 +82,9 @@ function silhouettes(assignments::AbstractVector{<:Integer},
8282
a[j] = r[l, j]
8383

8484
v = typemax(eltype(b))
85-
for i = 1:k
86-
@inbounds rij = r[i,j]
85+
@inbounds for i = 1:k
86+
counts[i] == 0 && continue # skip empty clusters
87+
rij = r[i,j]
8788
if (i != l) && (rij < v)
8889
v = rij
8990
end

test/silhouette.jl

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
using Test
22
using Clustering
3+
using Distances
34

45
@testset "silhouettes()" begin
56

@@ -54,4 +55,10 @@ end
5455
@test_throws ArgumentError silhouettes(a, d)
5556
end
5657

58+
@testset "empty clusters handled correctly (#241)" begin
59+
X = rand(MersenneTwister(123), 10, 5)
60+
pd = pairwise(Euclidean(), X, dims=1)
61+
@test all(>=(-0.5), silhouettes([5, 2, 2, 3, 2, 2, 3, 2, 3, 5], pd))
62+
end
63+
5764
end

0 commit comments

Comments
 (0)