Algorithm Search⌘K

Algorithmcore

Local polynomial regression

Also called LOESS, LOWESS, locally weighted scatterplot smoothing.

Fits a low-degree polynomial by weighted least squares around each point. It removes the boundary bias of kernel regression; LOWESS adds robust reweighting.

Time
O(q (n p + p^3)) worstO(n log n + (t + 1) n k) lowess
Space
O(p^2) extra
Where
k = the number of neighbours in a window; n = the number of data points; p = the degree; q = the number of points where the estimate is wanted; t = the number of robustness iterations
Properties
deterministicexactlinear smoothernot randomizedreproduces polynomials of degree p
Origin
William S. Cleveland, Susan J. Devlin, Charles J. Stone, Jianqing Fan, Irène Gijbels, 1979

Local polynomial regression estimates a regression function m(x)=E[Y∣X=x]m(x) = \mathbb{E}[Y \mid X = x] by fitting, at each point xx, a polynomial of low degree pp to the nearby data by weighted least squares, and taking the value of that polynomial at xx. The weights come from a kernel of bandwidth hh. With p=0p = 0 it is the Nadaraya-Watson estimator. With p=1p = 1, the local linear fit, it reproduces straight lines exactly, so it has no bias of order hh at the ends of the data or where the design is uneven. LOWESS (Cleveland 1979) is a local linear fit on nearest-neighbour windows with tricube weights, followed by a few robustness iterations that give less weight to points with large residuals. LOESS is the same idea with local quadratics and several predictors.

In plain words

To estimate a curve at some place, take the data points nearby, give the closest ones the most weight, and fit a straight line through them by least squares. The height of that line at the place is the estimate. Then move to the next place and fit a new line.

A plain weighted average of the nearby points does well in the middle of the data, but at the ends all the neighbours are on one side, and a rising curve gets pulled down or up. A line through the neighbours follows the slope, so it does not have this error. LOWESS adds one more idea: after a first fit, points far from the curve are probably bad, so it fits again with less weight on them.

The problem

The input is nn pairs (x1,y1),…,(xn,yn)(x_1, y_1), \ldots, (x_n, y_n) from the model yi=m(xi)+eiy_i = m(x_i) + e_i, a kernel K≥0K \ge 0, a bandwidth hh and a degree pp. At a point xx, the local fit minimizes

∑i=1nK ⁣(xi−xh)(yi−∑k=0pβk(xi−x)k)2,\sum_{i=1}^n K\!\left(\frac{x_i - x}{h}\right)\Big(y_i - \sum_{k=0}^p \beta_k (x_i - x)^k\Big)^2,

and the estimate is m^(x)=β^0\hat m(x) = \hat\beta_0. The other coefficients estimate the derivatives: k! β^kk!\,\hat\beta_k estimates m(k)(x)m^{(k)}(x). LOWESS uses p=1p = 1, the tricube kernel (1−∣u∣3)3(1 - |u|^3)^3 and, at each xix_i, the bandwidth hih_i equal to the distance to the rr-th nearest xjx_j, where r=⌊fn+12⌋r = \lfloor fn + \frac12 \rfloor for a span ff, often 2/32/3.

The algorithm

  1. LOCAL-POLYNOMIAL(x, (x_i, y_i), h, p, δ) ▷ δ: robustness weights, all 1 by default
  2. 1w_i ← δ_i · K((x_i − x)/h) for all i
  3. 2S_jk ← Σ_i w_i (x_i − x)^(j+k); t_j ← Σ_i w_i (x_i − x)^j y_i for 0 ≤ j, k ≤ p
  4. 3solve S β = t; return β_0 ▷ undefined if S is singular
  5. LOWESS((x_i, y_i), f, t)
  6. 4δ_i ← 1 for all i; h_i ← the distance from x_i to its r-th nearest x_j, r = round(f n)
  7. 5repeat t + 1 times
  8. 6ŷ_i ← LOCAL-POLYNOMIAL(x_i, data, h_i, 1, δ) with the tricube kernel, for all i
  9. 7r_i ← y_i − ŷ_i; s ← median |r_i|
  10. 8δ_i ← B(r_i / (6s)), with B(u) = (1 − u²)² for |u| < 1 and 0 otherwise
  11. 9return ŷ

Lines L2 and L3 are the normal equations of a weighted least squares fit in the shifted variable xi−xx_i - x, so that β0\beta_0 is the value at xx. They have p+1p + 1 unknowns, usually 2 or 3. The robustness weights of line L8 are the Tukey biweight of the residuals, scaled by 6 times their median absolute value; this is iteratively reweighted least squares with a local fit in place of a global one. The code skips line L8 after the last fit, and when s=0s = 0 it gives weight 1 to the points with residual 0 and weight 0 to the others.

Example

Local linear against local constant. Seven points on y=x2y = x^2 at x=0,1,…,6x = 0, 1, \ldots, 6, the Epanechnikov kernel 34(1−u2)\frac34(1 - u^2) and h=3h = 3. Exact values from the test file:

xx 0 1 2 3 4 5 6
true x2x^2 0 1 4 9 16 25 36
local linear −20/73 ≈ −0.27 67/35 ≈ 1.91 28/5 = 5.6 53/5 = 10.6 17.6 907/35 ≈ 25.91 2608/73 ≈ 35.73
local constant 14/11 ≈ 1.27 43/15 ≈ 2.87 5.6 10.6 17.6 343/15 ≈ 22.87 302/11 ≈ 27.45

At x=2,3,4x = 2, 3, 4 the neighbours lie symmetrically, the slope term has no effect, and the two fits agree; both are too high by 1.61.6, because they flatten the curvature. At the ends the local constant fit is far off: 27.4527.45 for 3636 at x=6x = 6. The local linear fit is off by only 0.270.27, because it follows the slope. For the line y=2xy = 2x at the same points, the local linear fit gives exactly 0,2,…,120, 2, \ldots, 12, while the local constant fit gives 18/1118/11 at x=0x = 0.

LOWESS with an outlier. Ten points near y=2x+1y = 2x + 1, with one wild value at x=7x = 7; span f=2/3f = 2/3, so r=7r = 7 neighbours:

xx 1 2 3 4 5 6 7 8 9 10
yy 3.1 4.9 7.2 8.8 11.1 13.0 30.0 16.9 19.2 21.0
no robustness (t=0t = 0) 3.05 5.03 7.01 9.01 12.50 16.84 19.31 20.07 20.47 20.49
LOWESS, t=2t = 2 3.05 5.03 7.01 9.01 11.00 12.99 15.01 17.03 19.04 21.06

Without robustness, the outlier lifts the curve from x=5x = 5 to the end. After the first fit its residual is the largest by far, its bisquare weight is 0, and the next fits ignore it. The robust fit is within 0.070.07 of the line 2x+12x + 1 everywhere.

Correctness

If at least p+1p + 1 distinct points have positive weight, the weighted least squares problem has one solution. If the data lie on a polynomial qq of degree at most pp, that polynomial has weighted residual sum 0, so it is the fit, and m^(x)=q(x)\hat m(x) = q(x) exactly, at every xx, inside or at the edge of the data. For p=1p = 1 this means the local linear fit reproduces any line. It follows that the equivalent weights ℓi(x)\ell_i(x) in m^(x)=∑iℓi(x)yi\hat m(x) = \sum_i \ell_i(x) y_i satisfy ∑iℓi=1\sum_i \ell_i = 1 and ∑iℓi(xi−x)=0\sum_i \ell_i (x_i - x) = 0. So for a smooth mm, the constant and linear parts of the Taylor expansion cancel, and the bias comes from the second derivative only. At the end point of an equally spaced design,

E m^(0)−m(0)=h22m′′(0) (μ2+)2−μ1+μ3+μ0+μ2+−(μ1+)2+o(h2),\mathbb{E}\,\hat m(0) - m(0) = \frac{h^2}{2}m''(0)\,\frac{(\mu_2^+)^2 - \mu_1^+\mu_3^+}{\mu_0^+\mu_2^+ - (\mu_1^+)^2} + o(h^2),

with the one-sided moments μk+=∫01ukK(u) du\mu_k^+ = \int_0^1 u^k K(u)\,du. For the Epanechnikov kernel the factor is −11/95-11/95. The Nadaraya-Watson estimator has a boundary bias of order hh instead. The full proofs are below. The rates for random designs and the minimax efficiency are cited.

Proof: A local polynomial fit of degree p reproduces polynomials of degree p exactly, and the local linear fit has a boundary bias of order h squaredfull

Setting. The data are pairs (x1,y1),…,(xn,yn)(x_1, y_1), \ldots, (x_n, y_n). Fix a point xx, a kernel K≥0K \ge 0, a bandwidth h>0h > 0, optional robustness weights δi≥0\delta_i \ge 0 and a degree p≥0p \ge 0. Line L1 sets wi=δiK((xi−x)/h)w_i = \delta_i K((x_i - x)/h), and with di=xi−xd_i = x_i - x the fit minimizes

Q(β)=∑i=1nwi(yi−∑k=0pβkdik)2.Q(\beta) = \sum_{i=1}^n w_i \Big(y_i - \sum_{k=0}^p \beta_k d_i^k\Big)^2 .

Line L2 forms the normal equations Sβ=tS\beta = t, with Sjk=∑iwidij+kS_{jk} = \sum_i w_i d_i^{j+k} and tj=∑iwidijyit_j = \sum_i w_i d_i^j y_i for 0≤j,k≤p0 \le j, k \le p, and line L3 solves them and returns m^(x)=β0\hat m(x) = \beta_0.

Part 1. The normal equations

Lemma 1. SS is positive definite if and only if at least p+1p + 1 distinct values xix_i have wi>0w_i > 0. Then QQ has exactly one minimizer, the solution of Sβ=tS\beta = t.

Proof. For a vector vv, v⊤Sv=∑iwi(∑kvkdik)2=∑iwi qv(di)2v^\top S v = \sum_i w_i \big(\sum_k v_k d_i^k\big)^2 = \sum_i w_i\,q_v(d_i)^2, where qvq_v is the polynomial with coefficients vv. This is 0 if and only if qvq_v vanishes at every did_i with wi>0w_i > 0. A nonzero polynomial of degree at most pp has at most pp roots, so with p+1p + 1 distinct such did_i only v=0v = 0 gives 0. With pp or fewer, a nonzero qvq_v with those roots exists. QQ is a quadratic in β\beta with Hessian 2S2S and gradient 2(Sβ−t)2(S\beta - t), so a positive definite SS gives one minimizer, where the gradient is 0. □\square

When SS is singular, the code returns "undefined". The test file skips such cases.

Part 2. Exact reproduction

Theorem 2 (polynomials of degree p are reproduced). Let SS be positive definite. If yi=q(xi)y_i = q(x_i) for a polynomial qq of degree at most pp, then m^(x)=q(x)\hat m(x) = q(x), and more generally βk=q(k)(x)/k!\beta_k = q^{(k)}(x)/k! for every kk.

Proof. Taylor's formula is exact for a polynomial of degree at most pp: q(xi)=∑k=0pq(k)(x)k! dikq(x_i) = \sum_{k=0}^p \frac{q^{(k)}(x)}{k!}\,d_i^k. So the vector β∘\beta^\circ with βk∘=q(k)(x)/k!\beta^\circ_k = q^{(k)}(x)/k! makes every residual 0 and Q(β∘)=0Q(\beta^\circ) = 0. Since Q≥0Q \ge 0, β∘\beta^\circ is a minimizer, and by Lemma 1 it is the only one. Line L3 returns β0∘=q(x)\beta^\circ_0 = q(x). □\square

Corollary 3 (the local linear fit reproduces a line). With p=1p = 1 and at least two distinct xix_i with positive weight, a line yi=a+bxiy_i = a + bx_i gives m^(x)=a+bx\hat m(x) = a + bx exactly, at every xx: in the interior of the data, at its ends, and outside it. The local constant fit (p=0p = 0) reproduces only constants.

The test file checks Theorem 2 in exact rational arithmetic for degrees 1, 2 and 3, at random points that include points at the edge of and outside the data, and checks β1=q′(x)\beta_1 = q'(x).

Corollary 4 (equivalent kernel). m^(x)=∑iℓi(x) yi\hat m(x) = \sum_i \ell_i(x)\,y_i with weights ℓi(x)=wi (e0⊤S−1)(1,di,…,dip)⊤\ell_i(x) = w_i\,(e_0^\top S^{-1})(1, d_i, \ldots, d_i^p)^\top that satisfy

∑iℓi(x)=1,∑iℓi(x) dik=0(1≤k≤p).\sum_i \ell_i(x) = 1, \qquad \sum_i \ell_i(x)\,d_i^k = 0 \quad (1 \le k \le p).

Proof. β=S−1t\beta = S^{-1}t and tt is linear in yy, which gives the formula. Apply Theorem 2 to q(t)=(t−x)kq(t) = (t - x)^k: then yi=diky_i = d_i^k and m^(x)=q(x)\hat m(x) = q(x), which is 1 for k=0k = 0 and 0 for k≥1k \ge 1. □\square

For p=1p = 1, solving the 2 by 2 system gives the closed form

m^(x)=∑iwi (S2−S1di) yiS0S2−S12,Sk=∑iwidik,\hat m(x) = \frac{\sum_i w_i\,(S_2 - S_1 d_i)\,y_i}{S_0 S_2 - S_1^2}, \qquad S_k = \sum_i w_i d_i^k,

and the test compares the general solver with it, exactly. With p=0p = 0, m^(x)=∑iwiyi/∑iwi\hat m(x) = \sum_i w_i y_i / \sum_i w_i, the Nadaraya-Watson estimator; the test checks this too.

Part 3. Bias at the boundary

Take the equally spaced design xi=i/Nx_i = i/N, i=0,…,Ni = 0, \ldots, N, no robustness weights, a kernel KK that is symmetric, vanishes outside [−1,1][-1, 1] and has bounded variation, and the end point x=0x = 0. Let μk+=∫01ukK(u) du\mu_k^+ = \int_0^1 u^k K(u)\,du. The weights depend only on the design, so E m^(0)=∑iℓi(0) m(xi)\mathbb{E}\,\hat m(0) = \sum_i \ell_i(0)\,m(x_i).

Theorem 5 (local linear boundary bias of order h2h^2). Let mm have a bounded second derivative that is continuous at 0. As h→0h \to 0 and Nh→∞Nh \to \infty,

E m^(0)−m(0)=h22 m′′(0) (μ2+)2−μ1+μ3+μ0+μ2+−(μ1+)2+o(h2).\mathbb{E}\,\hat m(0) - m(0) = \frac{h^2}{2}\,m''(0)\,\frac{(\mu_2^+)^2 - \mu_1^+\mu_3^+}{\mu_0^+\mu_2^+ - (\mu_1^+)^2} + o(h^2).

Proof. By Corollary 4 with p=1p = 1, the constant and linear parts of mm cancel exactly:

∑iℓi(0) m(xi)−m(0)=∑iℓi(0)(m(xi)−m(0)−m′(0) xi)=∑iℓi(0)(12m′′(0) xi2+ρixi2),\sum_i \ell_i(0)\,m(x_i) - m(0) = \sum_i \ell_i(0)\big(m(x_i) - m(0) - m'(0)\,x_i\big) = \sum_i \ell_i(0)\Big(\tfrac12 m''(0)\,x_i^2 + \rho_i x_i^2\Big),

where by Taylor's theorem ∣ρi∣≤12sup⁡0≤t≤h∣m′′(t)−m′′(0)∣→0|\rho_i| \le \frac12\sup_{0 \le t \le h}|m''(t) - m''(0)| \to 0, since only xi≤hx_i \le h have weight. From the closed form, ∑iℓi(0) xi2=(S22−S1S3)/(S0S2−S12)\sum_i \ell_i(0)\,x_i^2 = (S_2^2 - S_1 S_3)/(S_0 S_2 - S_1^2), and

∑i∣ℓi(0)∣ xi2≤h2∑i∣ℓi(0)∣≤h2 S0S2+S12S0S2−S12,\sum_i |\ell_i(0)|\,x_i^2 \le h^2 \sum_i |\ell_i(0)| \le h^2\,\frac{S_0 S_2 + S_1^2}{S_0 S_2 - S_1^2},

because ∣S2−S1xi∣≤S2+S1xi|S_2 - S_1 x_i| \le S_2 + S_1 x_i and ∑iwixi=S1\sum_i w_i x_i = S_1. Write xi=h⋅iδx_i = h\cdot i\delta with δ=1/(Nh)\delta = 1/(Nh). Then Sk=Nhk+1 (μk++O(δ))S_k = N h^{k+1}\,(\mu_k^+ + O(\delta)) by the same Riemann sum bound as for the Nadaraya-Watson estimator, applied to ukK(u)u^k K(u). So

S22−S1S3S0S2−S12=h2 (μ2+)2−μ1+μ3++O(δ)μ0+μ2+−(μ1+)2+O(δ),\frac{S_2^2 - S_1 S_3}{S_0 S_2 - S_1^2} = h^2\,\frac{(\mu_2^+)^2 - \mu_1^+\mu_3^+ + O(\delta)}{\mu_0^+\mu_2^+ - (\mu_1^+)^2 + O(\delta)},

and the ratio (S0S2+S12)/(S0S2−S12)(S_0S_2 + S_1^2)/(S_0S_2 - S_1^2) stays bounded. The denominator μ0+μ2+−(μ1+)2\mu_0^+\mu_2^+ - (\mu_1^+)^2 is positive by the Cauchy-Schwarz inequality, which is strict because KK is not concentrated at one point. So the first term gives the stated main term, and the ρi\rho_i terms are o(h2)o(h^2). □\square

For the Epanechnikov kernel, μ0+=12\mu_0^+ = \frac12, μ1+=316\mu_1^+ = \frac3{16}, μ2+=110\mu_2^+ = \frac1{10} and μ3+=116\mu_3^+ = \frac1{16}, so the factor is (1100−3256)/(120−9256)=−1195\big(\frac1{100} - \frac3{256}\big)/\big(\frac1{20} - \frac9{256}\big) = -\frac{11}{95}. For m(x)=x2m(x) = x^2 the remainder is 0, and the test measures the ratio of the bias to h2h^2: −0.11287-0.11287 for N=1000N = 1000, h=0.1h = 0.1 and −0.11433-0.11433 for N=4000N = 4000, h=0.05h = 0.05, against the limit −11/95=−0.11579-11/95 = -0.11579. Compare the Nadaraya-Watson estimator, whose boundary bias is 38h m′(0)\frac38 h\,m'(0) for the same kernel: order hh, not h2h^2.

In the interior, at a design point xx with h≤x≤1−hh \le x \le 1 - h, the design is symmetric around xx, so S1=S3=0S_1 = S_3 = 0 and the local linear fit equals the local constant fit there; the bias is h22μ2 m′′(x)+o(h2)\frac{h^2}{2}\mu_2\,m''(x) + o(h^2) by the same argument.

What is cited, not proved

For a random design with density ff, the local linear fit has interior bias h22μ2m′′(x)\frac{h^2}{2}\mu_2 m''(x) with no design bias term, variance σ2(x)R(K)/(nhf(x))\sigma^2(x)R(K)/(nhf(x)), the same bias order at the boundary, and it is the best linear smoother in a minimax sense (Fan 1992, 1993; Fan and Gijbels 1996, Chapter 3). For odd p−νp - \nu, where ν\nu is the order of the derivative estimated, the bias has the same order in the interior and at the boundary. These are cited, not proved here. The robustness iterations of LOWESS have no general convergence theorem; their effect on the example and in the tests is measured.

Cost

Line L1 costs O(n)O(n). Line L2 costs O(np)O(np) for the 2p+12p + 1 power sums and line L3 costs O(p3)O(p^3). So one point costs O(np+p3)O(np + p^3), and the fitted values at all nn data points cost O(n2p+np3)O(n^2 p + np^3), or O(n(kp+p3))O(n(k p + p^3)) when only the kk nearest neighbours have weight and the data are sorted. LOWESS repeats this 1+t1 + t times for tt robustness iterations.

Complexity

  • One point. The weights cost O(n)O(n), the 2p+12p + 1 power sums O(np)O(np), and the solve O(p3)O(p^3): O(np+p3)O(np + p^3) time and O(p2)O(p^2) extra space. For qq points, O(q(np+p3))O(q(np + p^3)).
  • Nearest-neighbour windows. With sorted data, the kk nearest neighbours of each point form a window that slides along the data, so all nn fitted values cost O(nlog⁡n+nk)O(n \log n + nk) for fixed pp. LOWESS repeats the fits t+1t + 1 times, usually t=2t = 2.
  • Interpolation. LOESS software fits at a set of vertices and interpolates between them, which makes the cost nearly linear in nn.
  • Grid. On an equally spaced design, the equivalent weights are the same at every interior point, and the fit is a convolution: this is the Savitzky-Golay filter.

Properties

  • Exact for polynomials of degree p. Proved above, and checked in exact arithmetic for p=1,2,3p = 1, 2, 3.
  • No boundary or design bias of order h. For p=1p = 1, the bias is h22μ2m′′(x)\frac{h^2}{2}\mu_2 m''(x) in the interior and of order h2h^2 at the boundary, with no term in f′/ff'/f for an uneven design. The variance has the same order as for the local constant fit, σ2(x)R(K)/(nhf(x))\sigma^2(x)R(K)/(nhf(x)), with a larger constant at the boundary (Fan 1992; Fan and Gijbels 1996). The rates are cited, not proved here.
  • Odd degrees. Going from an even pp to p+1p + 1 removes a bias term without raising the variance order, so odd degrees (p=1p = 1, or p=3p = 3 for derivatives) are usually preferred.
  • Linear smoother. Without robustness weights, m^=Ly\hat m = Ly for a matrix that depends only on the xix_i. Leave-one-out residuals and degrees of freedom tr⁡L\operatorname{tr} L follow directly.
  • Robustness. LOWESS resists isolated outliers in yy. It does not resist many outliers in one window, and the robustness iterations have no general convergence guarantee.

Variants and improvements

  • LOESS. Cleveland and Devlin (1988) allow several predictors, local quadratic fits and conditionally parametric terms, and choose the span by a CpC_p-type criterion.
  • Derivatives. k! β^kk!\,\hat\beta_k estimates m(k)(x)m^{(k)}(x); use p=k+1p = k + 1.
  • Variable bandwidth. Nearest-neighbour windows, as in LOWESS, or a bandwidth h(x)h(x) from a plug-in rule (Fan and Gijbels 1992).
  • Bandwidth choice. Cross-validation, generalized cross-validation, or plug-in rules for the regression AMISE; see bandwidth selection.
  • Local likelihood. For counts or binary responses, fit a local generalized linear model by local likelihood instead of local least squares.
  • Seasonal decomposition. STL applies LOESS repeatedly to separate the trend and the seasonal part of a time series.

When to use it

Use the local linear fit as the default nonparametric regression in one or a few predictors: it is simple, it behaves well at the ends of the data, and it adapts to uneven designs. Use LOWESS to draw a smooth trend through a scatter plot, especially when some points may be wild. In a regression discontinuity design, local linear fits on each side of the cut-off are the standard estimator, because the effect is measured at a boundary. For many predictors, or when you need a global smooth function, a smoothing spline, an additive model or a Gaussian process is often better.

Pitfalls

  • Sparse windows. With a fixed hh, a window with fewer than p+1p + 1 distinct points makes the system singular, and a window with few points makes the fit unstable. Nearest-neighbour windows avoid both.
  • Higher degree is not always better. Local quadratics and cubics need wider windows and have more variance, especially at the boundary. Prefer p=1p = 1 unless the curve has sharp peaks.
  • Robustness with small spans. With few points in each window, the robustness iterations can lock onto an outlier. On the example data with span 1/21/2 (5 neighbours), the robust fit after four iterations passed through the outlier at x=7x = 7 and stayed at 30 to the end; with span 2/32/3 it did not. This is a measurement, not a rule.
  • Extrapolation. The local line at the last data point continues its slope outside the data, which can be far off. Do not evaluate the fit far outside the data.
  • Confidence bands. The bias does not vanish at the usual bandwidths, so bands from the variance alone cover too little; undersmooth or correct the bias.

Implementations

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.

local_polynomial_regression.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-polynomial-regression/. The authors are listed in prov/C1XC0A.jsonl.

import math


def epanechnikov(u):
    """(3/4)(1 - u^2) on [-1, 1]; works with floats and Fractions."""
    return 3 * (1 - u * u) / 4 if -1 <= u <= 1 else 0 * u


def tricube(u):
    """(1 - |u|^3)^3 on [-1, 1], the weight of LOESS and LOWESS."""
    a = abs(u)
    return (1 - a * a * a) ** 3 if a < 1 else 0 * u


def bisquare(u):
    """(1 - u^2)^2 on [-1, 1], the robustness weight of LOWESS."""
    return (1 - u * u) ** 2 if abs(u) < 1 else 0 * u


def solve(A, b):
    """Gauss-Jordan elimination with pivoting on the largest entry.
    Exact for Fractions. Returns None if A is singular."""
    n = len(A)
    M = [list(row) + [v] for row, v in zip(A, b)]
    for c in range(n):
        p = max(range(c, n), key=lambda r: abs(M[r][c]))
        if M[p][c] == 0:
            return None
        M[c], M[p] = M[p], M[c]
        for r in range(n):
            if r != c and M[r][c] != 0:
                f = M[r][c] / M[c][c]
                M[r] = [a - f * e for a, e in zip(M[r], M[c])]
    return [M[i][n] / M[i][i] for i in range(n)]


def local_poly_coefficients(x, xs, ys, h, degree=1, kernel=epanechnikov, delta=None):
    """Weighted least squares fit of y on 1, (x_i - x), ..., (x_i - x)^p.

    beta_k estimates m^(k)(x) / k!. Returns None if the local design is singular.
    """
    n = len(xs)
    w = [kernel((xi - x) / h) * (1 if delta is None else delta[i])  # @line L1
         for i, xi in enumerate(xs)]
    p = degree
    d = [xi - x for xi in xs]
    S = [[sum(w[i] * d[i] ** (j + k) for i in range(n)) for k in range(p + 1)]  # @line L2
         for j in range(p + 1)]
    t = [sum(w[i] * d[i] ** j * ys[i] for i in range(n)) for j in range(p + 1)]
    return solve(S, t)  # @line L3


def local_poly(x, xs, ys, h, degree=1, kernel=epanechnikov, delta=None):
    """The local polynomial estimate of m(x): the intercept beta_0."""
    beta = local_poly_coefficients(x, xs, ys, h, degree, kernel, delta)
    return None if beta is None else beta[0]


def local_linear_closed_form(x, xs, ys, h, kernel=epanechnikov):
    """Reference: m(x) = sum w_i (S2 - S1 d_i) y_i / (S0 S2 - S1^2), d_i = x_i - x."""
    w = [kernel((xi - x) / h) for xi in xs]
    d = [xi - x for xi in xs]
    s0 = sum(w)
    s1 = sum(wi * di for wi, di in zip(w, d))
    s2 = sum(wi * di * di for wi, di in zip(w, d))
    den = s0 * s2 - s1 * s1
    if den == 0:
        return None
    return sum(wi * (s2 - s1 * di) * yi for wi, di, yi in zip(w, d, ys)) / den


def median(v):
    s = sorted(v)
    k = len(s)
    return s[k // 2] if k % 2 else (s[k // 2 - 1] + s[k // 2]) / 2


def lowess(xs, ys, frac=2 / 3, iterations=2):
    """LOWESS of Cleveland (1979): local linear fits with tricube weights over
    the k = round(frac n) nearest neighbours, then robustness iterations with
    bisquare weights of the residuals scaled by 6 times their median absolute value.

    Returns the fitted values at the x_i.
    """
    n = len(xs)
    k = max(2, min(n, int(frac * n + 0.5)))
    delta = [1] * n  # @line L4
    # h_i: the distance from x_i to its k-th nearest x_j (x_i itself counts).
    hs = [sorted(abs(xj - xi) for xj in xs)[k - 1] for xi in xs]
    fit = list(ys)
    for it in range(iterations + 1):  # @line L5
        fit = []
        for i in range(n):
            h = hs[i]
            if h == 0:
                fit.append(ys[i])
                continue
            v = local_poly(xs[i], xs, ys, h, 1, tricube, delta)  # @line L6
            if v is None:  # too few distinct points with weight: fall back to degree 0
                v = local_poly(xs[i], xs, ys, h, 0, tricube, delta)
            fit.append(ys[i] if v is None else v)
        if it == iterations:
            break
        r = [y - f for y, f in zip(ys, fit)]  # @line L7
        s = median([abs(v) for v in r])
        if s == 0:  # @line L8
            delta = [1 if v == 0 else 0 for v in r]
        else:
            delta = [bisquare(v / (6 * s)) for v in r]
    return fit  # @line L9
test_local_polynomial_regression.py 109 lines
# SPDX-License-Identifier: MIT
# Part of https://algorithm.tamnd.com/local-polynomial-regression/. The authors are listed in prov/C1XC0A.jsonl.

import random
from fractions import Fraction

from local_polynomial_regression import (
    epanechnikov, local_linear_closed_form, local_poly, local_poly_coefficients,
    lowess, tricube,
)

LOWESS_X = list(range(1, 11))
LOWESS_Y = [3.1, 4.9, 7.2, 8.8, 11.1, 13.0, 30.0, 16.9, 19.2, 21.0]


def F(v):
    return [Fraction(t) for t in v]


def test_page_example() -> None:
    xs = list(range(7))
    sq = [x * x for x in xs]
    ll = [local_poly(Fraction(x), xs, sq, Fraction(3)) for x in xs]
    lc = [local_poly(Fraction(x), xs, sq, Fraction(3), 0) for x in xs]
    assert ll == [Fraction(-20, 73), Fraction(67, 35), Fraction(28, 5), Fraction(53, 5),
                  Fraction(88, 5), Fraction(907, 35), Fraction(2608, 73)]
    assert lc == [Fraction(14, 11), Fraction(43, 15), Fraction(28, 5), Fraction(53, 5),
                  Fraction(88, 5), Fraction(343, 15), Fraction(302, 11)]
    line = [2 * x for x in xs]
    assert [local_poly(Fraction(x), xs, line, Fraction(2)) for x in xs] == line
    plain = lowess(LOWESS_X, LOWESS_Y, 2 / 3, 0)
    robust = lowess(LOWESS_X, LOWESS_Y, 2 / 3, 2)
    assert abs(plain[6] - 19.31) < 0.01
    assert all(abs(f - (2 * x + 1)) < 0.1 for x, f in zip(LOWESS_X, robust))


def test_reproduces_polynomials_of_its_degree_exactly() -> None:
    rng = random.Random(81)
    checked = 0
    for _ in range(150):
        p = rng.choice((1, 1, 2, 3))
        n = rng.randint(p + 1, 12)
        xs = [Fraction(rng.randint(-30, 30), rng.randint(1, 4)) for _ in range(n)]
        coef = [Fraction(rng.randint(-9, 9), rng.randint(1, 5)) for _ in range(p + 1)]
        q = lambda t: sum(c * t ** k for k, c in enumerate(coef))
        ys = [q(t) for t in xs]
        h = Fraction(rng.randint(2, 40), rng.randint(1, 3))
        # Any x, including points at the edge of the data and outside it.
        x = Fraction(rng.randint(-40, 40), rng.randint(1, 4))
        beta = local_poly_coefficients(x, xs, ys, h, p)
        if beta is None:  # fewer than p + 1 distinct points with weight
            continue
        checked += 1
        assert beta[0] == q(x)
        if p >= 1:  # beta_1 is the slope q'(x)
            assert beta[1] == sum(k * c * x ** (k - 1) for k, c in enumerate(coef) if k)
    assert checked > 50


def test_local_linear_matches_closed_form() -> None:
    rng = random.Random(82)
    for _ in range(200):
        n = rng.randint(1, 10)
        xs = [Fraction(rng.randint(-20, 20), rng.randint(1, 3)) for _ in range(n)]
        ys = [Fraction(rng.randint(-20, 20)) for _ in range(n)]
        h = Fraction(rng.randint(1, 30), rng.randint(1, 3))
        x = Fraction(rng.randint(-25, 25), rng.randint(1, 3))
        assert local_poly(x, xs, ys, h, 1) == local_linear_closed_form(x, xs, ys, h)


def test_degree_zero_is_nadaraya_watson() -> None:
    rng = random.Random(83)
    for _ in range(200):
        n = rng.randint(1, 10)
        xs = [Fraction(rng.randint(-20, 20), rng.randint(1, 3)) for _ in range(n)]
        ys = [Fraction(rng.randint(-20, 20)) for _ in range(n)]
        h = Fraction(rng.randint(1, 30), rng.randint(1, 3))
        x = Fraction(rng.randint(-25, 25), rng.randint(1, 3))
        w = [epanechnikov((x - xi) / h) for xi in xs]
        nw = sum(a * b for a, b in zip(w, ys)) / sum(w) if sum(w) else None
        assert local_poly(x, xs, ys, h, 0) == nw


def test_boundary_bias_is_of_order_h_squared() -> None:
    # Uniform design i/N on [0, 1]. A line has no bias at the end point 0,
    # and for m(x) = x^2 the bias over h^2 tends to
    # (mu2^2 - mu1 mu3) / (mu0 mu2 - mu1^2) = -11/95 (Epanechnikov, one-sided moments).
    for N, h in ((1000, Fraction(1, 10)), (4000, Fraction(1, 20))):
        xs = [Fraction(i, N) for i in range(N + 1)]
        assert local_poly(Fraction(0), xs, [3 - 2 * x for x in xs], h) == 3
        ratio = local_poly(Fraction(0), xs, [x * x for x in xs], h) / (h * h)
        assert abs(ratio + Fraction(11, 95)) < Fraction(1, 2) / (N * h)


def test_lowess_on_a_line_and_with_outliers() -> None:
    xs = F(range(12))
    line = [Fraction(5) - Fraction(1, 3) * x for x in xs]
    assert lowess(xs, line, 2 / 3, 2) == line
    rng = random.Random(84)
    xs = sorted(rng.uniform(0, 10) for _ in range(40))
    ys = [1 + 0.5 * x + rng.gauss(0, 0.2) for x in xs]
    for i in rng.sample(range(5, 35), 4):
        ys[i] += 15
    truth = [1 + 0.5 * x for x in xs]
    err = lambda fit: max(abs(f - t) for f, t in zip(fit, truth))
    # Measured on this seed: robustness weights remove the pull of the outliers.
    assert err(lowess(xs, ys, 2 / 3, 0)) > 1.0
    assert err(lowess(xs, ys, 2 / 3, 2)) < 0.4
    assert tricube(Fraction(1, 2)) == Fraction(343, 512)

History

Fitting low-degree polynomials to moving windows is old: actuaries used it for graduation of mortality tables, and Savitzky and Golay (1964) used it on equally spaced spectra. Stone (1977) studied local polynomial fits in his work on consistent nonparametric regression. Cleveland (1979) introduced LOWESS for scatter plots, with nearest-neighbour windows, tricube weights and robustness iterations. Cleveland and Devlin (1988) extended it to LOESS. Fan (1992, 1993) and Fan and Gijbels (1992) showed that the local linear fit has no design bias, adapts to the boundary, and is minimax efficient among linear smoothers. Their 1996 book made local polynomial fitting the standard view of kernel regression, with the Nadaraya-Watson estimator as the case p=0p = 0.

References

  1. William S. Cleveland, Robust locally weighted regression and smoothing scatterplots, Journal of the American Statistical Association 74(368), 1979, pp. 829 to 836 (LOWESS; the tricube weights on the nearest neighbours, and the robustness iterations with bisquare weights and 6 times the median absolute residual)
  2. William S. Cleveland and Susan J. Devlin, Locally weighted regression. An approach to regression analysis by local fitting, Journal of the American Statistical Association 83(403), 1988, pp. 596 to 610 (LOESS with several predictors and local quadratic fits)
  3. Jianqing Fan, Design-adaptive nonparametric regression, Journal of the American Statistical Association 87(420), 1992, pp. 998 to 1004 (the local linear smoother has no design bias)
  4. Jianqing Fan, Local linear regression smoothers and their minimax efficiencies, The Annals of Statistics 21(1), 1993, pp. 196 to 216 (minimax efficiency of the local linear smoother)
  5. Jianqing Fan and Irène Gijbels, Variable bandwidth and local linear regression smoothers, The Annals of Statistics 20(4), 1992, pp. 2008 to 2036 (the local linear fit adapts automatically to the boundary)
  6. D. Ruppert and M. P. Wand, Multivariate locally weighted least squares regression, The Annals of Statistics 22(3), 1994, pp. 1346 to 1370 (bias and variance of local polynomial fits, in the interior and at the boundary, in several dimensions)
  7. Jianqing Fan and Irène Gijbels, Local Polynomial Modelling and Its Applications, Chapman and Hall, 1996, Chapter 3 (the local polynomial fit, its equivalent kernel, and its bias and variance)

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.lowess
  • a full proof of time.worst
  • 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