`fit_line` fits y-on-x ordinary least squares for 2-D points but total least squares for D ≥ 3, so a near-vertical 2-D fit is 8.26° off (1.42° through the D = 3 path), the result changes when x and y are swapped, and an absolute `Σdx² > 1e-8` test turns small point sets vertical
fit_line(points, weights=None) (kornia/geometry/line.py:241) has two algorithms. For D ≥ 3 it takes the principal direction of the scatter matrix (an SVD), which is the total least squares line: it minimises the perpendicular distances. Since #3219, D = 2 goes to _fit_line_ols_2d / _fit_line_weighted_ols_2d (:186-238), which fit the slope of y on x by ordinary least squares: they minimise vertical distances and return (1, slope)/‖·‖. The two give different lines for the same points, and the 2-D one has three consequences:
- It is biased towards horizontal, and the bias grows with the steepness of the line. For a near-vertical set it is several degrees off.
- It depends on which coordinate is called x: swapping the two columns gives a different line, not the mirrored one.
- A line counts as vertical when
Σ(x − x̄)² <= 1e-8(:195,:199; the weightedΣw(x − x̄)²at:230), an absolute threshold. The same point set scaled by 1e-5 (for example, coordinates in kilometres instead of centimetres) crosses it and gets the direction(0, 1)whatever its slope.
The docstring says only "Fit a line from a set of points."
Reproduction
import torch
from kornia.geometry.line import fit_line
d = torch.float64
r6 = lambda v: [round(c, 6) for c in v.tolist()]
def angle(a, b):
a, b = a / a.norm(), b / b.norm()
return torch.rad2deg(torch.arccos((a @ b).abs().clamp(max=1.0))).item()
def tls_2d(p): # closed-form 2x2 total least squares: angle = 0.5 * atan2(2 Sxy, Sxx - Syy)
q = p - p.mean(0)
sxx, syy, sxy = (q[:, 0] ** 2).sum(), (q[:, 1] ** 2).sum(), (q[:, 0] * q[:, 1]).sum()
th = 0.5 * torch.atan2(2 * sxy, sxx - syy)
return torch.stack([th.cos(), th.sin()])
t = torch.tensor([-2.0, -1.3, -0.2, 0.4, 1.1, 2.7, 3.5], dtype=d)
off = torch.tensor([0.21, -0.35, 0.12, 0.30, -0.27, 0.05, -0.18], dtype=d) # perpendicular offsets
def noisy_line(origin, u):
u = u / u.norm()
n = torch.stack([-u[1], u[0]])
return origin + t[:, None] * u + off[:, None] * n, u
z0 = lambda p: torch.cat([p, torch.zeros(len(p), 1, dtype=d)], -1) # the same points as 3-D, z = 0
# 1) near-vertical line (true direction (0.1, 1)): 2-D vs the same points through the D >= 3 path vs x <-> y swapped
V, u = noisy_line(torch.tensor([2.0, 0.0], dtype=d), torch.tensor([0.1, 1.0], dtype=d))
f2, f3, fs = fit_line(V[None]), fit_line(z0(V)[None]), fit_line(V.flip(-1)[None])
print("near-vertical, off the true direction:")
print(f" D=2 fit {r6(f2.direction[0])}: {angle(f2.direction[0], u):.3f} deg")
print(f" same points as D=3 (z=0) {r6(f3.direction[0])}: {angle(f3.direction[0, :2], u):.3f} deg")
print(f" D=2 fit with x and y swapped {r6(fs.direction[0])}: {angle(fs.direction[0], u.flip(0)):.3f} deg")
print(f" closed-form 2-D TLS {r6(tls_2d(V))}: {angle(tls_2d(V), u):.3f} deg; swapped {angle(tls_2d(V.flip(-1)), u.flip(0)):.3f} deg")
w1 = fit_line(V[None], torch.ones(1, 7, dtype=d))
print(f" weighted D=2 branch, unit weights: {r6(w1.direction[0])} ({angle(w1.direction[0], u):.3f} deg)")
# 2) a steep line (true direction (1, 3)): the same points, 2-D vs 3-D
P, u = noisy_line(torch.tensor([0.5, -1.0], dtype=d), torch.tensor([1.0, 3.0], dtype=d))
g2, g3 = fit_line(P[None]), fit_line(z0(P)[None])
print(f"slope-3 line: D=2 vs D=3 (z=0) disagree by {angle(g2.direction[0], g3.direction[0, :2]):.3f} deg; "
f"off the truth D=2 {angle(g2.direction[0], u):.3f} deg, D=3 {angle(g3.direction[0, :2], u):.3f} deg, "
f"closed-form TLS vs D=3 {angle(tls_2d(P), g3.direction[0, :2]):.2e} deg")
# 3) the absolute threshold sum(dx^2) > 1e-8: the same slope-3 points, scaled
for s in (1.0, 1e-4, 1e-5):
print(f"scale {s:g}: D=2 {[round(c, 6) for c in fit_line((P * s)[None]).direction[0].tolist()]} "
f"D=3 {[round(c, 6) for c in fit_line(z0(P * s)[None]).direction[0].tolist()]} "
f"sum dx^2 {((P[:, 0] - P[:, 0].mean()) * s).pow(2).sum().item():.3e}")near-vertical, off the true direction:
D=2 fit [0.241419, 0.970421]: 8.260 deg
same points as D=3 (z=0) [-0.124134, -0.992265, -0.0]: 1.420 deg
D=2 fit with x and y swapped [0.992497, 0.122271]: 1.313 deg
closed-form 2-D TLS [0.124134, 0.992265]: 1.420 deg; swapped 1.420 deg
weighted D=2 branch, unit weights: [0.241419, 0.970421] (8.260 deg)
slope-3 line: D=2 vs D=3 (z=0) disagree by 2.379 deg; off the truth D=2 3.800 deg, D=3 1.420 deg, closed-form TLS vs D=3 0.00e+00 deg
scale 1: D=2 [0.378399, 0.925643] D=3 [-0.339643, -0.940554, -0.0] sum dx^2 3.104e+00
scale 0.0001: D=2 [0.378399, 0.925643] D=3 [-0.339643, -0.940554, -0.0] sum dx^2 3.104e-08
scale 1e-05: D=2 [0.0, 1.0] D=3 [-0.339643, -0.940554, -0.0] sum dx^2 3.104e-10kornia main 0fbed00b0, torch 2.14.0 (and 2.5.1: same output), CPU float64, macOS arm64.
The near-vertical set lies along (0.1, 1) with small perpendicular offsets. The D = 2 fit is 8.260° off. The same points given to the D ≥ 3 path (with z = 0) are 1.420° off, and so is the closed-form 2×2 TLS in the repro, which is also unchanged when x and y are swapped. The 2-D fit with x and y swapped is 1.313° off, because it is then fitting a near-horizontal line, where OLS is close to TLS. The weighted branch with unit weights gives exactly the unweighted OLS answer. For the slope-3 set the 2-D and 3-D answers for the same points differ by 2.379°. In the scale sweep, the 1e-4 set still has Σdx² = 3.1e-8 > 1e-8 and keeps its direction, while the 1e-5 set (3.1e-10) becomes (0, 1); the D = 3 direction is the same at every scale.
Expected
One definition of the fitted line for every D: the total least squares line, which is what fit_line computes for D ≥ 3 and what "fit a line to points" means when neither coordinate is the dependent variable. It does not depend on the labelling of the axes or on the unit of the coordinates. In 2-D it has a closed form, so it keeps the speed #3219 was after: with the (weighted) centred second moments Sxx, Syy, Sxy, the direction angle is θ = ½·atan2(2·Sxy, Sxx − Syy) and the direction is (cos θ, sin θ). The repro's tls_2d agrees with the D = 3 path to 0.00e+00° on the slope-3 set. It needs no vertical special case and no absolute threshold.
Classification
Silent wrong result (a different estimator than for D ≥ 3, with a bias that grows with the slope), plus an absolute threshold that is not scale-invariant. A 2-D caller cannot tell which estimator it gets, and the existing tests cannot tell them apart. TestFitLine::test_fit_line2 fits exact points on y = x, where OLS and TLS agree and the x ↔ y swap maps the set onto itself. test_fit_line_weighted adds noise of σ = 0.05 to the same 45° line and accepts any direction with cosine similarity above 0.998 (about 3.6°).
Idiom 7 (a special-case fixture hides it). #3219 introduced the 2-D branch; its description says that for noisy data the result "may differ". Found in the conventions batch 10 audit.
Disposition
Documented as a Known defect in the batch-10 Convention block for fit_line; fix separately. Fix direction: replace both 2-D branches with the closed-form TLS above, with the weighted mean and weighted moments in the weighted branch, and drop the 1e-8 vertical test. Two points for the fix PR:
- Sign. The 2-D branches now always return a direction with x ≥ 0, and the D ≥ 3 sign is whatever the SVD returns.
(cos θ, sin θ)withθ = ½·atan2(·) ∈ [−π/2, π/2]keeps x ≥ 0, but for an exactly vertical line x is about 0 and the sign of y follows the sign of the zeroSxy(atan2(±0, negative) = ±π). Pin whichever rule is chosen with an exactly vertical fixture. - Degenerate sets (all points equal,
Sxx = Syy = Sxy = 0) giveatan2(0, 0) = 0, the direction(1, 0). Rejecting degenerate input is a separate question, filed from the same audit.
A pin for the fix: the near-vertical set above, asserting that the 2-D fit agrees with the same points through the D = 3 path (within 1e-6 rad), and that swapping x and y mirrors the direction. #5026 (open) changes the dtype of the vertical fallback in _fit_line_ols_2d, a line that this fix removes.
Related: #3219 (merged PR, added the 2-D OLS branches), #5015 (open, 2-D half-precision dtype of the vertical fallback) and its fix PR #5026 (open), #5014 (open, weighted D ≥ 3 centring) and its fix PR #5029 (open).
Posted on behalf of @ducha-aiki by Claude (Opus 5.5).
Source: kornia/kornia