Skip to contents

Finds the optimal mapping from estimated cluster labels to true cluster labels using the Hungarian algorithm. This resolves the label switching problem inherent in clustering.

Usage

align_clusters_to_truth(z_true, z_hat)

Arguments

z_true

Integer vector of true cluster assignments (1 to K_true).

z_hat

Integer vector of estimated cluster assignments (1 to K_hat).

Value

A list with:

mapping

Named integer vector where names are estimated labels and values are corresponding true labels.

z_aligned

Integer vector of aligned estimated labels (same length as z_hat, with labels remapped to match z_true).

accuracy

Numeric scalar: proportion of correctly matched assignments after alignment.

Returns a list with all NA values if inputs are invalid.

Details

The Hungarian algorithm (via clue::solve_LSAP) finds the assignment that maximizes the overlap between estimated and true clusters. This is essential for fair evaluation of clustering methods where label identities are arbitrary.

When K_hat != K_true, the algorithm handles the mismatch by:

  • If K_hat < K_true: Some true clusters may not have a match

  • If K_hat > K_true: Some estimated clusters map to the same true cluster

Examples

if (FALSE) { # \dontrun{
z_true <- c(1, 1, 1, 2, 2, 2, 3, 3, 3)
z_hat <- c(3, 3, 3, 1, 1, 1, 2, 2, 2)  # Labels are permuted
result <- align_clusters_to_truth(z_true, z_hat)
result$accuracy  # Should be 1.0 (perfect after alignment)
} # }