Curves in Hilbert spaces

The decision procedure, the bisection and the exact distance also take curves whose vertices are known only through the distances between them: points of a Hilbert space, possibly of infinite dimension, such as the feature space of a kernel. Then the Fréchet distance compares sequences of objects that have no coordinates at all (frames under a kernel, distributions, strings or graphs under a kernel for them), and curves of very high dimension are compared at a cost that does not grow with the dimension once the distances between their vertices are known.

using FrechetDist
using BasicCompGeometry: HilbertSpace, vcurve

# frames: any vector of items; here frames of two video clips, 1:95 and 96:180.
s2 = 25.0
S = HilbertSpace(frames, (x, y) -> -2expm1(-sum(abs2, x .- y) / s2))  # Gaussian kernel
P, Q = vcurve(S, 1:95), vcurve(S, 96:180)

frechet_c_decide_exact(P, Q, 0.5)   # is the distance at most 0.5?
frechet_c_compute_bisect(P, Q)      # the distance, to 1e-10 relative
frechet_c_compute_exact(P, Q)       # the exact distance

The machinery

Spaces and virtual points (BasicCompGeometry 0.7.1). A HilbertSpace is a list of items, its input vertices, with a function giving the squared distance of two of them in some Hilbert space H:

ConstructorThe squared distance of items x, y
HilbertSpace(items, dist2)dist2(x, y), given directly (the most accurate choice when it can be computed without cancellation, as for the Gaussian kernel above)
HilbertSpace(items; kernel = k)k(x, x) + k(y, y) - 2k(x, y) for a positive-definite kernel k
HilbertSpace(points)the Euclidean squared distance of coordinate vectors

Every squared distance is computed at most once, when first needed, and cached in blocks of 256 × 256 pairs that are allocated when first touched (max_bytes bounds the cache, empty!(S) frees it, cache_stats(S) counts the calls of the distance function). A VPoint is a point (1 - t) x_a + t x_b on the segment of two input vertices; vcurve(S, indices) is the curve through the given input vertices, a GPntSeq of VPoints. Distances between points of segments follow from the squared distances of the (at most four) input vertices involved, by polarization: the space is never embedded anywhere.

What FrechetDist computes from the squared distances. The algorithms touch points only through a few primitives, and each of them has a version for virtual points:

  • the distance of two vertices: the cached value;
  • the free interval of a vertex c on a segment ab (the points of the segment within r of c): the closest point of the line, a + t0 (b - a), by the law of cosines, t0 = (|ca|² + |ab|² - |cb|²) / (2 |ab|²), and the distance h to it by Kahan's formula for the area of the triangle abc (accurate for needle-like triangles); the interval is then t0 ± sqrt(r² - h²) / |ab|, its ends decided by the squared distances of a and b themselves, as for coordinates;
  • the pieces of the curves for the box search are described by SausageTree, whose tests need only distances (a bounding box needs coordinates); the radius of a sausage, the largest distance from a vertex of the piece to the segment joining its ends, is computed from squared distances as well;
  • a prepared curve (DecideCurve) keeps the ball around its first vertex that holds it instead of its bounding box, and, as its width, the bound of a scan of the curve against the segment joining its ends;
  • the exact distance is the smallest Float64 that the decision procedure accepts, found by bisection to adjacent floats (about 60 decisions), and not a listed critical value as for coordinates: a critical value needs the position of a point on a segment, which the law of cosines, t0 = (|ca|² + |ab|² - |cb|²) / (2 |ab|²), gives only to about ε |ca|² / |ab|², useless on segments much shorter than the distances to them (measured: errors as large as the segment), while the decisions stay right.

So frechet_c_decide_exact, frechet_c_compute_bisect and frechet_c_compute_exact take virtual curves, and code written for them works on both kinds of curves.

Requirements. Both curves must be curves of the same space, and every vertex must be an input vertex of it (vcurve): a point derived from two vertices (a VPoint with 0 < t < 1) is refused, as its distances to other derived points would involve more than four input vertices; HilbertSpace(points) re-bases such points into a new space. The tree is SausageTree (the default for virtual curves; LazyBoxTree and BoxTree are refused). Repeated vertices (two input vertices at distance 0) are allowed. The distance function must come from a Hilbert space (a positive-definite kernel, or squared distances of points of a Hilbert space), be pure and thread-safe, and return finite non-negative values: otherwise the geometry is meaningless.

Accuracy. A distance computed from squared distances, rather than from coordinate differences, carries an error up to about √ε times the largest distance involved (a true 0 comes out as about 1e-8 times it). The upper bounds the decision relies on (the radii of the sausages, the ball of a prepared curve) add margins for it, assuming the squared distances of the space are accurate to a relative 1e-11 of the largest one involved. Under that assumption a "yes" or "no" from a filter agrees with the plain sweep on the given distances, and the answer is that of the plain sweep up to rounding at the distance itself, as for coordinates. The assumption holds for HilbertSpace(points) and for a dist2 computed without cancellation, as the Gaussian one above; with the kernel = form, k(x, x) + k(y, y) - 2k(x, y) cancels when x and y are close, and small distances lose their relative accuracy (prefer dist2 when it is available). Segments much shorter than the distances to them (near-duplicate vertices) make the triangle of the law of cosines meaningless; for them the free interval is decided by the lower bound (|ca| + |cb| - |ab|) / 2 on the distance from c to the segment.

Measured with example_higher/hilbert_accuracy.jl, on 200 pairs of random walks in ℝ^2 to ℝ^200 given as HilbertSpace(points): the bisection at rtol = 1e-14 agrees with the coordinates to 8.4e-15 relative, and the exact distance is the same Float64 on 135 of 200 pairs and within 1.8e-15 relative (8 ulps) on the others. In test/test_hilbert.jl: for a polynomial kernel, the results agree with those on its explicit feature map; for a Gaussian kernel, the decisions agree with the plain cell-by-cell sweep; on degenerate curves (collinear vertices, vertices on a grid, many vertices on one segment, near-duplicate vertices 1e-15 to 1e-6 apart) the decisions at (1 ± 1e-6) d agree with the coordinates, and the exact distance agrees to 1e-8 relative (the error is about the length of the shortest segment).

Costs. A decision touches O(1) distances per cell of the free space it visits and O(n + m) for its filters; each is computed once by the distance function and then read from the cache (a few nanoseconds). The exact distance costs about 60 decisions, and no tables. For coordinates in ℝ^d, a distance costs O(d) every time it is computed; in a space it is computed once.

Experiments: action recognition on KTH

The machinery was built for curves whose vertices are points of very high (or infinite) dimension. Videos are such curves: a clip is the curve of its frames. These experiments ask whether the continuous Fréchet distance, computed this way, is useful there, and what the Hilbert space costs and buys.

Data and task. The KTH human actions database: 2391 clips of 25 persons doing 6 actions (walking, jogging, running, boxing, hand waving, hand clapping) in 4 conditions (outdoors, outdoors with scale changes, other clothes, indoors), 25 frames per second, 49 to 129 frames per clip on average depending on the action. Every frame is reduced to 40 × 30 grey pixels, a point of ℝ^1200. The task is nearest-neighbour classification on the standard split by person of Schuldt, Laptev and Caputo (ICPR 2004): settings are chosen on the validation persons (768 queries against the 760 clips of the 8 training persons), and the test persons (863 queries against the 1528 clips of the training and validation persons) are classified once, every method with its setting chosen on validation. The runs below classify every 15th query (52 validation and 58 test queries, against all the references; about 9 minutes). Differences are tested with McNemar's exact test on the same queries (p below, example_higher/mcnemar.rb). Chance is 1/6.

Features (a frame of a clip becomes): raw, the pixels; centered, the pixels minus the clip's mean frame (removes the background); diff, the difference of consecutive frames (the motion).

Distances between clips:

  • mean frame: the distance between the mean frames of the two clips, order-free (on diff features, a motion-energy image);
  • DTW (sum): dynamic time warping, the sum of the frame distances along the best coupling; DTW (symmetric): the symmetric form of Sakoe and Chiba (a diagonal step weighs 2), divided by n + m;
  • discrete Fréchet: the largest frame distance along the best coupling of frames;
  • Fréchet: the continuous Fréchet distance (decisions with frechet_c_decide_exact on prepared curves, then a bisection to 1e-9 relative), on coordinates or in a HilbertSpace of all the frames (the same distance, see the costs below);
  • Fréchet, Gaussian kernel: the continuous Fréchet distance in the feature space of the Gaussian kernel on frames, where frames x and y are at squared distance 2 - 2 exp(-|x - y|² / s²) (-2expm1(...) in the code), with s² C times the median squared distance between frames, C chosen on validation. These curves live in an infinite-dimensional space: only HilbertSpace computes this distance.

Under the Gaussian kernel, the discrete Fréchet distance is a monotone function of the Euclidean one and makes the same predictions; the continuous one does not (points inside segments are mixtures of frames in the feature space).

Validation (52 queries)

Distancerawcentereddiff
mean frame0.2120.4810.712
DTW (sum)0.2880.5190.462
DTW (symmetric)0.192
discrete Fréchet0.4620.4620.538
Fréchet0.4040.4810.712
Fréchet, Gaussian kernel0.769 (C = 4)

The kernel width C was tried at 1, 4 and 16 on diff (0.731, 0.769, 0.712). The symmetric DTW, run on diff only, assigns every query to boxing. Fréchet on coordinates and in a HilbertSpace make the same prediction on all 52 queries.

Test (58 queries, once)

Each distance on the feature it does best with on validation:

Distance (validation choice)AccuracyFréchet (diff) against itFréchet, kernel, against it
mean frame (diff)0.7590.638 vs 0.759, p = 0.0920.655 vs 0.759, p = 0.15
DTW, sum (centered)0.5690.638 vs 0.569, p = 0.560.655 vs 0.569, p = 0.42
discrete Fréchet (diff)0.5340.638 vs 0.534, p = 0.110.655 vs 0.534, p = 0.039
Fréchet (diff)0.6380.655 vs 0.638, p = 1
Fréchet, Gaussian kernel, C = 4 (diff)0.655

On centered features the Fréchet distance and DTW (sum) are close: 0.552 and 0.569 (p = 1).

Frame rate

Queries at a third of the frame rate (every third frame; the references at the full rate), validation, centered features:

Distancefull ratea third
mean frame0.4810.481
DTW (sum)0.5190.231
discrete Fréchet0.4620.538
Fréchet0.4810.442

(diff is left out: the difference of every third frame is another feature than the references' consecutive differences.)

What the experiments show

On 52 and 58 queries, only large differences are significant (McNemar's exact test, p below); the rest are tendencies.

  • The continuous distance against the discrete one. On diff features the continuous Fréchet distance is better: 0.712 against 0.538 on validation (p = 0.012), 0.638 against 0.534 on test (p = 0.11; with the kernel, 0.655, p = 0.039). A likely reason: difference frames change much from one frame to the next, and the continuous distance matches a frame of one clip to a point between two frames of the other, not only to one of them. On raw and centered features the two are close (p = 0.25 and 1).
  • The frame rate. With queries at a third of the frame rate, DTW (sum) drops from 0.519 to 0.231: the sum counts the frames. The two Fréchet distances do not drop much: the discrete one goes from 0.462 to 0.538, the continuous one from 0.481 to 0.442 (between them, p = 0.12).
  • Against DTW. On test, the Fréchet distance on diff features gets 0.638, DTW at its best feature 0.569 (p = 0.56): no significant difference.
  • The kernel. The Gaussian kernel helps a little on validation (0.769 against 0.712, p = 0.25) and on test (0.655 against 0.638, p = 1); neither is significant. The kernel makes the Fréchet distance computable in an infinite-dimensional space; on this task it does not make it measurably more accurate.
  • The order-free baseline. The mean difference frame, where in the image the motion is, is the most accurate on test: 0.759 against 0.638 (p = 0.092). The kernel mean embedding (the order-free distance under the Gaussian kernel, MMD) is much worse than the mean difference frame: 0.346 against 0.712 on validation (p = 0.0003). (For scale: methods with learned features reach over 90% on KTH; nearest neighbours on whole clips are not meant to compete with them.)

So on this data the continuous Fréchet distance is better than the discrete one on diff features, and the Hilbert space computes it for any kernel with the same predictions and, as below, faster than the coordinates.

Costs

All times single-threaded, on an otherwise idle machine, excluding compilation (ruby examples/benchmarks/reproduce.rb hilbert kth reruns them).

Pairs of clips (example_higher/hilbert_timing.jl): the distance of every pair of the first clips of a set, on coordinates (Vector points) and as curves of a HilbertSpace of the same frames, with its cache emptied before every pair, so every frame distance a pair needs is computed inside its time:

SetPairsDFunctionCoordinatesHilbert spaceSpeed-upLargest differenceFrame distances computed
KTH, 40 × 307801200bisection (rtol 1e-10)14.63 s3.12 s4.7×9.0e-110.30 n m
KTH, 40 × 307801200exact34.12 s3.88 s8.8×3.4e-150.31 n m
KTH, 160 × 120 (kth)6619200bisection (rtol 1e-10)62.52 s4.46 s14×7.5e-110.52 n m
KTH, 160 × 120 (kth)6619200exact41.05 s4.55 s9.0×5.5e-140.51 n m

On coordinates, the decisions compute the distance of a pair of frames, O(D), many times over; in the space each is computed once, and a pair needs only about a third to a half of the n m frame distances. The differences are those of the tolerance (bisection) and of rounding (exact: the coordinates return a critical value, the space the smallest Float64 its decider accepts).

Classification (validation, diff features, 52 queries against 760 clips):

DistanceAccuracyTime
DTW (sum)0.46232.1 s
discrete Fréchet0.53821.4 s
Fréchet, coordinates0.71218.9 s
Fréchet, HilbertSpace (Euclidean)0.7127.8 s

The two Fréchet runs make the same prediction on all 52 queries; the space takes less than half the time. (DTW and the discrete Fréchet distance are plain dynamic programs in the script, computing every frame distance of a pair unless they abandon it early; their times are not a comparison of algorithms.) On the first queries, the space computes 0.28 to 0.57 million frame distances per query, in cache blocks of 256 × 256 distances taking 0.32 to 0.37 GB (up to 1.1 GB on test, against 1528 clips), freed by empty! after each query.