Algorithm Search⌘K

Algorithmadvanced

Spatial pyramid matching

Also called spatial pyramid kernel.

Compare images by histograms of visual words over grids of finer and finer cells, combined by a weighted histogram intersection kernel.

Time
O(M 4^L) denseO(n L) sparse
Space
O(n L) extra
Where
L = the finest pyramid level; M = the number of visual words; n = the total number of features of the two images
Properties
deterministicexactpositive semidefinitesymmetric
Origin
Svetlana Lazebnik, Cordelia Schmid, Jean Ponce, Kristen Grauman, Trevor Darrell, 2006

Spatial pyramid matching compares two images through their visual words and the rough places where those words occur. It cuts the image into a 1×11 \times 1, 2×22 \times 2, 4×44 \times 4, ... grid of cells, counts the words in each cell, and adds up the histogram intersections of the levels with weights that favor matches in small cells. The result is a positive semidefinite kernel, used mostly with a support vector machine for scene and object classification. It is a classification method, not an image retrieval method, and its level 0 is the plain bag of words.

In plain words

A bag of words forgets where things are in the picture. A beach photo has sky at the top and sand at the bottom, and the bag of words cannot see that.

Spatial pyramid matching counts the words again in each half, each quarter and so on, of the image. Two photos get points when they have the same word in the whole image, more points when the word also appears in the same quarter, and still more when it appears in the same small cell. Points for a match are given once, at the finest level where it is found. The total is a similarity that a classifier can use directly.

The problem

Input. Two images of size W×HW \times H (columns by rows), each given as a set of features (u,v,m)(u, v, m): a position with 0≤u≤W0 \le u \le W and 0≤v≤H0 \le v \le H (uu the column, vv the row, origin at the top left), and a visual word m∈{0,…,M−1}m \in \{0, \ldots, M - 1\}. The finest level L≥0L \ge 0.

Cells. Level l∈{0,…,L}l \in \{0, \ldots, L\} cuts the image into 2l×2l2^l \times 2^l equal cells. A feature at (u,v)(u, v) is in cell

(min⁡(⌊u 2l/W⌋,2l−1), min⁡(⌊v 2l/H⌋,2l−1)).\big( \min(\lfloor u\, 2^l / W \rfloor, 2^l - 1),\ \min(\lfloor v\, 2^l / H \rfloor, 2^l - 1) \big).

The minimum puts points on the right or bottom edge into the last cell. A bin at level ll is a pair (cell, word). HXl(b)H_X^l(b) is the number of features of XX in bin bb.

Output. With the histogram intersection Il=∑bmin⁡(HXl(b),HYl(b))I^l = \sum_b \min(H_X^l(b), H_Y^l(b)) (Lazebnik et al., Eq. 1), the kernel is (Eq. 2)

κL(X,Y)=IL+∑l=0L−112L−l(Il−Il+1)=12LI0+∑l=1L12L−l+1Il.\kappa^L(X, Y) = I^L + \sum_{l=0}^{L-1} \frac{1}{2^{L-l}} \big( I^l - I^{l+1} \big) = \frac{1}{2^L} I^0 + \sum_{l=1}^{L} \frac{1}{2^{L-l+1}} I^l .

The second form is Eq. 3. Lazebnik et al. write the kernel for one channel (one word) and add the channels (Eq. 4); taking the word as part of the bin, as here, gives the same sum.

The algorithm

  1. SPM-KERNEL(X, Y, L, W, H)
  2. 1for l = 0 to L do
  3. 2H_X^l ← the counts of X over the bins (cell at level l, word)
  4. 3H_Y^l ← the counts of Y over the same bins
  5. 4I^l ← the sum over the bins b of min(H_X^l(b), H_Y^l(b))
  6. 5kappa ← I^L
  7. 6for l = 0 to L - 1 do kappa ← kappa + (I^l - I^(l+1)) / 2^(L-l)
  8. 7return kappa

In practice each image is stored once as a single long vector: the histograms of all levels, each multiplied by its weight in Eq. 3, concatenated. The histogram intersection of two such vectors is κL\kappa^L, because min⁡(ah,ah′)=amin⁡(h,h′)\min(a h, a h') = a \min(h, h') for a>0a > 0. The vector has M(1+4+⋯+4L)=M(4L+1−1)/3M (1 + 4 + \cdots + 4^L) = M (4^{L+1} - 1)/3 entries; for M=200M = 200 and L=2L = 2 this is 4,200, the size Lazebnik et al. give. They also divide each histogram by the number of features of the image, so that images with many features do not get larger values.

Example

Take a 4×44 \times 4 image, two words aa and bb, and L=2L = 2.

features (u,v,m)(u, v, m)
XX (0.5,0.5,a)(0.5, 0.5, a), (1.5,0.5,a)(1.5, 0.5, a), (3.5,3.5,b)(3.5, 3.5, b), (2.5,0.5,b)(2.5, 0.5, b)
YY (0.5,1.5,a)(0.5, 1.5, a), (3.5,0.5,a)(3.5, 0.5, a), (3.5,2.5,b)(3.5, 2.5, b), (0.5,3.5,b)(0.5, 3.5, b)
  • Level 0, one cell. Both images have two aa and two bb, so I0=2+2=4I^0 = 2 + 2 = 4. The bag of words sees two equal images.
  • Level 1, cells of size 2. XX has aa twice in cell (0,0)(0, 0), bb in (1,1)(1, 1) and bb in (1,0)(1, 0). YY has aa in (0,0)(0, 0), aa in (1,0)(1, 0), bb in (1,1)(1, 1) and bb in (0,1)(0, 1). The common bins are ((0,0),a)((0, 0), a) with min⁡(2,1)=1\min(2, 1) = 1 and ((1,1),b)((1, 1), b) with 1, so I1=2I^1 = 2.
  • Level 2, cells of size 1. No bin is shared, so I2=0I^2 = 0.

By Eq. 2, κ2=0+12(2−0)+14(4−2)=1.5\kappa^2 = 0 + \frac12 (2 - 0) + \frac14 (4 - 2) = 1.5. By Eq. 3, 14⋅4+14⋅2+12⋅0=1.5\frac14 \cdot 4 + \frac14 \cdot 2 + \frac12 \cdot 0 = 1.5. Two matches are new at level 1 and count 1/21/2 each, and two are new at level 0 and count 1/41/4 each. For comparison, κ2(X,X)=4\kappa^2(X, X) = 4, so the layout costs more than half of the similarity. With the histograms divided by the 4 features, the kernel is 1.5/4=0.3751.5/4 = 0.375. With L=1L = 1 instead, κ1=2+12(4−2)=3\kappa^1 = 2 + \frac12(4 - 2) = 3.

Correctness

The proof in the correctness file shows four facts. First, Eq. 2 and Eq. 3 are equal, by collecting the coefficient of each IlI^l. Second, Il≥Il+1I^l \ge I^{l+1}: each bin at level ll is the union of four bins at level l+1l + 1 with the same word, and min⁡(a1+⋯+a4,b1+⋯+b4)≥∑jmin⁡(aj,bj)\min(a_1 + \cdots + a_4, b_1 + \cdots + b_4) \ge \sum_j \min(a_j, b_j); so Il−Il+1≥0I^l - I^{l+1} \ge 0 is the number of matches that are new at level ll, and each new match has a nonnegative weight. Third, IlI^l is the size of a largest one-to-one matching between XX and YY that pairs only features with the same word in the same level-ll cell; the tests compare it with a matching by augmenting paths. Fourth, κL\kappa^L is a positive semidefinite kernel, because min⁡(a,b)=∫0∞[t<a][t<b] dt\min(a, b) = \int_0^\infty [t < a][t < b]\, dt for a,b≥0a, b \ge 0 makes each intersection an inner product, and a sum of such kernels with nonnegative weights is again one. Grauman and Darrell (2005) prove the same for their pyramid match.

Proof: The spatial pyramid kernel counts new matches per level with nonnegative weights and is positive semidefinitefull

We use the notation of the page. XX and YY are finite sets of features (u,v,m)(u, v, m). At level ll, a bin is a pair (cell, word), HXl(b)H_X^l(b) is the number of features of XX in bin bb, and Il=∑bmin⁡(HXl(b),HYl(b))I^l = \sum_b \min(H_X^l(b), H_Y^l(b)). Lines L1 to L4 compute exactly these counts and sums, by the definitions, so the claims below are about the values that SPM-KERNEL returns.

Lemma 1 (the cells nest). For l<Ll < L, every bin of level l+1l + 1 lies inside exactly one bin of level ll with the same word, and every bin of level ll is the union of the four bins of level l+1l + 1 inside it with the same word.

Proof. Let s=2ls = 2^l and c(u)=min⁡(⌊us/W⌋,s−1)c(u) = \min(\lfloor u s / W \rfloor, s - 1) the column index at level ll, and c′(u)=min⁡(⌊2us/W⌋,2s−1)c'(u) = \min(\lfloor 2 u s / W \rfloor, 2s - 1) the one at level l+1l + 1. We show c(u)=⌊c′(u)/2⌋c(u) = \lfloor c'(u)/2 \rfloor for 0≤u≤W0 \le u \le W. If u<Wu < W, then c(u)=⌊y⌋c(u) = \lfloor y \rfloor and c′(u)=⌊2y⌋c'(u) = \lfloor 2y \rfloor with y=us/W<sy = us/W < s, and ⌊⌊2y⌋/2⌋=⌊y⌋\lfloor \lfloor 2y \rfloor / 2 \rfloor = \lfloor y \rfloor. If u=Wu = W, then c(u)=s−1c(u) = s - 1 and c′(u)=2s−1c'(u) = 2s - 1, and ⌊(2s−1)/2⌋=s−1\lfloor (2s - 1)/2 \rfloor = s - 1. The same holds for the rows. So the level-ll cell of a feature is a function of its level-(l+1)(l+1) cell, and each level-ll cell (i,j)(i, j) contains the four cells (2i+a,2j+b)(2i + a, 2j + b), a,b∈{0,1}a, b \in \{0, 1\}. The word is the same at all levels. □\square

Theorem 1 (the two forms agree). IL+∑l=0L−12−(L−l)(Il−Il+1)=2−LI0+∑l=1L2−(L−l+1)IlI^L + \sum_{l=0}^{L-1} 2^{-(L-l)} (I^l - I^{l+1}) = 2^{-L} I^0 + \sum_{l=1}^{L} 2^{-(L-l+1)} I^l.

Proof. Collect the coefficient of each IlI^l on the left. I0I^0 appears once, in the term l=0l = 0, with 2−L2^{-L}. For 1≤l≤L−11 \le l \le L - 1, IlI^l appears with +2−(L−l)+2^{-(L-l)} in term ll and with −2−(L−l+1)-2^{-(L-l+1)} in term l−1l - 1, so its coefficient is 2−(L−l)−2−(L−l+1)=2−(L−l+1)2^{-(L-l)} - 2^{-(L-l+1)} = 2^{-(L-l+1)}. ILI^L appears with +1+1 alone and −2−1-2^{-1} in term L−1L - 1, so its coefficient is 1/2=2−(L−L+1)1/2 = 2^{-(L-L+1)}. If L=0L = 0 both sides are I0I^0. □\square

Lemma 2 (intersection is a maximum matching). Call a matching at level ll a set of disjoint pairs (x,y)∈X×Y(x, y) \in X \times Y such that xx and yy are in the same bin of level ll. Then the largest such matching has exactly IlI^l pairs.

Proof. The pairs never connect different bins, so a matching is a union of matchings inside the bins. Inside bin bb any pairing of HXl(b)H_X^l(b) features with HYl(b)H_Y^l(b) features has at most min⁡(HXl(b),HYl(b))\min(H_X^l(b), H_Y^l(b)) pairs, and pairing them in any order reaches this number. Summing over the bins gives IlI^l. □\square

Lemma 3 (monotone). Il≥Il+1I^l \ge I^{l+1} for 0≤l<L0 \le l < L.

Proof. By Lemma 1, a matching at level l+1l + 1 pairs features that are in the same bin at level l+1l + 1, so also in the same bin at level ll. So it is also a matching at level ll, and by Lemma 2 Il+1≤IlI^{l+1} \le I^l. In terms of counts: if a bin at level ll splits into bins with counts a1,…,a4a_1, \ldots, a_4 and b1,…,b4b_1, \ldots, b_4, then min⁡(∑jaj,∑jbj)≥∑jmin⁡(aj,bj)\min(\sum_j a_j, \sum_j b_j) \ge \sum_j \min(a_j, b_j), since the right side is at most ∑jaj\sum_j a_j and at most ∑jbj\sum_j b_j. □\square

So ILI^L is the number of matches at the finest level, and Il−Il+1≥0I^l - I^{l+1} \ge 0 is the number of matches that a largest matching gains when the cells grow from level l+1l + 1 to level ll. The kernel gives weight 1 to the finest matches and 2−(L−l)2^{-(L-l)} to those new at level ll, as the page says.

Theorem 2 (positive semidefinite). For any finite list of feature sets X(1),…,X(N)X^{(1)}, \ldots, X^{(N)}, the matrix Gij=κL(X(i),X(j))G_{ij} = \kappa^L(X^{(i)}, X^{(j)}) is symmetric and positive semidefinite. The same holds when each histogram is first divided by the number of features of its image.

Proof. Symmetry is clear since min⁡\min is symmetric. For a,b≥0a, b \ge 0, min⁡(a,b)=∫0∞[t<a] [t<b] dt\min(a, b) = \int_0^\infty [t < a]\,[t < b]\, dt, where [⋅][\cdot] is 1 if the condition holds and 0 otherwise. So for reals c1,…,cNc_1, \ldots, c_N and one bin bb of level ll, with hi=HX(i)l(b)h_i = H^l_{X^{(i)}}(b),

∑i,jcicjmin⁡(hi,hj)=∫0∞(∑ici[t<hi])2dt≥0.\sum_{i,j} c_i c_j \min(h_i, h_j) = \int_0^\infty \Big( \sum_i c_i [t < h_i] \Big)^2 dt \ge 0.

So min⁡(hi,hj)\min(h_i, h_j) is a positive semidefinite kernel for each bin. A sum of positive semidefinite kernels is positive semidefinite, so IlI^l is one, and so is ∑lalIl\sum_l a_l I^l for al≥0a_l \ge 0. By Theorem 1, κL\kappa^L has this form with the positive weights 2−L2^{-L} and 2−(L−l+1)2^{-(L-l+1)}. Dividing the histograms of image ii by ni>0n_i > 0 replaces hih_i by hi/ni≥0h_i/n_i \ge 0, and the same argument applies. □\square

Corollary (the concatenated vector). Let ϕ(X)\phi(X) be the concatenation, over the levels, of the histograms of level ll multiplied by a0=2−La_0 = 2^{-L} and al=2−(L−l+1)a_l = 2^{-(L-l+1)} for l≥1l \ge 1. Then ∑imin⁡(ϕ(X)i,ϕ(Y)i)=κL(X,Y)\sum_i \min(\phi(X)_i, \phi(Y)_i) = \kappa^L(X, Y).

Proof. For a>0a > 0, min⁡(ah,ah′)=amin⁡(h,h′)\min(a h, a h') = a \min(h, h'). Summing over the entries of level ll gives alIla_l I^l, and Theorem 1 gives the claim. □\square

What is not claimed. The weights are a design choice taken from the pyramid match kernel. Nothing here says that the kernel classifies well; that is a benchmark result.

Complexity

In the real RAM with a hash table or a direct index for the bins, lines L2 and L3 cost O(n)O(n) per level for nn features in total, and line L4 costs O(n)O(n) per level with sparse histograms, since at most nn bins are nonzero. The whole kernel costs O(n(L+1))O(n (L + 1)) time and O(n(L+1))O(n (L + 1)) space. With dense vectors of length M(4L+1−1)/3M (4^{L+1} - 1)/3 it costs O(M4L)O(M 4^L). For classification, an SVM needs the kernel between all pairs of NN training images, so the Gram matrix costs O(N2)O(N^2) kernel evaluations. This cost is the main limit of the method at scale.

The cell index needs one multiplication and one floor per level and coordinate. Quantizing the descriptors to words, which comes before this algorithm, costs O(nMD)O(n M D) with a linear scan over MM centers of dimension DD.

Properties

  • Exact on integers. The weights are powers of 1/21/2 and the counts are integers, so the kernel is a dyadic rational. The code uses exact fractions.
  • Symmetric and positive semidefinite. So it is a valid SVM kernel. The tests check the Gram matrices of random sets with exact elimination.
  • κL(X,X)=∣X∣\kappa^L(X, X) = |X| without normalization, and 1 with it. The kernel is largest for identical images when the counts are equal.
  • Level 0 is the bag of words. κ0\kappa^0 is the histogram intersection of the word histograms.
  • Not translation invariant. The grid is fixed to the image frame. An object that moves by half a cell can change the counts of every finer level. This is wanted for scenes, whose layout is fairly stable, and a weakness for objects at random positions.
  • The weights are a design choice. The weight 1/2L−l1/2^{L-l} of a new match at level ll follows the pyramid match of Grauman and Darrell. It is a heuristic, not derived from a model of the data.

Variants and improvements

  • Pyramid match kernel (Grauman and Darrell 2005). The pyramid is over the descriptor space, with bins that double in width, and there is no image layout. Spatial pyramid matching is the same weighting with the image plane as the space and the words as channels.
  • Other features per cell. Any per-cell vector can be pooled in the pyramid, for example HOG like gradient features, Fisher vectors or VLAD. With such vectors the cells are usually concatenated and compared with a linear kernel.
  • Other pyramids. A 1×31 \times 3 level of horizontal bands is common for scenes, since sky, objects and ground lie in bands.
  • Max pooling and sparse coding. Later work replaces the counts by the maximum of soft assignments or of sparse codes over each cell and uses a linear SVM.
  • Explicit feature maps. The intersection kernel can be approximated by a finite-dimensional feature map, so that a linear SVM can be trained on large data.

When to use it

Use the spatial pyramid for whole-image classification, especially of scenes, where the layout of a category is stable: sky above, ground below. For object instances at arbitrary positions and scales it helps less, and spatial verification is a better way to use geometry. As a classical pipeline (dense SIFT, words, a pyramid, an SVM) it is a strong baseline. Convolutional networks later replaced it on most benchmarks.

Pitfalls

  • Points on the far edge. Without the minimum in the cell index, a point with u=Wu = W falls into a cell that does not exist.
  • Different image sizes. Use the size of each image for its own cells. The pyramid then compares relative positions, which assumes that the two images frame the scene in a similar way.
  • Forgetting the normalization by the number of features. Without it, images with many features get large kernel values with every other image.
  • Counting a match twice. Eq. 2 counts each match once, at its finest level. If the weights 1/2L−l1/2^{L-l} of Eq. 2 are put on the IlI^l themselves instead of on the differences, a match found at level LL is counted again at every coarser level.
  • Too many levels. At fine levels the cells hold few features and the intersections are almost zero; they add noise and cost. Lazebnik et al. found little gain beyond L=2L = 2 on their data, which is a benchmark observation.

Implementations

The Python code builds sparse histograms per level, computes the level intersections and the kernel by Eq. 2 and by Eq. 3, and builds the concatenated weighted vector, all with exact fractions. The tests check the example of this page, the cell rule at the far edge, the agreement of the three forms on random sets, the equality of each IlI^l with a maximum matching found by augmenting paths, the decrease of IlI^l with the level, the self kernel, level 0 as the bag of words, and the positive semidefiniteness of Gram matrices by exact elimination.

Each implementation follows the pseudocode above. A comment @line links a line of code to a line of the pseudocode. Point at a line of the pseudocode to see the matching code. The build runs the native tests of each language.

spatial_pyramid_matching.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spatial-pyramid-matching/. The authors are listed in prov/QX9B5V.jsonl.
"""Spatial pyramid matching (Lazebnik, Schmid and Ponce, CVPR 2006).

A feature is a triple (u, v, m): a position in a W x H image (u the column,
v the row, 0 <= u <= W and 0 <= v <= H) and a visual word m in 0..M-1.
Level l of the pyramid cuts the image into 2^l x 2^l equal cells; a feature
falls into cell (min(floor(u 2^l / W), 2^l - 1), min(floor(v 2^l / H), 2^l - 1)).
I^l is the histogram intersection of the two images at level l over the bins
(cell, word), and the kernel is
    K = I^L + sum_{l=0}^{L-1} (I^l - I^{l+1}) / 2^(L - l).
Histograms are sparse dicts, so the cost is O(n L) for n features, plus the
size of the smaller dict per intersection. Weights are exact Fractions, so
the kernel is exact on integer counts. Standard library only.
"""

from fractions import Fraction


def cell_of(u, v, level, W, H):
    """The cell (cu, cv) of position (u, v) at a level; points on the far edge go to the last cell."""
    s = 1 << level
    cu = min(int((u * s) // W), s - 1)
    cv = min(int((v * s) // H), s - 1)
    return cu, cv


def level_histogram(features, level, W, H, weight=1):
    """Sparse histogram {(cu, cv, m): weight times count} of the features at one level."""
    h = {}
    for u, v, m in features:
        key = cell_of(u, v, level, W, H) + (m,)
        h[key] = h.get(key, 0) + weight
    return h


def intersection(h1, h2):
    """Histogram intersection: the sum over bins of min(h1[b], h2[b])."""
    if len(h2) < len(h1):
        h1, h2 = h2, h1
    return sum(min(c, h2[b]) for b, c in h1.items() if b in h2)


def level_intersections(X, Y, L, W, H, normalize=False):
    """The list I^0, ..., I^L. With normalize, each histogram is divided by its number of features."""
    wx = Fraction(1, len(X)) if normalize and X else 1
    wy = Fraction(1, len(Y)) if normalize and Y else 1
    out = []
    for level in range(L + 1):  # @line L1
        hx = level_histogram(X, level, W, H, wx)  # @line L2
        hy = level_histogram(Y, level, W, H, wy)  # @line L3
        out.append(intersection(hx, hy))  # @line L4
    return out


def spm_kernel(X, Y, L, W, H, normalize=False):
    """The spatial pyramid match kernel, Eq. (2) of Lazebnik et al."""
    I = level_intersections(X, Y, L, W, H, normalize)
    kappa = Fraction(I[L])  # @line L5
    for level in range(L):  # @line L6
        kappa += Fraction(I[level] - I[level + 1]) / (1 << (L - level))
    return kappa  # @line L7


def level_weight(level, L):
    """Weight of level l in Eq. (3): 1/2^L for l = 0, and 1/2^(L - l + 1) for l >= 1."""
    if level == 0:
        return Fraction(1, 1 << L)
    return Fraction(1, 1 << (L - level + 1))


def spm_kernel_eq3(X, Y, L, W, H, normalize=False):
    """The same kernel as a weighted sum of the level intersections, Eq. (3)."""
    I = level_intersections(X, Y, L, W, H, normalize)
    return sum(level_weight(level, L) * I[level] for level in range(L + 1))


def pyramid_vector(X, M, L, W, H, normalize=False):
    """The concatenated weighted histograms as a dense list of length M (4^(L+1) - 1) / 3.

    The histogram intersection of two such vectors is the pyramid kernel.
    """
    wx = Fraction(1, len(X)) if normalize and X else 1
    out = []
    for level in range(L + 1):
        s = 1 << level
        h = level_histogram(X, level, W, H, wx)
        a = level_weight(level, L)
        for cv in range(s):
            for cu in range(s):
                for m in range(M):
                    out.append(a * h.get((cu, cv, m), 0))
    return out


def dense_intersection(p, q):
    return sum(min(a, b) for a, b in zip(p, q))
test_spatial_pyramid_matching.py 135 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/spatial-pyramid-matching/. The authors are listed in prov/QX9B5V.jsonl.

import random
from fractions import Fraction

from spatial_pyramid_matching import (cell_of, dense_intersection, intersection,
                                      level_histogram, level_intersections,
                                      pyramid_vector, spm_kernel, spm_kernel_eq3)

X = [(0.5, 0.5, 0), (1.5, 0.5, 0), (3.5, 3.5, 1), (2.5, 0.5, 1)]
Y = [(0.5, 1.5, 0), (3.5, 0.5, 0), (3.5, 2.5, 1), (0.5, 3.5, 1)]


def random_features(rng, n, M, W, H):
    return [(rng.randrange(W), rng.randrange(H), rng.randrange(M)) for _ in range(n)]


def max_matching(X, Y, level, W, H):
    """Brute force: the largest one-to-one matching of X to Y that pairs only
    features with the same word in the same cell, by augmenting paths."""
    ok = [[cell_of(x[0], x[1], level, W, H) == cell_of(y[0], y[1], level, W, H) and x[2] == y[2]
           for y in Y] for x in X]
    match_of_y = [-1] * len(Y)

    def augment(i, seen):
        for j in range(len(Y)):
            if ok[i][j] and not seen[j]:
                seen[j] = True
                if match_of_y[j] < 0 or augment(match_of_y[j], seen):
                    match_of_y[j] = i
                    return True
        return False

    return sum(1 for i in range(len(X)) if augment(i, [False] * len(Y)))


def is_psd(G):
    """Exact test with Fractions: symmetric Gaussian elimination (LDL^T)."""
    A = [[Fraction(t) for t in row] for row in G]
    n = len(A)
    for p in range(n):
        if A[p][p] < 0:
            return False
        if A[p][p] == 0:
            if any(A[p][j] != 0 for j in range(p + 1, n)):
                return False
            continue
        for i in range(p + 1, n):
            f = A[i][p] / A[p][p]
            for j in range(p + 1, n):
                A[i][j] -= f * A[p][j]
    return True


def test_example_of_the_page():
    assert level_intersections(X, Y, 2, 4, 4) == [4, 2, 0]
    assert spm_kernel(X, Y, 2, 4, 4) == Fraction(3, 2)
    assert spm_kernel(X, Y, 1, 4, 4) == 3
    assert spm_kernel(X, X, 2, 4, 4) == 4
    assert spm_kernel(X, Y, 2, 4, 4, normalize=True) == Fraction(3, 8)


def test_cell_rule_and_far_edge():
    assert cell_of(0, 0, 2, 8, 8) == (0, 0)
    assert cell_of(1.99, 2.0, 2, 8, 8) == (0, 1)
    assert cell_of(8, 8, 2, 8, 8) == (3, 3)
    assert cell_of(7, 3, 0, 8, 8) == (0, 0)


def test_two_forms_and_the_vector_agree():
    rng = random.Random(1)
    for _ in range(30):
        M, L, W, H = rng.randint(1, 4), rng.randint(0, 3), rng.choice([8, 12]), rng.choice([8, 16])
        A = random_features(rng, rng.randint(0, 12), M, W, H)
        B = random_features(rng, rng.randint(0, 12), M, W, H)
        for norm in (False, True):
            k2 = spm_kernel(A, B, L, W, H, norm)
            assert k2 == spm_kernel_eq3(A, B, L, W, H, norm)
            assert k2 == dense_intersection(pyramid_vector(A, M, L, W, H, norm), pyramid_vector(B, M, L, W, H, norm))


def test_intersection_is_a_maximum_matching():
    rng = random.Random(2)
    for _ in range(40):
        M, W, H = rng.randint(1, 3), 8, 8
        A = random_features(rng, rng.randint(0, 8), M, W, H)
        B = random_features(rng, rng.randint(0, 8), M, W, H)
        I = level_intersections(A, B, 3, W, H)
        for level in range(4):
            assert I[level] == max_matching(A, B, level, W, H)


def test_intersections_decrease_with_the_level():
    rng = random.Random(3)
    for _ in range(50):
        A = random_features(rng, 15, 3, 16, 16)
        B = random_features(rng, 15, 3, 16, 16)
        I = level_intersections(A, B, 4, 16, 16)
        assert all(I[level] >= I[level + 1] for level in range(4))


def test_self_kernel_and_level_zero_is_bag_of_words():
    rng = random.Random(4)
    A = random_features(rng, 9, 3, 8, 8)
    B = random_features(rng, 7, 3, 8, 8)
    assert spm_kernel(A, A, 3, 8, 8) == 9
    assert spm_kernel(A, A, 3, 8, 8, normalize=True) == 1
    bow_a, bow_b = {}, {}
    for _, _, m in A:
        bow_a[m] = bow_a.get(m, 0) + 1
    for _, _, m in B:
        bow_b[m] = bow_b.get(m, 0) + 1
    assert spm_kernel(A, B, 0, 8, 8) == intersection(bow_a, bow_b)


def test_gram_matrices_are_positive_semidefinite():
    rng = random.Random(5)
    for _ in range(4):
        sets = [random_features(rng, rng.randint(1, 8), 2, 8, 8) for _ in range(7)]
        for norm in (False, True):
            G = [[spm_kernel(a, b, 2, 8, 8, norm) for b in sets] for a in sets]
            assert is_psd(G)
    assert not is_psd([[1, 2], [2, 1]])


def test_layout_matters_only_above_level_zero():
    moved = [(3.5 - u, 3.5 - v, m) for u, v, m in X]
    assert level_intersections(X, moved, 0, 4, 4) == [4]
    assert spm_kernel(X, moved, 2, 4, 4) < spm_kernel(X, X, 2, 4, 4)


def test_vector_length():
    assert len(pyramid_vector([], 200, 2, 8, 8)) == 4200
    assert len(level_histogram(X, 2, 4, 4)) == 4

History

Grauman and Darrell (2005) proposed the pyramid match kernel, an approximate optimal matching of two sets of feature vectors through histograms with bins that double in size. Lazebnik, Schmid and Ponce (2006) applied the same idea to the image plane, with one channel per visual word. On the 15 scene categories data set with M=200M = 200 words, they report a mean recognition rate of 72.2 percent for the bag of words (L=0L = 0) and 81.1 percent for the pyramid with L=2L = 2, and 64.6 percent on Caltech-101 with 30 training images per class (Section 5). These are benchmark results for their features and training splits. The spatial pyramid then became a standard part of image classification systems, including those built on Fisher vectors and sparse codes.

References

  1. Svetlana Lazebnik, Cordelia Schmid and Jean Ponce, Beyond bags of features: spatial pyramid matching for recognizing natural scene categories, CVPR 2006, vol. 2, 2169-2178, Section 3.1 (histogram intersection, Eq. 1, and the pyramid match kernel, Eq. 2 and 3), Section 3.2 (one channel per visual word, Eq. 4, and the concatenated weighted histograms), Section 5 (results on the 15 scene categories and Caltech-101)
  2. Kristen Grauman and Trevor Darrell, The pyramid match kernel: discriminative classification with sets of image features, ICCV 2005, vol. 2, 1458-1465, The pyramid match kernel over a multi-resolution histogram in feature space, and its proof that it is a Mercer kernel
  3. Jorge Sanchez, Florent Perronnin, Thomas Mensink and Jakob Verbeek, Image classification with the Fisher vector: theory and practice, International Journal of Computer Vision 105(3), 2013, 222-245, The use of spatial pyramids with Fisher vectors
  4. Richard Szeliski, Computer Vision, Algorithms and Applications, second edition, Springer, 2022, Section 6.2, Image classification

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH1 sketch
  • a full proof of time.dense
  • a full proof of time.sparse
  • a full proof of space.extra
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (python)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW2 basic
  • a scene preset for the example