Nearest centroid: one representative per class
最近质心分类
Fit exact class means, derive their boundaries, and test scaling, coincident centers and outliers.
nearest-centroidFour examples become two reference points
Suppose a toy sorter measures two numeric features. Class A contains (-2,2) and (2,2); class B contains (5,-1) and (7,1). The average of A is (0,2), and the average of B is (6,0). A nearest-centroid classifier saves those two points and sends a new observation to whichever is closer.
For (2,0), the squared distances are 8 and 16. It chooses A. There is no vote among training neighbors: every class contributes one representative, however many training observations it has. Nor is the algorithm discovering clusters: the labels determine which rows are averaged. This makes a useful small baseline when one representative captures each class reasonably well. The fixed scikit-learn 1.7.2 guide, §1.6.5 describes this class representation and its limitations.
Now divide the first feature by 10 before measuring distance. The same query has squared distances 4.04 and 0.16, so B wins. “Closest” only becomes meaningful after specifying the features and their scales.
A mean for each label, a boundary between means
Let contain the training indices with label , and let be its size. The fitted centroid is a vector of coordinate means. With fixed positive scales , our prediction rule is:
An exact tie needs a policy. Our program chooses the tied class whose label appeared first in training. That convention makes a result reproducible; it supplies no evidence that one tied label is better.
Why use a mean? For each class, expanding the squared distances around its mean gives this identity for any proposed center :
The cross term vanishes because deviations from each coordinate mean sum to zero. Positive scales make the final term nonnegative, with equality only at . This minimizes within-class squared reconstruction error. It does not prove that the resulting classifier minimizes the number of classification mistakes.
The boundary between two distinct centers A and B follows by setting their squared distances equal and canceling the quadratic terms in :
For the original centers and unit scales, the line is . A class’s region is an intersection of pairwise half-spaces, with boundaries assigned by the tie policy. Coincident centers tie everywhere. Curved or disconnected class structure is therefore not captured by a single center.
There is also a conditional probabilistic interpretation. If class distributions are Gaussian with a common covariance with , and equal prior probabilities, maximizing their densities gives this distance rule. Unequal priors or a general shared covariance change it. This is a restricted case of the LDA model in the official guide, §1.2.2.2. The program does not estimate a covariance or posterior probabilities. Gaussian assumptions are unnecessary for running the geometric rule; they are additional conditions for that probabilistic interpretation. Estimated means also introduce estimation error.
Keep the arithmetic visible
The complete Python 3.10+ program uses Fraction, so all distances and ties are exact for its accepted inputs. Coordinates and scales must be integers or Fraction objects; booleans and floats are rejected. Training and prediction rows use lists or tuples, labels are nonempty strings, and at least one training row and feature are required. A class with one training example is allowed. Empty prediction input returns an empty tuple.
fit returns immutable labels, centroids and scales. predict expects that unchanged result, not an arbitrary manually constructed model tuple. It does not retain training rows or change fitted values. The optional scales are supplied explicitly; this program does not estimate them. In a real pipeline, estimate any data-dependent scaling on training data only.
from fractions import Fraction as F
def vector(row, d):
if not isinstance(row, (list, tuple)) or len(row) != d:
raise ValueError('Expected a vector with the fitted dimension.')
if any(type(v) not in (int, F) for v in row):
raise ValueError('Coordinates must be integers or Fractions.')
return tuple(F(v) for v in row)
def fit(X, y, scales=None):
if not isinstance(X, (list, tuple)) or not X:
raise ValueError('Training data must be a nonempty list or tuple.')
if not isinstance(y, (list, tuple)) or len(y) != len(X):
raise ValueError('Provide one label per training row.')
if not isinstance(X[0], (list, tuple)) or not X[0]:
raise ValueError('At least one feature is required.')
d = len(X[0])
scales = (F(1),) * d if scales is None else vector(scales, d)
if any(s <= 0 for s in scales):
raise ValueError('Each scale must be strictly positive.')
totals, counts = {}, {}
for row, label in zip(X, y):
point = vector(row, d)
if type(label) is not str or not label:
raise ValueError('Labels must be nonempty strings.')
if label not in totals:
totals[label] = [F(0)] * d
counts[label] = 0
counts[label] += 1
for j, value in enumerate(point):
totals[label][j] += value
labels = tuple(totals) # First appearance settles an exact distance tie.
centers = tuple(tuple(v / counts[k] for v in totals[k]) for k in labels)
return labels, centers, scales
def predict(model, X):
# model is an unchanged result from fit; arbitrary model tuples are not supported.
labels, centers, scales = model
if not isinstance(X, (list, tuple)):
raise ValueError('Prediction rows must be a list or tuple.')
output = []
for row in X:
point = vector(row, len(scales))
def squared(k):
return sum(((x - c) / s) ** 2
for x, c, s in zip(point, centers[k], scales))
winner = min(range(len(labels)), key=squared)
output.append(labels[winner])
return tuple(output)
if __name__ == '__main__':
X = ((-2, 2), (2, 2), (5, -1), (7, 1))
y = ('A', 'A', 'B', 'B')
raw = fit(X, y)
print('centers =', tuple(tuple(str(v) for v in c) for c in raw[1]))
print('raw =', predict(raw, ((2, 0), (5, 1), (3, 1))))
print('scaled =', predict(fit(X, y, (10, 1)), ((2, 0),)))
separate = fit(((-2,), (2,), (-1,), (1,)), ('outer', 'outer', 'inner', 'inner'))
print('same-center =', predict(separate, ((-2,), (-1,), (1,), (2,))))
outlier = fit(((0,), (2,), (100,), (9,), (11,)), ('A', 'A', 'A', 'B', 'B'))
print('outlier =', predict(outlier, ((1,),)))
print('empty =', predict(raw, ()))
Actual output:
centers = (('0', '2'), ('6', '0'))
raw = ('A', 'B', 'A')
scaled = ('B',)
same-center = ('outer', 'outer', 'outer', 'outer')
outlier = ('B',)
empty = ()
The raw query (3,1) lies on the boundary, so A wins the recorded tie. In same-center, the outer points -2,2 and inner points -1,1 both average to zero. The classifier predicts outer for all four observations, including both inner ones. More data with the same symmetric pattern would not repair this representation.
The outlier example moves A’s center from 1 to 34 by adding 100. B’s center remains 10, and a query at 1 now receives B. This is a deliberately constructed failure, not an accuracy estimate for an application.
For rows, features and observed classes, fitting takes arithmetic operations and auxiliary/model storage, under the usual constant-time dictionary assumption. Predicting rows takes arithmetic operations for nonempty input, or constant overhead when , and extra storage. These are arithmetic-operation counts: the bit cost of exact rational numbers can grow with coordinate size and denominators. The model has centroid coordinates regardless of .
A compact summary can discard the decisive feature
| Situation | What the small model misses | A useful comparison |
|---|---|---|
| A label occupies two separated regions | Its mean may lie in another class’s region | Local neighbors or multiple prototypes |
| Strongly correlated features | Coordinate scaling cannot rotate the metric | LDA with a suitable shared covariance estimate |
| Classes have different spreads | One center says nothing about spread | QDA or another model with class-specific shape |
| Outliers move the mean | Squared reconstruction error heavily weights distant points | Inspect data quality; compare a robust prototype |
| Different class frequencies or error costs | This rule has no prior or cost term | Specify the decision objective explicitly |
A coordinate median minimizes coordinatewise absolute deviation, whereas a mean minimizes squared deviation; swapping the distance while keeping the same center needs a fresh argument. A class mean can also be an impossible raw object. Averaging embeddings or numeric features does not create a valid document, image or physical item.
Compare against a majority-class baseline and kNN using a held-out split. Record feature scaling and per-class errors, and reserve final test data from model selection. The label counts themselves do not enter this program’s distance scores: duplicating every row of one class leaves its center unchanged. Duplicating selected rows can move it. The small stored model is an engineering advantage, not a guarantee of representative features or good generalization.
Check the boundary before trusting the label
1. Which labels do (3,1) and (3,0) receive under the original unit scales?
Answer: The boundary is . The first point is a tie, assigned A by first appearance. The second gives 9 and is closer to B: squared distances to A and B are 13 and 9.
2. Repeat every A training row ten times without changing the B rows. Does the model start favoring A?
Answer: Its centroid and the predictions stay unchanged. This implementation does not estimate a prior from class counts. Repeating only one A row would change the mean; adding a prior term would define a different decision rule.
3. Multiply the first coordinate of all training and query points by 100. How can you preserve predictions?
Answer: Multiply its supplied scale by 100 as well. Every squared scaled difference is then unchanged. Leaving the scale at one changes the metric and may change predictions. Apply the same coordinate and scale convention to training and prediction.
4. Can this implementation, with its fixed label priority, perfectly classify the inner and outer points?
Answer: No. Both fitted centers are zero, so every point ties. A fixed label tie policy predicts the same class throughout. Choosing a different first label merely swaps which class loses. The failure comes from the representation, even though all training labels were available.
Separate the baseline from its extensions
The fixed neighbors guide also describes nearest shrunken centroids. That extension changes the feature contributions and introduces a shrinkage choice; it is not implemented here. The guide’s example scores are specific experiments, not performance claims for this chapter’s original data.
The LDA/QDA mathematics provides the next comparison: change the covariance and priors while retaining explicit class models. Follow LDA, QDA and k-means. The last method learns cluster assignments without supplied class labels, which changes what the centers mean. This chapter uses no library code, figures or datasets and does not claim to reproduce a particular estimator API.
Make a prediction, then check
Outer points −2,2 and inner points −1,1 form two classes with the same centroid 0. How does the program classify?
Learning objectives
- Calculate class means, scaled distances and ties; distinguish labeled prototypes, kNN and clustering.
- Prove the squared-reconstruction identity, derive linear boundaries, and state extra conditions for a probabilistic interpretation.
- Run the exact program and explain scaling, replicated rows, coincident centers and outliers.
Prerequisites & connections
Explore related knowledge →References
- Nearest neighbors — Nearest Centroid Classifier (1.7.2)
scikit-learn contributors - Linear and Quadratic Discriminant Analysis (1.7.2)
scikit-learn contributors
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.
- Both languages align on 3 displayed equations, 6 anchors and 4 answered exercises. Original four-point, scaling, coincident inner/outer and outlier outputs actually executed; no generalized performance claim.
- Five author tests pass: an independent raw-group-sum affine reference checks 432 predictions; squared reconstruction identity, exact ties, class replication, translation/rotation/unit change, tiny rational gaps, invalid inputs and full stdout verified.
- Algorithm is a geometric mean/common diagonal-scale baseline, not shrunken centroids, covariance estimation or probability calibration. Predict expects unchanged fit output; operation counts are separated from rational bit costs.
- Read complete bilingual articles, program, five author tests and metadata. All five tests passed. Exact integer/Fraction coordinates, strictly positive common scales, first-appearance ties, singleton classes, empty prediction, unchanged fit-result contract and immutable learned tuples agree with the description. No algorithm defect found.
- Independent geometry uses the identity distance(query,mean)^2 = average squared distance to raw class points minus half the average squared distance over ordered within-class point pairs. It computes neither centroids nor affine discriminants, unlike the author reference. Twelve focused models spanning one to three dimensions give 66 query comparisons and 138 class-distance checks; all pass. Five additional checks cover post-fit input mutation, a tiny-rational singleton/empty query and invalid scales.
- Reviewed the within-class reconstruction identity and pairwise boundary proof separately from classification optimality. Common diagonal Gaussian covariance/equal priors are additional probabilistic conditions, not requirements for geometric execution. Arithmetic time/storage bounds include fitted dimension, positive observed class count, output rows and empty-query overhead; arbitrary rational bit costs are qualified.
- Requested and reread two author corrections: exercise 4 now explicitly concerns this implementation with fixed label priority, because arbitrary query-dependent deterministic tie breaking is a different possibility; the Gaussian interpretation now specifies sigma squared > 0. No code or test change was needed. Final five hashes match, and final strict MDX/KaTeX/actual React HTML pass with three displays, six anchors and four answers per locale.
- 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.
- Publication navigation points existing topics to their complete articles, retaining pending directory entries. Principles, equations, programs and exercises are unchanged; final article SHA values rebound.
- Publication-format correction: algorithm articles use the existing concept template; kind changed from algorithm to concept. Prose, mathematics and program unchanged.
Source locations checked:
- Nearest neighbors — Nearest Centroid Classifier (1.7.2) · Root actually read official 1.7.2 neighbors page via web text, lines 253–270, sections 1.6.5/1.6.5.1. Used class-centroid description and limits; did not copy library data/code/images or carry over example accuracy. Replaced broad no-parameters wording with explicit metric/scaling/tie choices. Original shrunken-centroid PDF URL failed and is not claimed read.
- Linear and Quadratic Discriminant Analysis (1.7.2) · Root actually read official 1.7.2 LDA/QDA page via web text, lines 85–125: Bayes Gaussian class densities, shared covariance LDA, prior term, Mahalanobis and whitening interpretation. Derived special diagonal common covariance/equal-prior geometric rule separately. API page fetch and Stanford notes URL failed; neither is represented as read.
- Nearest neighbors — Nearest Centroid Classifier (1.7.2) · Independently opened official /1.7/modules/neighbors.html, rendered as 1.7.2, through web. Read §1.6.5 and §1.6.5.1, lines 253–270: per-class centroid representation, non-convex/spread limitations and shrinkage extension. The article correctly avoids the guide’s broad no-parameters wording and makes scaling/ties explicit. No copied library example, shrunken-centroid paper read, estimator run or guide accuracy claim adopted.
- Linear and Quadratic Discriminant Analysis (1.7.2) · Independently opened official versioned LDA/QDA page through web, rendered as 1.7.2. Read lines 85–125: Gaussian conditional density, Bayes priors, equal-covariance LDA, Mahalanobis rule and whitening. For positive sigma squared and fixed positive scales, common diagonal covariance and equal priors yield the article’s geometric rule. The article does not claim covariance estimation, posterior output or an exact estimator API reproduction.
Related topics