Foundations 2: Smoothness and Least Squares

Back to regularizeNd series home

Previous: Foundations 1: Fidelity Equations

Prerequisites: Foundations 1: Fidelity Equations.

Learning goals

NoteSource and attribution

This page is adapted from “Introduction to Regularizing with 2D Data – Part 2 of 3” by Peter Goldstein, published January 31, 2013 on Math for Mere Mortals (under the username kintaar): https://mathformeremortals.wordpress.com/2013/01/31/introduction-to-regularizing-with-2d-data-part-2-of-3/ (Goldstein 2013a).

This page is an independent implementation and modernization of that article’s ideas for regularizeNd, not a transcription. Its text, equations, examples, numbers, and figures were written and computed for this site.

Foundations 1 built the fidelity matrix \(A_f\) for five samples on the nonuniform output grid \(g=[0,\ 1,\ 2,\ 2.5,\ 3,\ 4]\). Each row holds the linear-interpolation weights that turn the six table values \(z\) into a prediction at one sample, so \(A_f z \approx y\) is a \(5\times 6\) system.

addpath('fixtures');
r = regularizeNdFoundationsFixtures(Verbose=false);
fx = r.oneD;
x = fx.x;  y = fx.y;  g = fx.grid;
Af = fx.system.fidelity;
N = numel(g);  Nf = numel(x);

Why add a smoothness preference

Five fidelity equations cannot fix six unknowns. Many tables reproduce the samples equally well, and they differ in how the curve bends between and beyond the samples. We need a rule that picks one of them.

regularizeNd’s rule is a preference: among tables that fit the data about equally well, choose the one whose slope changes slowly. Slope change is the second derivative, so the new equations ask the second derivative of the table to be zero at every interior node. Unless the samples lie on a straight line, these equations cannot all hold together with the fidelity equations, and that is intended. Least squares will trade the two kinds of error against each other.

The second derivative on a nonuniform grid

Write the grid nodes as \(g_1<g_2<\dots<g_N\) and the table values as \(z_1,\dots,z_N\). (The deep dive writes the same formula with \(x\) for the nodes.) At an interior node \(g_j\), take its neighbours and the spacings

\[ h_- = g_j - g_{j-1},\qquad h_+ = g_{j+1} - g_j . \]

Exactly one parabola passes through the three points \((g_{j-1},z_{j-1})\), \((g_j,z_j)\), \((g_{j+1},z_{j+1})\). In Lagrange form,

\[ p(t) = z_{j-1}\frac{(t-g_j)(t-g_{j+1})}{(g_{j-1}-g_j)(g_{j-1}-g_{j+1})} + z_j\frac{(t-g_{j-1})(t-g_{j+1})}{(g_j-g_{j-1})(g_j-g_{j+1})} + z_{j+1}\frac{(t-g_{j-1})(t-g_j)}{(g_{j+1}-g_{j-1})(g_{j+1}-g_j)} . \]

Each numerator is a quadratic in \(t\) with leading coefficient 1, so its second derivative is 2. The parabola’s second derivative is therefore a constant, a fixed linear combination of the three values:

\[ p'' = \frac{2}{h_-(h_-+h_+)}\,z_{j-1} \;-\; \frac{2}{h_-h_+}\,z_j \;+\; \frac{2}{h_+(h_-+h_+)}\,z_{j+1}. \]

This is the formula in the deep dive’s Regularization blocks section. On a uniform grid, \(h_-=h_+=h\), it reduces to the familiar \((z_{j-1}-2z_j+z_{j+1})/h^2\).

A grid with \(N\) nodes has \(N-2\) interior nodes, so it gives \(N-2\) smoothness rows. The fixture grid has 6 nodes and 4 rows. Collected into the unscaled matrix \(D\), with columns in grid order:

Row Node triple \(h_-\) \(h_+\) Weights
1 \((0,\ 1,\ 2)\) 1 1 \([1,\ -2,\ 1]\)
2 \((1,\ 2,\ 2.5)\) 1 0.5 \([\tfrac43,\ -4,\ \tfrac83]\)
3 \((2,\ 2.5,\ 3)\) 0.5 0.5 \([4,\ -8,\ 4]\)
4 \((2.5,\ 3,\ 4)\) 0.5 1 \([\tfrac83,\ -4,\ \tfrac43]\)

\[ D=\begin{bmatrix} 1&-2&1&0&0&0\\ 0&\tfrac43&-4&\tfrac83&0&0\\ 0&0&4&-8&4&0\\ 0&0&0&\tfrac83&-4&\tfrac43 \end{bmatrix}. \]

The weights change with the spacing for two reasons. First, they scale like \(1/h^2\). Row 3 is row 1 with the spacing halved, and every weight is four times larger. The same jump in \(z\) over a shorter interval is a steeper slope, so the same kink means more bending. Second, an uneven triple gives uneven weights, and the node across the shorter gap gets the larger weight. In row 2 the right gap is half the left gap, so the right weight \(\tfrac83\) is twice the left weight \(\tfrac43\). Row 4 is the mirror image.

The code below builds \(D\) from the spacing formula and checks it against the fixture. It then applies \(D\) to a constant, a straight line, and a parabola, all sampled on the grid.

stencil = @(gl, gc, gr) [2./((gc-gl).*(gr-gl)), -2./((gc-gl).*(gr-gc)), 2./((gr-gc).*(gr-gl))];
secondDiff = @(g) sparse(repmat((1:numel(g)-2)', 1, 3), (1:numel(g)-2)' + (0:2), ...
    stencil(g(1:end-2), g(2:end-1), g(3:end)), numel(g)-2, numel(g));

D = secondDiff(g);
Ns = size(D, 1);
assert(max(abs(D - fx.system.d2), [], 'all') < 1e-14)
disp(rats(full(D)))

constant = ones(N, 1);  straight = g;  parabola = g.^2;
table(D*constant, D*straight, D*parabola, VariableNames=["constant", "line", "g^2"])
       1            -2             1             0             0             0      
       0            4/3           -4            8/3            0             0      
       0             0             4            -8             4             0      
       0             0             0            8/3           -4            4/3     
ans = 4×3 table
constant line g^2
0 0 2
-4.4409e-16 -8.8818e-16 2.0000
0 0 2
-2.2204e-16 -8.8818e-16 2.0000

Every row returns 0 for the constant and the line (to round-off), and 2 for \(g^2\), which is the exact second derivative of \(t^2\). The weights in a row sum to zero, which removes constants. Their sum against the node positions is also zero, which removes the linear term. The fixture asserts both properties.

That makes the straight line special. \(D\) has \(N-2\) independent rows, so its null space has dimension 2, and it contains a constant and a line. The only tables with zero smoothness penalty are straight lines \(z_j=a+b\,g_j\). The regularizer cannot see a straight line, and every other shape costs something.

Scaling the smoothness rows

regularizeNd does not stack \(D\) as it is. It multiplies it by a single number,

\[ L = s\cdot\sqrt{\frac{N_f}{N_s}}\cdot(g_N-g_1)^2\cdot D , \]

where \(N_f\) is the number of fidelity rows (one per sample) and \(N_s\) is the number of smoothness rows. Each factor has a job.

  • \(s\) is the user’s smoothness. It sets how much bending matters compared with missing the samples. Larger \(s\) means a stiffer table.
  • \(\sqrt{N_f/N_s}\) balances row counts. Least squares adds up squared residuals, so a block with more rows has more say. Refining the output grid adds smoothness rows without adding data. This factor keeps the total weight of the smoothness block in proportion to the fidelity block, so the same \(s\) means about the same thing on a coarse or a fine grid. The square root appears because the residuals are squared. Foundations 3 shows what goes wrong without it.
  • \((g_N-g_1)^2\) removes the units of \(x\). The weights in \(D\) have units of \(1/x^2\). Multiplying by the squared axis range cancels them, which is the same as measuring the axis on \([0,1]\). A table in millimetres and the same table in metres then get the same penalty from the same \(s\).

For the fixture, \(s=0.01\), \(N_f=5\), \(N_s=4\), and the range is \(4-0=4\):

\[ 0.01\cdot\sqrt{5/4}\cdot 4^2 = 0.01\cdot 1.118034\cdot 16 = 0.1788854382 . \]

The cell below forms \(L\), then repeats the construction with every grid coordinate multiplied by 1000, as if the axis were measured in units a thousand times smaller. The weights of \(D\) shrink by \(1000^2\), the range factor grows by \(1000^2\), and \(L\) is unchanged to round-off.

smoothnessBlock = @(g, s) s * sqrt(Nf/(numel(g)-2)) * (g(end)-g(1))^2 * secondDiff(g);

L = smoothnessBlock(g, 0.01);
multiplier = 0.01 * sqrt(Nf/Ns) * (g(end)-g(1))^2;
fprintf('multiplier = %.10f\n', multiplier)
assert(max(abs(L - fx.system.regularization), [], 'all') < 1e-14)

Lscaled = smoothnessBlock(1000*g, 0.01);
unitChange = full(max(abs(L - Lscaled), [], 'all'))
multiplier = 0.1788854382
unitChange = 5.5511e-17

Stacking and solving

Put the two blocks on top of each other. The smoothness rows ask for zero bending, so their right-hand side is zero:

\[ A=\begin{bmatrix}A_f\\ L\end{bmatrix},\qquad b=\begin{bmatrix}y\\ 0\end{bmatrix},\qquad \min_z\ \|Az-b\|_2^2 \;=\; \min_z\ \Big(\|A_fz-y\|_2^2+\|Lz\|_2^2\Big). \]

For the fixture, \(A\) has 9 rows and 6 columns. The fidelity block has rank 5, and adding \(L\) raises the rank to 6, so the least-squares problem has exactly one solution. It still cannot make all nine residuals zero, so the solution is a compromise between the two blocks.

A = [Af; L];
b = [y; zeros(Ns, 1)];
z = A \ b;
assert(max(abs(z - fx.system.solution)) < 1e-12)

sizeOfA = size(A)
rankOfAf = rank(full(Af))
rankOfA = rank(full(A))
table(g, z, VariableNames=["node g", "table value z"])
sizeOfA = 1×2 double
     9     6
rankOfAf = 5
rankOfA = 6
ans = 6×2 table
node g table value z
0 0.9508
1 1.2046
2 0.6536
2.5000 0.8810
3 0.9258
4 -0.0477

The fitted table is

\[ z \approx [0.950780,\ 1.204629,\ 0.653552,\ 0.881039,\ 0.925797,\ -0.047683]^T . \]

The table does not pass through the samples. Interpolating it back to the sample locations gives \(A_f z\):

Sample \(x\) 0.35 1.00 1.80 2.70 3.65
Sample \(y\) 1.0 1.4 0.4 1.2 0.2
Fitted \(A_f z\) 1.039627 1.204629 0.763767 0.898942 0.293035

The largest miss is at \(x=1.80\), where the samples on either side pull the curve up and the smoothness rows resist a sharp dip. Even the sample at \(x=1.00\), which sits exactly on a node, is missed. Foundations 3 takes these residuals apart.

close all
figure
plot(g, z, '-o', 'LineWidth', 1.5, 'DisplayName', 'fitted table z')
hold on; grid on
plot(x, y, 'rx', 'MarkerSize', 12, 'LineWidth', 2, 'DisplayName', 'samples')
fitted = Af * z;
gray = [0.5 0.5 0.5];
plot(x, fitted, 'o', 'Color', gray, 'MarkerSize', 8, 'LineWidth', 1.5, 'DisplayName', 'fitted value A_f z')
plot([x x]', [y fitted]', '--', 'Color', gray, 'HandleVisibility', 'off')
xlabel('x'); ylabel('y')
title('Fidelity and smoothness rows solved together (s = 0.01)')
legend('Location', 'southwest')

The least-squares table for s = 0.01 (linear between nodes) against the five samples. Gray circles mark the fitted values A_f z at the sample locations; dashed segments show each miss.

Setting the gradient of \(\|Az-b\|_2^2\) to zero gives the normal equations

\[ (A^TA)\,z = A^Tb . \]

Each fidelity row touches two neighbouring nodes and each smoothness row touches three, so every nonzero of \(A^TA\) lies within two places of the diagonal: it is pentadiagonal. Foundations 4 shows how to build and store this matrix efficiently. Foundations 5 traces how each row projects into it.

zNormal = (A'*A) \ (A'*b);
normalVersusQR = max(abs(zNormal - z))
[i, j] = find(A'*A);
bandwidth = max(abs(i - j))
normalVersusQR = 4.4409e-16
bandwidth = 2

How the smoothness value changes the fit

The same assembly works for any \(s\). The figure repeats the solve for four values a factor of ten apart and adds the least-squares straight line through the five samples.

sList = [0.001 0.01 0.1 1];
lineCoef = [x, ones(Nf, 1)] \ y;
zLine = [g, ones(N, 1)] * lineCoef;

figure
plot(x, y, 'rx', 'MarkerSize', 12, 'LineWidth', 2, 'DisplayName', 'samples')
hold on; grid on
fidelitySSE = zeros(size(sList));  maxFromLine = zeros(size(sList));
for k = 1:numel(sList)
    zk = [Af; smoothnessBlock(g, sList(k))] \ b;
    fidelitySSE(k) = sum((Af*zk - y).^2);
    maxFromLine(k) = max(abs(zk - zLine));
    plot(g, zk, '-o', 'LineWidth', 1.5, 'DisplayName', sprintf('s = %g', sList(k)))
end
plot(g, zLine, '--', 'Color', [0.5 0.5 0.5], 'LineWidth', 2, 'DisplayName', 'least-squares line')
xlabel('x'); ylabel('y')
title('Effect of the smoothness value')
legend('Location', 'southwest')

table(sList', fidelitySSE', maxFromLine', ...
    VariableNames=["s", "fidelity SSE", "max |z - line| at nodes"])

Fitted tables for four smoothness values. As s grows, the table flattens onto the least-squares straight line through the samples.
ans = 4×3 table
s fidelity SSE max |z - line| at nodes
1.0000e-03 1.9590e-04 0.8457
0.0100 0.2714 0.4207
0.1000 0.7086 0.0309
1 0.7293 3.5169e-04

At \(s=0.001\) the table follows the samples closely, with a fidelity SSE of about 0.0002, but it is still a compromise. At \(s=1\) it is within 0.0004 of the straight line at every node. The limit makes sense: as \(s\) grows, any bending costs more than any miss, so the table is pushed into the null space of \(D\), which is the straight lines. Linear interpolation reproduces a straight line exactly, so the best straight-line table is the least-squares line through the samples. Choosing \(s\) for real data is the subject of Part 2.

Connection to regularizeNd

regularizeNdMatrices returns the two blocks built on this page. Lreg is a cell array with one smoothness block per input axis. In 1D, Lreg{1} is exactly \(L\), already scaled by \(s\sqrt{N_f/N_s}(g_N-g_1)^2\). regularizeNd stacks the blocks with zeros on the right-hand side and solves. Its default solver, 'normal', solves the normal equations:

x = [0.35; 1.00; 1.80; 2.70; 3.65];
y = [1.0; 1.4; 0.4; 1.2; 0.2];
xGrid = {[0; 1; 2; 2.5; 3; 4]};

[Afidelity, Lreg] = regularizeNdMatrices(x, xGrid, 0.01, 'linear');
% Afidelity is A_f; Lreg{1} is 0.1788854382 * D

% What regularizeNd does with the default 'normal' solver:
A = vertcat(Afidelity, Lreg{:});
nSmoothness = sum(cellfun(@(L) size(L, 1), Lreg));
z = (A'*A) \ (A'*[y; sparse(nSmoothness, 1)]);

% The same table in one call:
z = regularizeNd(x, y, xGrid, 0.01, 'linear');

The package is not run on this page. The fixture script’s package cross-check compared its fidelity matrix and smoothness block with regularizeNdMatrices, and its solution with regularizeNd (run with the '\' solver). All agreed to \(8.88\times10^{-16}\). The normal-equation solve above matches the QR solution to round-off. The other solvers ('\' for sparse QR, and the iterative 'pcg', 'symmlq', and 'lsqr') solve the same least-squares problem by different routes.

How this differs from the original

  • Scale factor. The original scales the second-derivative rows by \(S=K\sqrt{N_f/N_d}\), with \(N_d\) the number of derivative rows. regularizeNd also multiplies by the squared axis range \((g_N-g_1)^2\). So the original’s \(K\) and regularizeNd’s \(s\) are not interchangeable numbers. On this fixture’s grid, the same value would give a block 16 times weaker under the original scheme.
  • Same stencil. Both use the same three-point second-derivative weights, so rows next to a change in spacing get different weights. They are reached by different routes. The original takes them from an earlier article, A Numerical Second Derivative from Three Points, which finds the slope on each side of the middle node, treats each slope as sitting at its interval’s midpoint, and divides their difference by the distance between those midpoints, \((g_{j+1}-g_{j-1})/2\). That article then observes that the result equals the second derivative of the fitted parabola. This page starts from the parabola in Lagrange form.
  • Solver. The original forms the normal equations and points out that their pentadiagonal matrix suits Gaussian elimination with back-substitution. Its companion spreadsheet, offered with Part 3 (Goldstein 2013b), did not do that: it solved the system with Excel’s MINVERSE(), an explicit matrix inverse. A banded elimination and back-substitution solver arrived later, in the RegularizeData2D VBA function (Goldstein 2013c, 2013d). regularizeNd’s default 'normal' solver also solves the normal equations, using MATLAB’s sparse factorization and no inverse, and the other solvers listed above are available when the normal equations are poorly conditioned or too large.
  • Terminology. The original calls one input and one output “2D data”. This site follows regularizeNd and calls it 1D input.

With fidelity rows, scaled smoothness rows, and a least-squares solve, the 1D method is complete. The next page splits the residual into its fidelity and smoothness parts and shows why the \(\sqrt{N_f/N_s}\) factor keeps the fit stable when the grid is refined.

Next

Back to regularizeNd series home

Previous: Foundations 1: Fidelity Equations

Next: Foundations 3: Normalization and Residuals

References

Goldstein, Peter. 2013a. “Introduction to Regularizing with 2D Data – Part 2 of 3.” Math for Mere Mortals. https://mathformeremortals.wordpress.com/2013/01/31/introduction-to-regularizing-with-2d-data-part-2-of-3/.
———. 2013b. “Introduction to Regularizing with 2D Data – Part 3 of 3.” Math for Mere Mortals. https://mathformeremortals.wordpress.com/2013/01/31/introduction-to-regularizing-with-2d-data-part-3-of-3/.
———. 2013c. “RegularizeData2D, the Excel Spreadsheet Function for Regularizing 2D Data – Part 1 of 2.” Math for Mere Mortals. https://mathformeremortals.wordpress.com/2013/02/13/regularizedata2d-the-excel-spreadsheet-function-for-regularizing-2d-data-part-1-of-2/.
———. 2013d. “RegularizeData2D, the Excel Spreadsheet Function for Regularizing 2D Data – Part 2 of 2.” Math for Mere Mortals. https://mathformeremortals.wordpress.com/2013/02/17/regularizedata2d-the-excel-spreadsheet-function-for-regularizing-2d-data-part-2-of-2/.