-
Notifications
You must be signed in to change notification settings - Fork 15
Add KMedoids #298
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
Add KMedoids #298
Changes from 3 commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
087c96e
Initial implementation of KMedoids
juliohm 6643e90
Add basic test for KMedoids
juliohm 9d5f3ff
Add KMedoids to docs
juliohm a8c32c3
Add more tests for KMedoids
juliohm 08f3cc3
Use existing _nrows utility
juliohm b9f56fb
Use _assert utility function
juliohm 260c156
Retrieve distance type
juliohm 8ad1323
Minor adjustments
juliohm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
|
|
@@ -242,6 +242,12 @@ SDS | |
| ProjectionPursuit | ||
| ``` | ||
|
|
||
| ## KMedoids | ||
|
|
||
| ```@docs | ||
| KMedoids | ||
| ``` | ||
|
|
||
| ## Closure | ||
|
|
||
| ```@docs | ||
|
|
||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,145 @@ | ||
| # ------------------------------------------------------------------ | ||
| # Licensed under the MIT License. See LICENSE in the project root. | ||
| # ------------------------------------------------------------------ | ||
|
|
||
| """ | ||
| KMedoids(k; tol=1e-4, maxiter=10, weights=nothing, rng=Random.default_rng()) | ||
|
|
||
| Assign labels to rows of table using the `k`-medoids algorithm. | ||
|
|
||
| The iterative algorithm is interrupted if the relative change of | ||
| the average dissimilarity between successive iterations is smaller | ||
| than a tolerance `tol` or if the number of iterations exceeds | ||
| the maximum number of iterations `maxiter`. | ||
|
|
||
| Optionally, specify a dictionary of `weights` for each column to | ||
| affect the underlying table distance from TableDistances.jl, and | ||
| a random number generator `rng` to obtain reproducible results. | ||
|
|
||
| ## Examples | ||
|
|
||
| ```julia | ||
| KMedoids(3) | ||
| KMedoids(4, maxiter=20) | ||
| KMedoids(5, weights=Dict(:col1 => 1.0, :col2 => 2.0)) | ||
| ``` | ||
|
|
||
| ## References | ||
|
|
||
| * Kaufman, L. & Rousseeuw, P. J. 1990. [Partitioning Around Medoids (Program PAM)] | ||
| (https://onlinelibrary.wiley.com/doi/10.1002/9780470316801.ch2) | ||
|
|
||
| * Kaufman, L. & Rousseeuw, P. J. 1991. [Finding Groups in Data: An Introduction to Cluster Analysis] | ||
| (https://www.jstor.org/stable/2532178) | ||
| """ | ||
| struct KMedoids{W,RNG} <: StatelessFeatureTransform | ||
| k::Int | ||
| tol::Float64 | ||
| maxiter::Int | ||
| weights::W | ||
| rng::RNG | ||
| end | ||
|
|
||
| function KMedoids(k; tol=1e-4, maxiter=10, weights=nothing, rng=Random.default_rng()) | ||
| # sanity checks | ||
| @assert k > 0 "number of clusters must be positive" | ||
| @assert tol > 0 "tolerance on relative change must be positive" | ||
| @assert maxiter > 0 "maximum number of iterations must be positive" | ||
| KMedoids(k, tol, maxiter, weights, rng) | ||
| end | ||
|
|
||
| parameters(transform::KMedoids) = (; k=transform.k) | ||
|
|
||
| function applyfeat(transform::KMedoids, feat, prep) | ||
| # retrieve parameters | ||
| k = transform.k | ||
| tol = transform.tol | ||
| maxiter = transform.maxiter | ||
| weights = transform.weights | ||
| rng = transform.rng | ||
|
|
||
| # number of observations | ||
| nobs = _nrow(feat) | ||
|
|
||
| # sanity checks | ||
| k > nobs && throw(ArgumentError("requested number of clusters > number of observations")) | ||
|
|
||
| # normalize variables | ||
| stdfeat = feat |> StdFeats() | ||
|
|
||
| # define table distance | ||
| td = TableDistance(normalize=false, weights=weights) | ||
|
|
||
| # initialize medoids | ||
| medoids = sample(rng, 1:nobs, k, replace=false) | ||
|
|
||
| # pre-allocate memory for labels and distances | ||
| labels = fill(0, nobs) | ||
| dists = fill(Inf, nobs) | ||
|
|
||
| # main loop | ||
| iter = 0 | ||
| δcur = mean(dists) | ||
| while iter < maxiter | ||
| # update labels and medoids | ||
| _updatelabels!(td, stdfeat, medoids, labels, dists) | ||
| _updatemedoids!(td, stdfeat, medoids, labels) | ||
|
|
||
| # average dissimilarity | ||
| δnew = mean(dists) | ||
|
|
||
| # break upon convergence | ||
| abs(δnew - δcur) / δcur < tol && break | ||
|
|
||
| # update and continue | ||
| δcur = δnew | ||
| iter += 1 | ||
| end | ||
|
|
||
| newfeat = (; cluster=labels) |> Tables.materializer(feat) | ||
|
|
||
| newfeat, nothing | ||
| end | ||
|
|
||
| function _updatelabels!(td, table, medoids, labels, dists) | ||
| for (k, mₖ) in enumerate(medoids) | ||
| inds = 1:_nrow(table) | ||
|
|
||
| X = Tables.subset(table, inds) | ||
| μ = Tables.subset(table, [mₖ]) | ||
|
|
||
| δ = pairwise(td, X, μ) | ||
|
|
||
| @inbounds for i in inds | ||
| if δ[i] < dists[i] | ||
| dists[i] = δ[i] | ||
| labels[i] = k | ||
| end | ||
| end | ||
| end | ||
| end | ||
|
|
||
| function _updatemedoids!(td, table, medoids, labels) | ||
| for k in eachindex(medoids) | ||
| inds = findall(isequal(k), labels) | ||
|
|
||
| X = Tables.subset(table, inds) | ||
|
|
||
| j = _medoid(td, X) | ||
|
|
||
| @inbounds medoids[k] = inds[j] | ||
| end | ||
| end | ||
|
|
||
| function _nrow(table) | ||
juliohm marked this conversation as resolved.
Outdated
Show resolved
Hide resolved
|
||
| cols = Tables.columns(table) | ||
| vars = Tables.columnnames(cols) | ||
| vals = Tables.getcolumn(cols, first(vars)) | ||
| length(vals) | ||
| end | ||
|
|
||
| function _medoid(td, table) | ||
| Δ = pairwise(td, table) | ||
| _, j = findmin(sum, eachcol(Δ)) | ||
| j | ||
| end | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,16 @@ | ||
| @testset "KMedoids" begin | ||
| @test !isrevertible(KMedoids(3)) | ||
| @test TT.parameters(KMedoids(3)) == (k=3,) | ||
|
|
||
| a = [randn(100); 10 .+ randn(100)] | ||
| b = [randn(100); 10 .+ randn(100)] | ||
| t = Table(; a, b) | ||
|
|
||
| c = t |> KMedoids(2; rng) | ||
| i1 = findall(isequal(1), c.cluster) | ||
| i2 = findall(isequal(2), c.cluster) | ||
| @test mean(t.a[i1]) > 5 | ||
| @test mean(t.b[i1]) > 5 | ||
| @test mean(t.a[i2]) < 5 | ||
| @test mean(t.b[i2]) < 5 | ||
| end |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.