VC dimension: every labeling of some fixed points
VC 维
Inspect finite shattering with witness rows and missing-label certificates; distinguish growth, geometry and parameter count.
vc-dimensionCan the class fit every labeling of these points?
Place three distinct objects on a table and give each a binary label. A classifier might fit the particular labels you chose. Now change those labels in every possible way. Can the same class of classifiers fit all eight assignments, using a different classifier when necessary?
That is a shattering question. It concerns the possibilities offered by a hypothesis class, not one trained model or one successful optimization run. VC dimension measures the largest number of points on which the class can realize every binary labeling. The abbreviation names Vapnik and Chervonenkis. Stanford CS229, §4, pp. 9–10.
This chapter computes the answer for a small, explicitly listed class. It returns evidence: a hypothesis for each labeling of a shattered set, and a missing labeling for every candidate set one size larger. Thresholds, intervals and planar separators show why the geometry of the class matters more than counting parameter slots. The PAC learning chapter explains the statistical guarantees to which this combinatorial quantity connects.
One set, every labeling, possibly different hypotheses
Let H be a nonempty class of functions from a domain X to . For distinct points S=(x₁,…,xₘ), its trace is the set of binary vectors that members of H produce on those points:
The trace counts distinct label patterns, not parameter descriptions. The equivalent quantifier order is worth reading aloud:
The points remain fixed while the labels change. The chosen h may change with the labels. A single function cannot simultaneously assign zero and one to one point. Finding just one fitting labeling is also insufficient. If labels (1,0,1) are impossible on three ordered points, that alone prevents those points from being shattered, even if the other seven patterns are possible.
The dimension is:
It is infinite if sets of arbitrarily large finite size can be shattered. To prove the value is d, exhibit one shattered d-point set and rule out every (d+1)-point set. Larger shattered sets would contain shattered subsets of size d+1, so that upper-bound step suffices. Failing to shatter one inconvenient d-point arrangement does not disprove dimension d. Understanding Machine Learning, Definition 6.5 and §6.3.
The empty set has one possible labeling, the empty vector. Every nonempty H realizes it. A class containing just one function has dimension zero. The implementation accepts an empty domain with its empty function, but rejects an empty hypothesis class to avoid mixing conventions for the supremum of an empty collection.
Growth counts the labelings that remain possible
The growth function takes the largest trace size over point sets of size m:
For a finite domain of size N, this definition is used only for 0≤m≤N. The program does not invent values for larger sets that cannot exist in its domain. If a finite class has M distinct functions and shatters m points, those 2ᵐ patterns require at least 2ᵐ functions. Hence its dimension is at most floor(log₂ M), as well as at most N. Duplicate rows or duplicate parameter descriptions do not increase M.
Increasing thresholds on an ordered line realize only strings of zeros followed by ones. On m distinct ordered points, the switch can occur in m+1 places. A single interval realizes an empty positive set or one contiguous block of positives. Choosing that block’s first and last positions gives:
Here the classes allow all increasing thresholds and all intervals, including an empty positive region. For thresholds, either label is possible on one point, but (1,0) is impossible on any ordered pair: VC dimension is 1. Intervals realize all four patterns on any two points, but (1,0,1) is impossible on any ordered triple: dimension is 2. On a finite ordered domain, these values are capped by N, and the formulas apply for m≤N. Repeated observations of one input do not count as distinct points.
For general classes of finite VC dimension d, the Sauer–Shelah–Perles bound limits growth:
One way to see the counting mechanism is to separate traces according to the label on the last point. On the remaining points, let U contain patterns occurring with either last label, and I patterns occurring with both. The original number of traces is |U|+|I|. U cannot have dimension above d; I cannot shatter d points, because adjoining the last point would give d+1 shattered points in the original class. This yields the Pascal-type recurrence behind the binomial sum, with at most one pattern when d=0. Empty I contributes zero. The full induction appears in the textbook. For fixed d, growth is polynomial in m; before dimension d is exceeded it can still be 2ᵐ. Definition 6.9 and Lemma 6.10.
Three parameters are not the reason planar affine separators have dimension three
Consider h(x,y)=1[a·x+b·y+c≥0], including an intercept c. Three noncollinear points are shattered: assign each a score +1 or −1 according to its desired label, then solve the three independent affine equations. The program supplies explicit integer coefficients for the triangle (0,0), (2,0), (0,2), realizing all eight patterns without any point lying on the boundary.
No four distinct planar points can be shattered. If one lies in the convex hull of the other three, label the three positive and that point negative. An affine score at their convex combination cannot be negative when all three scores are nonnegative. Otherwise the four form a convex quadrilateral. Give one diagonal’s endpoints positive labels and the other diagonal’s endpoints negative labels. At the intersection, the affine score would have to be both nonnegative and strictly negative. Degenerate arrangements fall under the convex-hull case. Thus the continuous class has dimension three. Three collinear points, however, cannot realize positive endpoints and a negative middle point. This shows the difference between “some set” and “every set.” Stanford, planar example, pp. 9–10.
Parameter count is representation-dependent. Writing a threshold as t=u+v introduces two real parameters without changing the class or its dimension. In the other direction, one unbounded nonnegative integer q can encode a predictor on nonnegative integer inputs by taking the x-th binary digit of q. Choosing q as the sum of yₓ2ˣ realizes any labeling of inputs 0 through m−1; this one-integer-parameter class has infinite VC dimension. Its required number of bits grows with m. This is not a finite-precision counterexample or a claim about an ordinary one-weight neural network. The allowed representation, precision and operations matter.
Return both the successful fits and the missing labels
inspect takes a nonempty list or tuple of complete binary rows. Each column is one distinct input; each row is a hypothesis on the whole finite domain. The code rejects ragged rows, nonbinary values and Booleans. It copies and deduplicates rows, retaining their first original zero-based row IDs for evidence.
For each subset of columns, trace maps every realized label tuple to the first original row that produces it. A subset is shattered when the dictionary has exactly 2ᵏ entries. Otherwise, the code records the first missing tuple in lexicographic order. It returns the largest size, the growth values, a maximal shattered set with all its representatives, and one blocker for every subset of size d+1. If d=N, the domain size itself supplies the upper bound and the blocker list is empty.
None means no missing labeling; the empty tuple is a genuine labeling on the empty domain and must not be mistaken for failure. The code exhausts the finite search. It has no early-stop budget, and its returned dimension is exact for the supplied table. A sample of functions from a larger continuous family can establish a lower bound for that family, but cannot establish its upper bound.
from itertools import combinations, product
def sequence(value):
if type(value) not in (list, tuple):
raise ValueError('expected list or tuple')
return value
def prepare(raw):
raw = sequence(raw)
if not raw:
raise ValueError('the hypothesis class must be nonempty')
n = len(sequence(raw[0]))
rows, seen = [], set()
for original_id, value in enumerate(raw):
row = tuple(sequence(value))
if len(row) != n or any(type(bit) is not int or bit not in (0, 1) for bit in row):
raise ValueError('equal-width binary rows required; no Booleans')
if row not in seen:
seen.add(row)
rows.append((original_id, row))
return n, tuple(rows)
def trace(rows, points):
# Internal helper: prepared rows and increasing distinct valid point indices.
representatives = {}
for original_id, row in rows:
labels = tuple(row[x] for x in points)
representatives.setdefault(labels, original_id)
return representatives
def inspect(raw):
"""Exact finite-domain shattering, growth and lower/upper certificates."""
n, rows = prepare(raw)
growth = [0] * (n + 1)
records = []
dimension, witness_points = -1, None
for size in range(n + 1):
for points in combinations(range(n), size):
representatives = trace(rows, points)
count = len(representatives)
growth[size] = max(growth[size], count)
missing = None
if count == 1 << size:
if size > dimension:
dimension, witness_points = size, points
else:
missing = next(labels for labels in product((0, 1), repeat=size)
if labels not in representatives)
records.append((points, missing))
lower = trace(rows, witness_points)
blockers = tuple((points, missing) for points, missing in records
if len(points) == dimension + 1)
return {'domain_size': n, 'distinct_hypotheses': len(rows),
'dimension': dimension, 'growth': tuple(growth),
'witness': (witness_points, tuple(sorted(lower.items()))),
'blockers': blockers}
def thresholds(n):
if type(n) is not int or n < 0:
raise ValueError('nonnegative integer domain size required')
return tuple(tuple(int(x >= t) for x in range(n)) for t in range(n + 1))
def intervals(n):
if type(n) is not int or n < 0:
raise ValueError('nonnegative integer domain size required')
empty = (0,) * n
return (empty,) + tuple(tuple(int(left <= x <= right) for x in range(n))
for left in range(n) for right in range(left, n))
if __name__ == '__main__':
for name, rows in (('thresholds', thresholds(4)), ('intervals', intervals(4))):
result = inspect(rows)
print(name, 'VC:', result['dimension'], 'growth:', result['growth'])
result = inspect(intervals(4))
print('interval witness:', result['witness'])
print('interval blockers:', result['blockers'])
points = ((0, 0), (2, 0), (0, 2))
parameters = ((0, 0, -1), (0, 1, -1), (1, 0, -1), (1, 1, -1),
(-1, -1, 1), (-1, 0, 1), (0, -1, 1), (0, 0, 1))
table = tuple(tuple(int(a*x + b*y + c >= 0) for x, y in points)
for a, b, c in parameters)
print('triangle realized labels:', tuple(sorted(table)))
print('triangle finite-table VC:', inspect(table)['dimension'])
print('empty domain VC:', inspect(((),))['dimension'])
Actual output:
thresholds VC: 1 growth: (1, 2, 3, 4, 5)
intervals VC: 2 growth: (1, 2, 4, 7, 11)
interval witness: ((0, 1), (((0, 0), 0), ((0, 1), 5), ((1, 0), 1), ((1, 1), 2)))
interval blockers: (((0, 1, 2), (1, 0, 1)), ((0, 1, 3), (1, 0, 1)), ((0, 2, 3), (1, 0, 1)), ((1, 2, 3), (1, 0, 1)))
triangle realized labels: ((0, 0, 0), (0, 0, 1), (0, 1, 0), (0, 1, 1), (1, 0, 0), (1, 0, 1), (1, 1, 0), (1, 1, 1))
triangle finite-table VC: 3
empty domain VC: 0
The interval witness uses columns (0,1). Its four entries point back to original interval rows 0,5,1,2 for labels (0,0), (0,1), (1,0), (1,1). All four three-column sets have a missing (1,0,1) pattern. That is a checkable lower and upper certificate, not merely a number returned by a search routine.
The triangle result is exact for its eight-row table. The separate convexity argument establishes the upper bound for all affine separators in the plane. Enumerating a small grid of coefficients and failing to find a separator would not be a proof that no real coefficients work.
Let R be the number of supplied rows, M the number of distinct rows and N the number of columns. Validation and deduplication take expected O(R(N+1)) time under ordinary hash-table assumptions. The subset scan takes expected O((M+1)(N+1)2ᴺ) time: each projection costs O(N+1), and the first missing labeling is found after at most M+1 membership probes. Sorting the final witness is covered by this bound. Retained data and records use O((M+2ᴺ)(N+1)) slots, apart from the original input. These bounds include N=0 and count binary entries and index operations as unit cost; adversarial hashing and arbitrary-width index encodings need separate costs.
The generators create complete finite restrictions of increasing thresholds and single intervals. Generating their rows also takes time proportional to their output size. This is a small inspector, not a practical algorithm for deriving the dimension of a large network class from its parameter list.
A combinatorial capacity measure does not train the model
Shattering a set says nothing about whether an optimizer can find the witnessing hypotheses efficiently. A finite function table makes those witnesses searchable by construction; a succinct parameterized family may make the same question difficult. VC dimension does not measure training runtime, optimization error or the accuracy of one fitted model.
A labeling can be realizable on one inspected subset yet unrealizable on the complete domain. Nor does a class shattering a set imply that a population’s labels belong to the class. “Every labeling of some finite points is possible” is a capacity statement; realizability in PAC learning is an assumption about the actual distribution and labels.
In the standard IID binary statistical setting, with the usual measurability conditions, finite VC dimension characterizes distribution-free PAC learnability and supports agnostic learning relative to the class. That is a statistical connection, not an automatic runtime guarantee. This chapter does not plug a guessed parameter count into a sample-size formula. The PAC learning and empirical risk chapters explain the accuracy/confidence and realizable/agnostic distinctions.
Changing the domain can change the answer. Affine separators on the entire plane have dimension three; their restriction to a particular collinear set has lower capacity. Restricting parameters can also change the class. The finite program needs the complete allowed table to claim the exact dimension of that table. Conversely, adding duplicate representations or repeating a column as if it were a new physical input does not provide new independent labeling freedom.
Real-valued regression and multiclass classification need capacity notions suited to their output and loss. They should not be forced into this binary inspector by an unexplained conversion. A model can also generalize well under a particular distribution even when its unrestricted class has large or infinite VC dimension; the distribution-free worst-case question is stronger.
Check both halves of the dimension claim
-
Increasing thresholds fit labels (0,1) on two ordered inputs. Does that prove dimension at least two? Which assignment prevents shattering?
Answer: No. Shattering requires all four assignments on those same points. The assignment (1,0) is impossible for an increasing threshold, so every ordered pair fails. A single point can receive either label, establishing dimension one on a nonempty ordered domain.
-
Inspect the interval witness on columns (0,1). Verify its four original row IDs. Why are the four reported three-point blockers enough to prove dimension two for this four-point domain?
Answer: Rows 0,5,1,2 project to (0,0), (0,1), (1,0), (1,1). They establish the lower bound. Every three-point subset has the missing pattern (1,0,1), establishing the upper bound. Any shattered four-point set would have shattered three-point subsets, so no larger counterexample is possible.
-
Three collinear points cannot be shattered by planar affine separators. Does that contradict dimension three? What extra assumption changes if the intercept is removed?
Answer: No. A noncollinear triangle is a shattered set of size three; the definition does not require every triple to work. Removing the intercept restricts boundaries to lines through the origin and changes the hypothesis class, so the affine proof cannot simply be reused.
-
The nonempty class contains only the all-zero function, perhaps repeated one hundred times. What are its dimension and growth? Does replacing a threshold t by two parameters u,v with t=u+v change its dimension?
Answer: Its dimension is zero and growth is one for every admissible subset size, including zero. Repetitions add no functions. The two-parameter threshold representation defines the same class, so its dimension remains one when the domain is nonempty and all thresholds are allowed.
Count functions on inputs, not descriptions of functions
Shalev-Shwartz and Ben-David’s 2014 textbook develops the definition, the two-part proof requirement, threshold examples and growth-function bound. Relevant pages were read from the official PDF’s extracted search text: online pp. 70 and 74, whose numbering differs from print. The recurrence explanation and table implementation here are original. The book link is retained without redistributing its restricted-distribution PDF.
The second source is Andrew Ng’s official eleven-page CS229 learning-theory note. Pages 9–10 state shattering, explain redundant parameterizations and contrast noncollinear with collinear triples. The first page identifies the document as Part VI; no date is inferred from its filename. Only the relevant arguments are used, not its informal suggestion that parameter count usually predicts the answer.
The program is tested against an independent bit-set feasibility oracle: each desired label intersects the compatible hypothesis IDs, and an empty intersection exposes a missing assignment. Certificate checks return to original rows. These small exact checks support the finite inspector; the geometric and counting proofs establish the broader mathematical claims.
Make a prediction, then check
Three collinear points cannot be shattered by planar affine separators. Does this rule out VC dimension three?
Learning objectives
- Read the shattering quantifiers and prove a dimension with an existential lower bound and a universal upper bound.
- Compute finite traces, growth and original-row certificates while treating duplicate functions and the empty domain correctly.
- Distinguish threshold, interval and affine geometry from raw parameter counts and from a particular model’s generalization.
Prerequisites & connections
Explore related knowledge →References
- Understanding Machine Learning: From Theory to Algorithms — author online copy
Shai Shalev-Shwartz; Shai Ben-David · 2014 - CS229 Lecture Notes — Part VI: Learning Theory
Andrew Ng
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.
- Nine tests passed. An independent hypothesis-ID bit-set intersection oracle checks all 255 nonempty binary classes on three points, including growth, dimension and original-row lower/upper certificates. It does not compute projected-row dictionaries. Sauer bounds are checked for every returned size.
- Checked 12 threshold/interval restrictions on domain sizes 0–5, duplicate first-row IDs, single-function and empty-domain cases, five finite binary-digit encodings, and invalid inputs. Eight exact triangle witnesses and 125 midpoint/diagonal score identities test geometric calculations; continuous impossibility rests on the prose convexity proof, not the finite coefficient checks.
- Both complete articles contain six matching displays, six stable anchors, four answered exercises and identical Python with seven verified stdout lines. Strict MDX/KaTeX and actual React HTML passed; all seven math annotations match. An author compile found raw prose set braces, which were converted to proper math/text before final validation. Humanizer reread; AI author checks only, review written pending independent review.
- All nine author tests passed. Independently used inclusion-exclusion over nonempty hypothesis subfamilies: their singleton labeling events intersect exactly when all selected rows agree on the inspected columns. This directly counts trace size without projection dictionaries or the author bit-set feasibility oracle. Forty tables, including empty domains, duplicates, correlated columns, thresholds, intervals, deterministic small random cases, label complements and column reversals, matched growth and dimension.
- Replayed 86 witness rows and 78 blockers against original inputs using squared label mismatch, including earliest original-row priority. Checked the lower/upper certificate argument, heredity of shattering, empty-class rejection versus empty-domain dimension zero, growth domain restriction, duplicate semantics and the first-missing bound of at most M+1 probes. Expected hash-table time and retained subset records account for N=0 and distinguish raw R from unique M.
- Read both full articles and metadata. Reviewed Sauer recurrence separately from examples; noncollinear affine interpolation and the convex-hull/diagonal argument prove the continuous planar dimension with the >=0 boundary convention. The one-integer encoding explicitly permits unbounded precision. Statistical IID/measurability conditions, realizability versus shattering and absence of runtime guarantees are stated. No sample-size formula is asserted by this article.
- Strict MDX/KaTeX and actual React HTML passed: each language has six display equations, six stable anchors and four answered exercises; all seven rendered math annotations match. Author tests verify identical program and seven stdout lines. Final five SHA values match the frozen manifest.
- 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:
- Understanding Machine Learning: From Theory to Algorithms — author online copy · Actually read search-extracted text from the official understanding-machine-learning-theory-algorithms.pdf: online p. 69 Definitions 6.2–6.3 for restrictions/shattering and the threshold orientation; p. 70 Definition 6.5 and §6.3 for the existential lower bound and universal upper bound; p. 74 Definition 6.9 and Lemma 6.10 for growth, the binomial bound and union/intersection counting. Online pagination differs from print. Text extraction only; no complete-PDF or visual-page audit, download or redistribution claimed.
- CS229 Lecture Notes — Part VI: Learning Theory · Actually opened the official eleven-page PDF. Section 4, printed p. 9, web lines 411–448, explains redundant real parameterizations and states shattering/VC; pp. 9–10, lines 449–492, gives the noncollinear three-point affine example and warns that collinear triples need not be shattered. Read the following statistical connection at p. 11, lines 495–534, without copying its asymptotic formula. The original integer triangle coefficients and convex-hull argument in this article are independently checked, not a claim that a finite coefficient grid proves the continuous upper bound.
- Understanding Machine Learning: From Theory to Algorithms — author online copy · Direct PDF open returned Internal Error. Independently read official-PDF indexed text: online p. 70 Definition 6.5, §6.3 and threshold example; p. 72 finite-class bound and Theorem 6.7 equivalences; p. 74 Definition 6.9, Lemma 6.10 and the union/intersection counting proof. No complete PDF download or visual-page audit claimed; search crawl date was not treated as publication date.
- CS229 Lecture Notes — Part VI: Learning Theory · Actually opened official eleven-page Part VI notes. Read pp. 9–10 (lines 411–492) on redundant parameters, shattering quantifiers, planar affine example and collinear contrast; p. 11 (lines 495–534) statistical connection. No publication date inferred and no informal parameter-count shortcut adopted.
Related topics