VC dimension and the Sauer-Shelah lemma
For infinite classes, count distinct labelings on n points instead of log|H|. Define shattering, growth function and VC dimension, calculate geometric examples including half-spaces via Radon, and prove Sauer-Shelah.
After this lesson you can
- Define shattering, growth function Π_H(n) and VC dimension.
- Calculate VC dimension of thresholds, intervals, rectangles and half-spaces in R^d, using Radon’s theorem for the latter.
- Construct a one-parameter class with infinite VC dimension and explain why VC dimension is not parameter count.
- Prove Sauer-Shelah by induction and derive Π_H(n) ≤ (en/d)^d for n ≥ d.
- Calculate the growth function of a small class by brute force and verify Sauer numerically.
Before you start
Counting functions on a sample
Half-planes have infinitely many positions and orientations. Applying the finite-class bound directly with is useless. On a finite set of points, however, only the distinct labelings produced there matter. That count can be small even for infinitely many rules.
Proving dimension requires two distinct pieces: exhibit one shattered set of points and prove that no set of points is shattered. A degenerate configuration may not be shattered even though another of the same size is. Do not confuse the trace on one sample with the maximum over all samples.
For example, if a class realizes only vectors 000, 001 and 111 on three points, its trace there has size 3, even if it contains infinitely many distinct formulas. It does not shatter those three points because five labelings are missing. The growth function at three is the largest trace size among all three-point sets; another set may have more. If an -point set is shattered, each subset is shattered too: extend any labeling of the subset to the remaining points and use the corresponding witness.
Trace counting depends on the rule class and how boundaries are treated. Here a binary rule includes boundary points as positive; negatives must lie outside. On a finite separable sample there is positive slack relative to negatives, so the boundary can be shifted slightly to obtain strict separation between both groups. Figures use finite-precision coordinates and calculations; proofs are understood over real numbers.
In the game, drag three to six points and select a class. Each cell represents a labeling; existence of a witness is checked and drawn when one exists. For disks the set of feasible centers is clipped numerically, with points snapped to a grid and finite tolerance. For degenerate convex sets of one or two positives, their convex hull is shown: a sufficiently small convex neighborhood can avoid negatives outside it. The figure’s decisions are a finite experiment, not a proof for all sets.
Each cell number encodes its labeling: add for each positive point . For example, with four points, cell 5 makes points 1 and 3 positive. At the vertices of a convex quadrilateral, the two diagonals cross; that pattern and its complement cannot be separated by a line. Move one point inside the triangle formed by the other three and another certificate appears: a half-plane cannot include all three vertices while excluding the interior point.
Geometric bounds
For thresholds on , one point is shattered, but two ordered points cannot realize pattern 1,0: VC = 1. Intervals shatter two points, while three ordered points cannot realize 1,0,1: VC = 2. These classes include the empty rule through an appropriate choice or as an explicit case.
For axis-aligned rectangles in the plane, the four points and are shattered: each omitted point is extreme in some coordinate, so the rectangle fitted to positives excludes it. For five points, select one representative of each minimum and maximum along both coordinates. With at most four representatives, one point remains inside the rectangle enclosing the others. The labeling excluding only that point is unrealizable; therefore VC = 4, even with coordinate ties.
Planar disks have VC = 3. Three vertices of an equilateral triangle are shattered: small disks isolate one, a disk with one side as diameter contains its endpoints and excludes the third, and disks exist for all or none. For four points , there is a nontrivial affine dependence , , with coefficients of both signs. Membership in a disk is determined by the sign of . Summing with those coefficients,
a constant independent of the disk. The two complementary labelings that assign 1 to positive coefficients and 0 to negative coefficients, or the reverse, would require strictly opposite signs for that sum. At least one is impossible. Zero coefficients receive arbitrary labels. Thus no four-point set is shattered.
Planar convex sets with no vertex limit have infinite VC dimension: for each choose distinct points on a circle. The hull of any subset of positives excludes the remaining circle points; empty and singleton subsets are handled with small regions. Limiting the number of sides changes the class and needs a different bound; no exact dimension follows from one picture.
The difference between disks and convex sets illustrates why counting “smooth geometric families” is insufficient. Every disk is convex, but not every convex polygon is a disk. The first class shatters no four-point set; the second, if allowed as many vertices as needed, can select any subset of points in convex position. Class inclusion only guarantees the smaller class’s growth function does not exceed the larger one’s.
Half-spaces and Radon
Affine half-spaces in have VC dimension . For the lower bound, choose affinely independent points. For any sign assignment an affine function takes those values on the points: solve an invertible system with unknowns. Its sign realizes the labeling.
For the upper bound, take any points. Their augmented vectors are linearly dependent, so there are nonzero coefficients with and . There are positive and negative coefficients. Normalize each group by the sum of its coefficient magnitudes: both groups give the same point as a convex combination. Zero coefficients may be assigned anywhere. This is Radon’s partition. An affine function cannot be positive on one group and negative on the other when their hulls intersect, because it would take incompatible signs at the common point. Thus no -point set is shattered.
The figure seeks a partition and an intersection of hulls; degenerate configurations can have several valid ones. Numerical precision limits belong to the visual implementation. The algebraic argument also covers repeated or collinear points.
Sauer-Shelah lemma
If , the Sauer-Shelah lemma states
To prove the first inequality, take a family of subsets of with VC dimension at most . Project each subset onto the first indices and call the family of distinct projections . Call the projections occurring with both possibilities for the last index. Each projection contributes once to and, if it has two extensions, once more to : .
The dimension of is at most . That of is at most : if shattered indices, both extensions of each trace would shatter those indices plus the last in . By induction on , with bases or ,
For the second inequality take . Since for ,
The dichotomy concerns the growth function of a fixed class: if its VC dimension is infinite, it shatters sets of every size and ; if finite, the lemma gives at most polynomial growth in for fixed . It does not claim every finite-dimensional class attains the bound or every particular trace has that size.
The sum equals when , since it then includes all binomial coefficients. When , some are omitted and growth is controlled by a polynomial of degree . For , a nonempty class realizes only one trace on each set and is treated separately from , which divides by .
The figure uses exact formulas for intervals and affine half-planes in general position. For rectangles it enumerates all distinct coordinate orders up to and shows the maximum found among those generic configurations; this is an enumeration result, not a proof for degenerate sets. The vertical scale is base-2 logarithmic and Sauer is a bound, not necessarily an attained curve.
On a line with ordered points, an interval selects a consecutive block: there are nonempty blocks and one empty trace. For affine half-planes in the plane, points in general position give labelings for . The expressions describe different classes although both are infinite. The graph compares their logarithms to show when the curve separates from available counts.
import numpy as np
from itertools import product
from math import comb
from scipy.optimize import linprog
def halfplane_realizable(X, labels):
sign=2*np.asarray(labels)-1
A=-sign[:,None]*np.column_stack((X,np.ones(len(X))))
# Una separación estricta finita puede reescalarse a margen 1.
return linprog(np.zeros(3),A_ub=A,b_ub=-np.ones(len(X)),bounds=[(None,None)]*3,method='highs').success
def trace_count(X,oracle):
return sum(oracle(X,y) for y in product([0,1],repeat=len(X)))
rng=np.random.default_rng(1306)
for n in range(1,7):
X=rng.normal(size=(n,2))
observed=trace_count(X,halfplane_realizable)
sauer=sum(comb(n,i) for i in range(min(3,n)+1))
print('n',n,'trazas',observed,'Sauer',sauer,'2ⁿ',2**n)
assert observed <= sauerThe program counts traces on the generated set; it does not automatically maximize over all possible positions. Margin 1 is legitimate for strict separation of a finite set because it can be rescaled. A negative result from the numerical optimizer must be interpreted with its tolerance; it does not replace Radon’s proof.
import numpy as np
from itertools import product
from scipy.optimize import linprog
from scipy.spatial import ConvexHull
def rectangle_realizable(X,y):
P=X[np.asarray(y,dtype=bool)]; N=X[~np.asarray(y,dtype=bool)]
if not len(P): return True
lo,hi=P.min(axis=0),P.max(axis=0)
return not np.any(np.all((N>=lo)&(N<=hi),axis=1))
def disk_realizable(X,y):
P=X[np.asarray(y,dtype=bool)]; N=X[~np.asarray(y,dtype=bool)]
if not len(P) or not len(N): return True
pairs=[(p,q) for p in P for q in N]
A=np.array([-2*(p-q) for p,q in pairs])
b=np.array([-(p@p-q@q)-1e-7 for p,q in pairs])
return linprog(np.zeros(2),A_ub=A,b_ub=b,bounds=[(None,None)]*2,method='highs').success
def polygon_witness(X,y,k=3):
P=X[np.asarray(y,dtype=bool)]; N=X[~np.asarray(y,dtype=bool)]
if not len(P) or not len(N): return True
if len(P)==1: return np.all(np.linalg.norm(N-P[0],axis=1)>1e-8)
if len(P)==2:
u=P[1]-P[0]; t=np.clip((N-P[0])@u/(u@u),0,1)
return np.all(np.linalg.norm(N-(P[0]+t[:,None]*u),axis=1)>1e-8)
hull=ConvexHull(P)
if len(hull.vertices)>k: return False # criterio suficiente, no oráculo completo
return not np.any(np.all(N@hull.equations[:,:-1].T+hull.equations[:,-1]<=1e-8,axis=1))
def shattered(X,oracle):
return all(oracle(X,y) for y in product([0,1],repeat=len(X)))
cross=np.array([[-1,0],[1,0],[0,-1],[0,1]],float)
triangle=np.array([[0,0],[1,0],[.5,.8660254]])
print('rectángulo, cuatro extremos:',shattered(cross,rectangle_realizable))
print('discos, triángulo:',shattered(triangle,disk_realizable))
print('triángulos convexos, tres puntos:',shattered(triangle,polygon_witness))
rng=np.random.default_rng(1306)
candidates=[rng.normal(size=(4,2)) for _ in range(10)]
print('búsqueda de 4 puntos: rectángulo / disco / testigo poligonal',
*(sum(shattered(X,f) for X in candidates) for f in [rectangle_realizable,disk_realizable,polygon_witness]))The preceding polygon check is sufficient, not complete: if the positive hull has more than vertices, another polygon of vertices might contain it and avoid negatives. With one or two positives, provided no negative lies in their hull, a sufficiently narrow triangle can be chosen around it. Thus a found witness proves a lower bound; a failed attempt does not prove impossibility. The program avoids attributing an exact VC dimension to that search.
One parameter can have infinite capacity
Consider with one parameter . For any , take and choose digits for label 1, or for label 0. Define integer and . The fractional part of lies between 0.2 and 0.3 if , and between 0.7 and 0.8 if . The sine is respectively positive or negative. Adding a more significant digit leaves earlier phases unchanged because it adds an integer to each. Thus sets of any size are shattered: VC dimension is infinite with one parameter.
The figure uses six digits and finite-precision arithmetic. The mathematical proof allows arbitrarily large integers and does not guarantee that a fixed-precision computer represents unlimited frequencies. Parameter count alone does not determine VC dimension. For ReLU networks, Bartlett, Harvey, Liaw and Mehrabian prove an upper bound and lower constructions under their conditions on weights and depth; these are not a universal equality for every architecture.
Exercises
Step 1 of 2. Why can d+1 affinely independent points receive arbitrary signs?
Step 1 of 2. How are the sizes related?
def is_shattered(points, realizable):
pass
def vc_lower_bound(sampler, realizable, k_max):
pass