Skip to content

Commit

Permalink
Update project
Browse files Browse the repository at this point in the history
  • Loading branch information
raphasampaio committed Jan 28, 2025
1 parent a1437fc commit 6b96888
Showing 1 changed file with 11 additions and 14 deletions.
25 changes: 11 additions & 14 deletions src/assignments.jl
Original file line number Diff line number Diff line change
Expand Up @@ -38,33 +38,30 @@ end

function balanced_kmeans_assignment_step!(; result::KmeansResult, distances::AbstractMatrix{<:Real}, is_empty::AbstractVector{<:Bool})
k, n = size(distances)
cluster_capacity = div(n, k)
capacity = div(n, k)

candidates = Vector{Tuple{Float64, Int, Int}}()
sizehint!(candidates, k * n)

# flatten all (cluster, point) pairs into a single list, store tuples of the form (distance, point, cluster)
assignment_candidates = Vector{Tuple{Float64, Int, Int}}(undef, n * k)
index = 1
for cluster in 1:k
for point in 1:n
assignment_candidates[index] = (distances[cluster, point], point, cluster)
index += 1
push!(candidates, (distances[cluster, point], point, cluster))
end
end
sort!(assignment_candidates, by = x -> x[1])
sort!(candidates, by = x -> x[1])

fill!(result.assignments, 0)
cluster_load = fill(0, k)
load = zeros(Int, k)
objective = 0.0
assigned_count = 0

# greedily assign
for (dist, point, cluster) in assignment_candidates
if result.assignments[point] == 0 && cluster_load[cluster] < cluster_capacity
for (distance, point, cluster) in candidates
if result.assignments[point] == 0 && load[cluster] < capacity
result.assignments[point] = cluster
cluster_load[cluster] += 1
objective += dist
load[cluster] += 1
objective += distance
assigned_count += 1

# if all points assigned, we can stop early
if assigned_count == n
break
end
Expand Down

2 comments on commit 6b96888

@raphasampaio
Copy link
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@JuliaRegistrator register

Release notes:

Features

  • Add balanced k-means

@JuliaRegistrator
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Registration pull request updated: JuliaRegistries/General/123869

Tagging

After the above pull request is merged, it is recommended that a tag is created on this repository for the registered package version.

This will be done automatically if the Julia TagBot GitHub Action is installed, or can be done manually through the github interface, or via:

git tag -a v0.5.0 -m "<description of version>" 6b96888dc7cab04535f5cd9e771ce97b673427aa
git push origin v0.5.0

Please sign in to comment.