Skip to content

Commit a063ec6

Browse files
committed
_kmedoid_upd_assignments(): cleanups
1 parent bb15e09 commit a063ec6

File tree

1 file changed

+16
-23
lines changed

1 file changed

+16
-23
lines changed

src/kmedoids.jl

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -182,51 +182,44 @@ end
182182

183183

184184
# update assignments and related quantities
185-
function _kmed_update_assignments!(dist::AbstractMatrix{T}, # in: (n, n)
185+
# returns the total cost and the number of assignment changes
186+
function _kmed_update_assignments!(dist::AbstractMatrix{<:Real}, # in: (n, n)
186187
medoids::AbstractVector{Int}, # in: (k,)
187188
assignments::Vector{Int}, # out: (n,)
188189
groups::Vector{Vector{Int}}, # out: (k,)
189-
costs::Vector{T}, # out: (n,)
190-
isinit::Bool) where T # in
190+
costs::AbstractVector{<:Real},# out: (n,)
191+
initial::Bool) # in
191192
n = size(dist, 1)
192193
k = length(medoids)
193-
ch = 0
194194

195-
if !isinit
196-
for i = 1:k
197-
empty!(groups[i])
198-
end
199-
end
195+
# reset cluster groups (note: assignments are not touched yet)
196+
initial || foreach(empty!, groups)
200197

201198
tcost = 0.0
199+
ch = 0
202200
for j = 1:n
203-
p = 1
201+
p = 1 # initialize the closest medoid for j
204202
mv = dist[medoids[1], j]
205203

206-
for i = 2:k
207-
v = dist[medoids[i], j]
204+
# find the closest medoid for j
205+
@inbounds for i = 2:k
206+
m = medoids[i]
207+
v = dist[m, j]
208+
# assign if current medoid is closer or if it is j itself
208209
if v < mv
209210
p = i
210211
mv = v
211212
end
212213
end
213214

214-
if isinit
215-
assignments[j] = p
216-
else
217-
a = assignments[j]
218-
if p != a
219-
ch += 1
220-
end
221-
assignments[j] = p
222-
end
223-
215+
ch += !initial && (p != assignments[j])
216+
assignments[j] = p
224217
costs[j] = mv
225218
tcost += mv
226219
push!(groups[p], j)
227220
end
228221

229-
return (tcost, ch)::Tuple{Float64, Int}
222+
return (tcost, ch)
230223
end
231224

232225

0 commit comments

Comments
 (0)