Function kmedoids::pam_swap

source ·
pub fn pam_swap<M, N, L>(
    mat: &M,
    med: &mut Vec<usize>,
    maxiter: usize
) -> (L, Vec<usize>, usize, usize)where
    N: Zero + PartialOrd + Copy,
    L: AddAssign + Signed + Zero + PartialOrd + Copy + From<N>,
    M: ArrayAdapter<N>,
Expand description

Run the original PAM SWAP algorithm (no BUILD, but given initial medoids).

This is provided for academic reasons to see the performance difference. Quality-wise, FasterPAM is not worse on average, but much faster. FastPAM1 is supposed to do the same swaps, and find the same result, but faster.

  • type M - matrix data type such as ndarray::Array2 or kmedoids::arrayadapter::LowerTriangle
  • type N - number data type such as u32 or f64
  • type L - number data type such as i64 or f64 for the loss (must be signed)
  • mat - a pairwise distance matrix
  • med - the list of medoids
  • maxiter - the maximum number of iterations allowed

returns a tuple containing:

  • the final loss
  • the final cluster assignment
  • the number of iterations needed
  • the number of swaps performed


  • panics when the dissimilarity matrix is not square
  • panics when k is 0 or larger than N


Given a dissimilarity matrix of size 4 x 4, use:

let data = ndarray::arr2(&[[0,1,2,3],[1,0,4,5],[2,4,0,6],[3,5,6,0]]);
let mut meds = kmedoids::random_initialization(4, 2, &mut rand::thread_rng());
let (loss, assi, n_iter, n_swap): (f64, _, _, _) = kmedoids::pam_swap(&data, &mut meds, 100);
println!("Loss is: {}", loss);