Cluster evaluation: a high score still needs a question
聚类评估
Compute silhouette, chance-adjusted pair agreement and coverage on the same records, then explain why their verdicts differ.
cluster-evaluationTwo scores, two different questions
Four customers have feature values 0, 1, 10 and 11. A clustering puts the first two together and the last two together. The picture looks convincing: each pair is close, and a large gap separates the pairs. But suppose the category we care about alternates across the records: A, B, A, B. The tidy geometric groups disagree with that category.
Nothing has gone wrong with arithmetic. We asked two different questions. An internal measure uses features, distances and cluster assignments to evaluate geometric structure. An external measure compares assignments with a reference partition. A third question, stability, asks whether reasonable changes to data or fitting choices preserve the result. Practical usefulness requires another check against the task itself.
This chapter computes a silhouette score and an adjusted Rand index (ARI) for the same small dataset. The geometric grouping has a silhouette near 0.90 and an ARI of −0.5 against the specified categories. Grouping by those categories gives ARI 1 but a negative silhouette. You can reproduce both results without installing a clustering library.
The input to an evaluation is already a partition. The functions below do not fit k-means or DBSCAN. Keeping fitting and evaluation separate makes it easier to see which records, distances and labels each score actually uses.
Compare distances inside a group, or pairs across partitions
Silhouette: is this record closer to its own group?
For a record i in cluster A, let a_i be its mean distance to the other members of A. For each other cluster, compute the mean distance from i to that cluster’s members, then take the smallest of those means as b_i:
The competitor is the nearest average cluster, not the nearest individual point. For a non-singleton record with at least one nonzero mean distance, its silhouette is
Large positive values favor separation under this distance; negative values mean another cluster is closer on average. Rousseeuw’s original construction sets singleton silhouettes to zero. We also use zero when a_i and b_i are both zero, and explicitly require between two and n−1 occupied clusters in our program. This avoids reporting the all-singleton partition as a useful geometric evaluation. Rousseeuw, §2, printed pp.55–56
Because both means are nonnegative, the score is between −1 and 1. Multiplying all distances by the same positive constant leaves it unchanged. Squaring the distances, adding a constant or rescaling only one feature can change it. Our implementation uses absolute distance on a line, not squared distance.
ARI: do two partitions agree about pairs?
Let n_ab count records in reference group a and predicted group b. Let r_a and c_b be the corresponding row and column totals. Among T unordered record pairs, define H as the number placed together by both partitions, and P and Q as the counts placed together by each partition separately:
Here is the chance model used for adjustment: keep the two sets of group sizes fixed, and randomly permute one partition’s labels over the records. A pair together in the first partition has probability Q/T of also being together in the permuted second partition. Summing over its P pairs gives expected overlap E=PQ/T. Thus the adjusted comparison is
This equation follows from chance-adjusting pair agreement. The raw Rand index counts pairs together in both plus pairs separate in both: its numerator is T−P−Q+2H. Subtracting its expected value and dividing by its remaining distance to one cancels the common factors and gives the expression above. The fixed API describes chance adjustment, symmetry and invariance to label renaming, and attributes the measure to Hubert and Arabie. Adjusted Rand API and references
The expected ARI is zero under this fixed-size permutation model when its denominator is nonzero. A particular random partition can score above or below zero. This is an expectation under a specified null model, not a claim that every random labeling scores zero.
Our direct function requires at least two records. When the denominator is zero, both partitions must put all records in one group or both must make every record a singleton. Their pair decisions are identical; the program returns one. It compares partitions, so renaming group zero to group twenty changes nothing.
Return coverage alongside the scores
Run this complete program with Python 3. Coordinates are one-dimensional integers or Fraction values; group labels are integers, with booleans rejected. Inputs must be aligned. The functions copy their inputs and use exact rational arithmetic.
silhouette returns every (a,b,s) triple, using None for the undefined within-group mean of a singleton. adjusted_rand returns pair counts as well as the score. evaluate additionally records retained row indices and coverage. By default, −1 is treated like any other label. With exclude_noise=True, rows whose predicted label is −1 are removed from both partitions and the feature vector. No other label is specially interpreted.
If the retained data cannot support a metric’s stated contract, the wrapper returns None for that metric, not a fabricated zero. It still reports coverage, including zero when every row is rejected. Standalone metric functions raise ValueError on invalid input.
from collections import Counter
from fractions import Fraction as F
def labels(values):
if type(values) not in (list,tuple) or any(type(v) is not int for v in values):
raise ValueError('labels must be a list or tuple of integers')
return tuple(values)
def silhouette(xs,groups):
groups=labels(groups)
if type(xs) not in (list,tuple) or any(type(x) is not int and not isinstance(x,F) for x in xs):
raise ValueError('coordinates must be integers or Fraction values')
xs=tuple(F(x) for x in xs);n=len(xs)
if len(groups)!=n or not 2<=len(set(groups))<=n-1:
raise ValueError('aligned rows and between two and n-1 clusters required')
members={label:tuple(i for i,g in enumerate(groups) if g==label) for label in set(groups)}
rows=[]
for i,x in enumerate(xs):
own=members[groups[i]]
a=sum(abs(x-xs[j]) for j in own if j!=i)/F(len(own)-1) if len(own)>1 else None
b=min(sum(abs(x-xs[j]) for j in ids)/F(len(ids))
for label,ids in members.items() if label!=groups[i])
score=F(0) if a is None or max(a,b)==0 else (b-a)/max(a,b)
rows.append((a,b,score))
return {'rows':tuple(rows),'mean':sum(row[2] for row in rows)/n}
def adjusted_rand(first,second):
first,second=labels(first),labels(second);n=len(first)
if len(second)!=n or n<2:raise ValueError('at least two aligned records required')
choose2=lambda k:k*(k-1)//2
total=choose2(n)
shared=sum(choose2(v) for v in Counter(zip(first,second)).values())
a=sum(choose2(v) for v in Counter(first).values())
b=sum(choose2(v) for v in Counter(second).values())
expected=F(a*b,total);maximum=F(a+b,2)
score=F(1) if maximum==expected else (shared-expected)/(maximum-expected)
return {'shared':shared,'first_pairs':a,'second_pairs':b,'total_pairs':total,
'expected_shared':expected,'score':score}
def evaluate(xs,predicted,reference,exclude_noise=False):
predicted,reference=labels(predicted),labels(reference)
if type(exclude_noise) is not bool:raise ValueError('exclude_noise must be boolean')
if type(xs) not in (list,tuple) or any(type(x) is not int and not isinstance(x,F) for x in xs):
raise ValueError('coordinates must be integers or Fraction values')
if not xs or len(xs)!=len(predicted) or len(xs)!=len(reference):
raise ValueError('nonempty aligned records required')
kept=tuple(i for i,g in enumerate(predicted) if not exclude_noise or g!=-1)
x=tuple(xs[i] for i in kept);p=tuple(predicted[i] for i in kept);r=tuple(reference[i] for i in kept)
internal=silhouette(x,p) if 2<=len(set(p))<=len(p)-1 else None
external=adjusted_rand(r,p) if len(p)>=2 else None
return {'kept':kept,'coverage':F(len(kept),len(xs)),
'silhouette':internal,'ari':external}
if __name__=='__main__':
xs=(0,1,10,11);semantic=(0,1,0,1);geometric=(0,0,1,1)
for name,p in [('geometric',geometric),('semantic',semantic)]:
report=evaluate(xs,p,semantic)
print(name,'silhouette:',report['silhouette']['mean'],'ARI:',report['ari']['score'])
print('first record (a,b,s):',silhouette(xs,geometric)['rows'][0])
extended=xs+(100,);prediction=geometric+(-1,);reference=semantic+(2,)
for excluded in (False,True):
report=evaluate(extended,prediction,reference,excluded)
print('exclude noise:',excluded,'coverage:',report['coverage'],
'silhouette:',report['silhouette']['mean'],'ARI:',report['ari']['score'])
print('all rejected:',evaluate((0,1),(-1,-1),(0,1),True))
print('degenerate identical partitions:',adjusted_rand((0,1),(8,9))['score'])
For nonempty input, direct silhouette calculation uses O(n²) distance work and O(n) auxiliary storage; no distance matrix is stored. Counting ARI’s contingency cells uses O(n) expected dictionary work and O(n) storage under ordinary hash-table assumptions. Exact integer and fraction bit costs are additional. The wrapper validates all coordinates before filtering, so an invalid rejected row is not silently accepted.
Inspect the disagreement rather than averaging it away
geometric silhouette: 359/399 ARI: -1/2
semantic silhouette: -9/20 ARI: 1
first record (a,b,s): (Fraction(1, 1), Fraction(21, 2), Fraction(19, 21))
exclude noise: False coverage: 1 silhouette: 1436/1995 ARI: -1/4
exclude noise: True coverage: 4/5 silhouette: 359/399 ARI: -1/2
all rejected: {'kept': (), 'coverage': Fraction(0, 1), 'silhouette': None, 'ari': None}
degenerate identical partitions: 1
For the first geometric record, a is 1 and b is 21/2, producing 19/21. The other end of its pair has silhouette 17/19. The mean across both pairs is 359/399. These are statements about distance separation.
Against the alternating categories, the geometric grouping has P=Q=2 pairs together in each partition, H=0 together in both, and T=6 total pairs. Its expected overlap is 2/3, giving ARI −1/2. The category grouping agrees perfectly with itself, but its mean within-category distance is large: its silhouette is −9/20.
The extra record at 100 illustrates another choice. Treating its −1 label as a singleton group gives full coverage and a different pair comparison. Excluding it raises the average silhouette here, but leaves only four-fifths of the original records. A changed denominator and a changed population are part of the result.
A score rewards the structure built into its definition
Silhouette rewards compact groups separated under the chosen distance. That is not the same objective as following a curved high-density region. The original paper states the compact, separated setting for its construction. Inspect per-record and per-cluster values alongside the mean, especially when clusters differ greatly in size. Rousseeuw, §2
ARI requires a reference partition over the same retained records. That reference might be a useful annotation, a different algorithm’s output or a previous run; calling the argument reference does not establish ground truth. Pair-based counts also give large groups many pairs. Record the group sizes and the reason this particular reference matters.
Rejecting difficult records can improve a conditional score while reducing coverage. Compare both, using the same selection rule across candidates. If one method rejects half the data and another rejects none, their retained-only scores do not evaluate the same population. Our explicit −1 handling is a policy choice, not a universal interpretation of clustering noise.
Stability adds evidence but does not prove usefulness. An algorithm that always returns one group is perfectly repeatable. When comparing resamples, align shared record identities or define a separate assignment rule for a fixed evaluation set; do not compare labels attached to different rows as though they were paired observations.
Finally, using a score to choose the number of clusters or other parameters makes it part of model selection. The winning score is not an untouched assessment of the whole selection process. Save candidate settings, preprocessing, distance, reference provenance, noise policy, retained counts and the evaluation split with the final report.
Decide what each number is allowed to say
1. A silhouette of about 0.90 accompanies ARI −0.5. Which result is wrong?
Answer: Neither. The first measures geometric compactness and separation; the second compares pair assignments with a specified reference. Our four records produce exactly this combination.
2. Rename every predicted cluster without changing its members. What happens?
Answer: Both metrics remain unchanged. Neither uses the numeric magnitude of the cluster name. Keep the noise policy consistent: renaming −1 to another number while retaining an exclusion rule for −1 changes which rows are selected.
3. Reject every row and report “no remaining errors.” Is the clustering perfect?
Answer: No. Coverage is zero. The wrapper returns no silhouette or ARI, because there is no retained partition to evaluate under their contracts. The rejection itself must be judged against the task.
4. Is the ARI chance baseline independent of its randomization assumptions?
Answer: No. The derivation here fixes group sizes and randomly permutes labels across records. It gives E=PQ/T. A different random partition model needs its own expectation; “chance corrected” does not remove the need to name that model.
Evaluation starts with the intended use of the groups
The silhouette paper made a partition inspectable one record at a time. Its display can reveal a weak small group that an overall mean conceals. Chance-adjusted pair agreement addresses a different issue: some agreements are expected merely from group sizes. These ideas complement a task-specific evaluation; neither identifies the one true taxonomy hidden in every dataset.
For a search product, test whether grouping helps users find relevant items. For a scientific dataset, examine whether groups survive measurement changes and support a stated hypothesis. For monitoring, evaluate which incidents are found and what review burden the clusters create. The appropriate downstream comparison can differ even when the clustering algorithm is identical.
Continue with unsupervised learning for the distinction between observed structure and interpretation, and hierarchical clustering for the consequences of choosing a cut through a hierarchy. Keep both the numerical evidence and the question it answers visible.
Make a prediction, then check
Removing predicted noise improves the silhouette. What must be reported with that new score?
Learning objectives
- Derive silhouette and chance-adjusted pair agreement and compute them on the same records.
- Explain why geometric separation and reference agreement can give opposite judgments.
- Report noise selection and retained coverage alongside conditional scores.
Prerequisites & connections
Explore related knowledge →References
- Silhouettes: a graphical aid to the interpretation and validation of cluster analysis
Peter J. Rousseeuw · 1987 - scikit-learn 1.7 — adjusted_rand_score
scikit-learn developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Six tests pass. An independent raw unordered-pair agreement reference explicitly enumerates all 24 index permutations for each of 18 partition comparisons, computes the null expectation and then adjusts the observed score. It uses no contingency table or closed-form expected-overlap expression.
- Analytic silhouette rows give 19/21, 17/19 and mean 359/399; alternating groups give -9/20. ARI gives -1/2 despite the high geometric score. Singleton, coincident-record and two exact similarity-transform cases pass.
- Noise inclusion/exclusion yields coverage 1 versus 4/5 and ARI -1/4 versus -1/2. All-rejected and one-retained cases return unavailable metrics rather than fabricated zero. Input contracts check malformed alignment, booleans, a nonfinite rejected coordinate and preservation. All seven stdout lines execute as printed.
- Full bilingual articles share four displays, six standard anchors, four answered exercises and the identical full Python program. Strict MDX/KaTeX and actual React HTML pass with the shared fatal guard. Edited with established Humanizer guidance; source access details stay in metadata. Written pending independent peer review.
- Ran all six author tests. Independently recovered pair overlap and within-partition pair totals from equivalence-matrix inner products. Expected overlap was computed by explicit hypergeometric cell-occupancy distributions, not the implemented PQ/T expression or the author’s full index-permutation oracle. Nine partition comparisons, including degenerate extremes and unequal group sizes, checked five returned fields; 48 hypergeometric cell distributions were used.
- A separate sorted-coordinate prefix-sum reference computes each cluster’s absolute-distance total without repeating pairwise distance loops. Piecewise silhouette expressions check six complete reports and 25 rows, including singleton, coincident, mixed fractional and negative-silhouette cases. The remaining author tests independently cover selected-population coverage, noise policies, invalid rejected coordinates, transformations and preservation.
- Read both full articles, complete code, exercises and metadata. Verified the ARI denominator-zero classification algebraically, n >= 2 standalone ARI versus the wrapper’s nonempty input contract, the conditional meaning of retained scores, metric-versus-task distinctions and O(n²) silhouette work/O(n) storage. No semantic truth or guaranteed generalization is inferred from a reference partition or stability.
- Strict MDX/KaTeX and actual React HTML pass: each language has four displays, six anchors and four answers; four math annotations match exactly. Author tests check identical complete code and all seven stdout lines. All five final file hashes match the frozen manifest, and source IDs/URLs are copied exactly from metadata. No frozen files were edited.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
Source locations checked:
- Silhouettes: a graphical aid to the interpretation and validation of cluster analysis · Actually read original PDF text: first page journal volume 20 (1987), pages 53–65, title/author, received/revised 1986 distinguished from publication; §2 printed pp.55–56, lines 109–151, compact/separated scope, average own-cluster exclusion, minimum other-cluster mean, ratio, singleton zero and multiplicative-scale invariance. Also read discussion text lines 414–426 on inspecting outliers and weak structure. No visual figure inspection, full thirteen-page reading or source-data replication claimed. Our both-zero convention and 2 through n-1 occupied-cluster contract are stated implementation choices.
- scikit-learn 1.7 — adjusted_rand_score · Actually read fixed /1.7/ page displaying 1.7.2, lines 623–634, pair agreement, chance-adjustment scheme, symmetry and label-permutation invariance; 668–670 attributes Comparing Partitions to Hubert and Arabie (1985). The closed contingency formula in our article is derived explicitly from raw pair agreement and a fixed-margin permutation null, then checked by enumerating actual permutations. DOI publisher fetch failed; no reading of the Hubert–Arabie full paper claimed. Fixed silhouette_samples API fetch also failed and is not counted as a source. No sklearn code or example values reused.
- Silhouettes: a graphical aid to the interpretation and validation of cluster analysis · Actually opened the original 13-page university PDF. Read printed page 53 for journal year 1987, title/author and the distinct 1986 received/revised dates; printed pages 55–56, section 2, for compact separated clusters, within-cluster self exclusion, the minimum competing cluster mean, the silhouette ratio, singleton zero and invariance under positive multiplicative distance scaling. The draft correctly labels the both-zero convention and occupied-cluster count contract as its own choices. Text reading only; no figure audit or full-paper reading claimed.
- scikit-learn 1.7 — adjusted_rand_score · Actually opened the fixed /1.7 adjusted_rand_score API rendered 1.7.2. Read lines 623–634 for raw pair agreement, chance adjustment, label permutation and symmetry, and lines 668–670 for Hubert–Arabie 1985 attribution. The draft explicitly derives a fixed-margin permutation null and qualifies its zero expectation by a nonzero denominator, rather than treating every random labeling as zero. Did not read the Hubert–Arabie original or run sklearn.
Related topics