|
| 1 | +# ------------------------------------------------------------------ |
| 2 | +# Licensed under the MIT License. See LICENSE in the project root. |
| 3 | +# ------------------------------------------------------------------ |
| 4 | + |
| 5 | +""" |
| 6 | + KMedoids(k; tol=1e-4, maxiter=10, weights=nothing, rng=Random.default_rng()) |
| 7 | +
|
| 8 | +Assign labels to rows of table using the `k`-medoids algorithm. |
| 9 | +
|
| 10 | +The iterative algorithm is interrupted if the relative change on |
| 11 | +the average distance to medoids is smaller than a tolerance `tol` |
| 12 | +or if the number of iterations exceeds the maximum number of |
| 13 | +iterations `maxiter`. |
| 14 | +
|
| 15 | +Optionally, specify a dictionary of `weights` for each column to |
| 16 | +affect the underlying table distance from TableDistances.jl, and |
| 17 | +a random number generator `rng` to obtain reproducible results. |
| 18 | +
|
| 19 | +## Examples |
| 20 | +
|
| 21 | +```julia |
| 22 | +KMedoids(3) |
| 23 | +KMedoids(4, maxiter=20) |
| 24 | +KMedoids(5, weights=Dict(:col1 => 1.0, :col2 => 2.0)) |
| 25 | +``` |
| 26 | +
|
| 27 | +## References |
| 28 | +
|
| 29 | +* Kaufman, L. & Rousseeuw, P. J. 1990. [Partitioning Around Medoids (Program PAM)] |
| 30 | + (https://onlinelibrary.wiley.com/doi/10.1002/9780470316801.ch2) |
| 31 | +
|
| 32 | +* Kaufman, L. & Rousseeuw, P. J. 1991. [Finding Groups in Data: An Introduction to Cluster Analysis] |
| 33 | + (https://www.jstor.org/stable/2532178) |
| 34 | +""" |
| 35 | +struct KMedoids{W,RNG} <: StatelessFeatureTransform |
| 36 | + k::Int |
| 37 | + tol::Float64 |
| 38 | + maxiter::Int |
| 39 | + weights::W |
| 40 | + rng::RNG |
| 41 | +end |
| 42 | + |
| 43 | +function KMedoids(k; tol=1e-4, maxiter=10, weights=nothing, rng=Random.default_rng()) |
| 44 | + # sanity checks |
| 45 | + _assert(k > 0, "number of clusters must be positive") |
| 46 | + _assert(tol > 0, "tolerance on relative change must be positive") |
| 47 | + _assert(maxiter > 0, "maximum number of iterations must be positive") |
| 48 | + KMedoids(k, tol, maxiter, weights, rng) |
| 49 | +end |
| 50 | + |
| 51 | +parameters(transform::KMedoids) = (; k=transform.k) |
| 52 | + |
| 53 | +function applyfeat(transform::KMedoids, feat, prep) |
| 54 | + # retrieve parameters |
| 55 | + k = transform.k |
| 56 | + tol = transform.tol |
| 57 | + maxiter = transform.maxiter |
| 58 | + weights = transform.weights |
| 59 | + rng = transform.rng |
| 60 | + |
| 61 | + # number of observations |
| 62 | + nobs = _nrows(feat) |
| 63 | + |
| 64 | + # sanity checks |
| 65 | + k > nobs && throw(ArgumentError("requested number of clusters > number of observations")) |
| 66 | + |
| 67 | + # normalize variables |
| 68 | + stdfeat = feat |> StdFeats() |
| 69 | + |
| 70 | + # define table distance |
| 71 | + td = TableDistance(normalize=false, weights=weights) |
| 72 | + |
| 73 | + # initialize medoids |
| 74 | + medoids = sample(rng, 1:nobs, k, replace=false) |
| 75 | + |
| 76 | + # retrieve distance type |
| 77 | + s = Tables.subset(stdfeat, 1:1) |
| 78 | + D = eltype(pairwise(td, s)) |
| 79 | + |
| 80 | + # pre-allocate memory for labels and distances |
| 81 | + labels = fill(0, nobs) |
| 82 | + dists = fill(typemax(D), nobs) |
| 83 | + |
| 84 | + # main loop |
| 85 | + iter = 0 |
| 86 | + δcur = mean(dists) |
| 87 | + while iter < maxiter |
| 88 | + # update labels and medoids |
| 89 | + _updatelabels!(td, stdfeat, medoids, labels, dists) |
| 90 | + _updatemedoids!(td, stdfeat, medoids, labels) |
| 91 | + |
| 92 | + # average distance to medoids |
| 93 | + δnew = mean(dists) |
| 94 | + |
| 95 | + # break upon convergence |
| 96 | + abs(δnew - δcur) / δcur < tol && break |
| 97 | + |
| 98 | + # update and continue |
| 99 | + δcur = δnew |
| 100 | + iter += 1 |
| 101 | + end |
| 102 | + |
| 103 | + newfeat = (; cluster=labels) |> Tables.materializer(feat) |
| 104 | + |
| 105 | + newfeat, nothing |
| 106 | +end |
| 107 | + |
| 108 | +function _updatelabels!(td, table, medoids, labels, dists) |
| 109 | + for (k, mₖ) in enumerate(medoids) |
| 110 | + inds = 1:_nrows(table) |
| 111 | + |
| 112 | + X = Tables.subset(table, inds) |
| 113 | + μ = Tables.subset(table, [mₖ]) |
| 114 | + |
| 115 | + δ = pairwise(td, X, μ) |
| 116 | + |
| 117 | + @inbounds for i in inds |
| 118 | + if δ[i] < dists[i] |
| 119 | + dists[i] = δ[i] |
| 120 | + labels[i] = k |
| 121 | + end |
| 122 | + end |
| 123 | + end |
| 124 | +end |
| 125 | + |
| 126 | +function _updatemedoids!(td, table, medoids, labels) |
| 127 | + for k in eachindex(medoids) |
| 128 | + inds = findall(isequal(k), labels) |
| 129 | + |
| 130 | + X = Tables.subset(table, inds) |
| 131 | + |
| 132 | + j = _medoid(td, X) |
| 133 | + |
| 134 | + @inbounds medoids[k] = inds[j] |
| 135 | + end |
| 136 | +end |
| 137 | + |
| 138 | +function _medoid(td, table) |
| 139 | + Δ = pairwise(td, table) |
| 140 | + _, j = findmin(sum, eachcol(Δ)) |
| 141 | + j |
| 142 | +end |
0 commit comments