Measuring error

RMSE, relative L2, R² and max error: which number to report, and what each one hides.

Outcome: Compute MAE, RMSE, max error and R²; compute the relative L2 error per design, a common metric of field-surrogate papers; read a benchmark table, and check integrated quantities as well as fields; report errors in each case’s reference units, against a reference that needs no training, with the median and the seed spread.

Builds on Train, validation and test

A metric compares predictions y^\hat{y} with solver values yy over the test runs (and, for fields, over all their points). Each answers a different question, and hides something.

The simplest field model is the mean of the training fields, returned for every design whatever its inputs. On the 8 validation runs of the aircraft, Example 3-3 scores it R2R^2 0.946, yet its relative L2 error is 21 % and its lift is off by 0.27 on average.

  • MAE, mean absolute error: the typical size of an error, in the units of the output.
  • RMSE, root mean squared error: like MAE but weights large errors more. The square root of Equation 3-1, the loss of fitting.
  • Max error: the single worst point. For fields it usually sits where the field changes fastest, such as a suction peak.
  • R2R^2: 1−∑i(yi−y^i)2/∑i(yi−yˉ)21 - \sum_i (y_i - \hat{y}_i)^2 / \sum_i (y_i - \bar{y})^2, one minus the squared error over the spread of the data around its mean yˉ\bar{y}: the share of the variation the model explains. 1 is perfect, 0 is no better than predicting the mean, and on held-out runs it can go negative. It is easily high when the data vary a lot.

Relative L2, a common metric of field papers

Many field-surrogate papers report the relative L2 error.

DefinitionRelative L2 error

For each test design, the size of the error field divided by the size of the true field, both measured with the L2 norm (the square root of the sum of squares over all points).
relative L2=∥y^−y∥2∥y∥2\text{relative } L_2 = \frac{\lVert \hat{y} - y \rVert_2}{\lVert y \rVert_2}
(3-2)
Computed per test design, then averaged over designs. Tables often print it ×10−2\times 10^{-2}, so 1.9 means 1.9 %.

It makes designs with large and small fields comparable. If the field is close to zero, though, the denominator is small and the error explodes. It also depends on what is predicted: the same model scores differently on CpC_p and on pressure in pascals, where the large free-stream value inflates ∥y∥\lVert y \rVert.

VRMSE, the headline metric of The Well, a public collection of physics simulations, is the RMSE divided by the standard deviation of the true field, so 1.0 means no better than predicting the mean.

Area weighting

A mesh refined near the wall or at the leading edge puts many nodes there. A plain average over nodes then weights those regions heavily, and the far field barely counts. The average used should be stated; on the same model the two can differ noticeably.

For the error per square metre of surface (or cubic metre of volume), each point is weighted by the area or volume it stands for: the cell areas the solver already uses to integrate forces.

RMSEA=∑iai (y^i−yi)2∑iai\mathrm{RMSE}_A = \sqrt{\frac{\sum_i a_i \, (\hat{y}_i - y_i)^2}{\sum_i a_i}}
(3-3)
aia_i: the area or volume point ii stands for. With all aia_i equal it is the ordinary RMSE.

The weighted sums are a quadrature of the integrals they stand for (a Riemann sum), so they converge as the mesh is refined. A plain average over nodes converges instead to a mean weighted by the mesher’s point density.

Errors in context

Against the spread of the data. An RMSE means little alone: read against the standard deviation of the target, as in VRMSE, it gives the typical error as a share of the variation.

In each case’s own units. When test cases differ in speed or size, an error in SI units averaged over them is set mostly by the fastest or largest. Each case’s error is better computed in its own reference units, as for CpC_p (physical fields): velocity divided by the case’s free-stream speed, pressure by its dynamic pressure. Unlike the relative L2 error, this does not explode where the true field is small, since the divisor is a known input of the case.

Against a trivial reference. Weather forecasters score a forecast against one that needs no skill, such as persistence or climatology, as a skill score: one minus the forecast’s mean squared error over the reference’s (Murphy 1988). R2R^2 is the skill score whose reference is the mean of the data. For a flow, a reference that needs no training is the free stream predicted everywhere. A model whose error is near that reference’s shows no skill, however small the number looks.

Over cases and seeds. A few hard cases can set a mean, so the median belongs beside it, and so does the spread over training seeds: one run per model cannot separate two models whose errors differ by less than that spread.

On the integrated quantities. Lift and drag computed from the predicted field are compared with the solver’s. Small field errors that push the same way add up: a CpC_p error of 0.02 over the whole upper surface of a wing shifts CLC_L by about 0.02, while a uniform offset over a closed surface cancels exactly. Drag is a small difference of large pressure forces. Drag is often quoted in counts (one count is ΔCD=0.0001\Delta C_D = 0.0001), as a mean absolute error and a maximum.

As a ranking. To pick among designs, the right order often matters more than exact values; a limit on stress or temperature needs the value itself. The Spearman rank correlation between predicted and true drag (1 = same order) checks that; AirfRANS scores it. Small field errors can still scramble the order when designs differ by little.

Against the solver’s own error. For an absolute value, a 1 % surrogate error matters little next to a 5 % solver error against the tunnel, but it can decide a comparison of designs that differ by 1 % (see is the training data right?).

By region. An average can hide a large error where the design is decided; a map of the error over the geometry shows it. On the site’s surrogate the largest errors sit at the leading-edge suction peak and the wing tips (see testing on unseen designs).

Example 3-3 adds two functions to aircraft.py: lift, Equation 2-2 on the aircraft’s own points, and scores, every metric of this lesson for a predicted field. It then scores the mean-field baseline.

Example 3-3. Point, field, area-weighted, lift and ranking metrics, with NumPy, SciPy and scikit-learn
# Add to aircraft.py, with its other imports at the top:
from scipy.stats import spearmanr
from sklearn.metrics import (mean_absolute_error, r2_score,
                             root_mean_squared_error)

def lift(cp, d, idx):
    """CL of runs idx, integrated from their Cp."""
    a = np.radians(d["alpha"][idx])[:, None]
    n = d["normal"][idx]
    n_L = n[..., 1] * np.cos(a) - n[..., 0] * np.sin(a)1
    f = cp * n_L * d["area"][idx]
    return -f.sum(axis=1) / d["S_ref"][0]

def scores(pred, d, idx):
    """Errors of pred, (runs, points), on the runs idx."""
    true = d["cp"][idx]
    err = pred - true
    t, p = true.ravel(), pred.ravel()2
    a = d["area"][idx]3
    rel = (np.linalg.norm(err, axis=1)
           / np.linalg.norm(true, axis=1))4
    cl_p, cl_t = lift(pred, d, idx), lift(true, d, idx)
    return {
        "RMSE": root_mean_squared_error(t, p),
        "MAE": mean_absolute_error(t, p),
        "max": np.abs(err).max(),
        "R2": r2_score(t, p),
        "rel_L2": rel.mean(),
        "RMSE_A": np.sqrt((a * err**2).sum() / a.sum()),
        "dCL": np.abs(cl_p - cl_t).mean(),
        "Spearman": spearmanr(cl_p, cl_t)[0],5
    }

# Then, in a script:
import numpy as np
from aircraft import load_runs, scores, split_runs

d = load_runs()
train, val, test, in_box = split_runs(d)

# The mean-field baseline: one field for every design,
# the mean of the training fields.
mean_field = d["cp"][train].mean(axis=0)
pred = np.tile(mean_field, (len(val), 1))
for name, value in scores(pred, d, val).items():
    print(f"{name:9s}{value:7.3f}")
  1. The component of each outward normal in the lift direction, perpendicular to the flow at angle of attack α\alpha (with xx along the free stream at zero angle of attack and yy up): the nL,in_{L,i} of Equation 2-2.
  2. ravel flattens (runs, points) into one long vector, so RMSE, MAE and R2R^2 pool every point of every run, as the max error does. root_mean_squared_error needs scikit-learn 1.4 or later.
  3. The area of every point of every run, shape (runs, points): the aia_i of Equation 3-3. The sums run over both axes, so RMSE_A pools every point of every run, like the RMSE.
  4. axis=1 takes the norm over the points of each run: one relative L2 error per run (Equation 3-2), then the mean.
  5. spearmanr returns the correlation and a p-value; [0] keeps the correlation, here of the runs ranked by lift.
RMSE       0.149
MAE        0.060
max        1.231
R2         0.946
rel_L2     0.209
RMSE_A     0.138
dCL        0.271
Spearman   0.786

On the 8 validation runs Example 3-3 prints an R2R^2 of 0.946: a model that ignores its inputs explains 95 % of the variance, because most of the variation of CpC_p is from point to point over the surface, and the mean field already has it. Weighting by area lowers the RMSE from 0.149 to 0.138: the largest errors sit where the points are densest. Even the ranking by lift scores 0.786, though the predicted field is the same for every run; only the lift direction and the geometry change from run to run. Example 3-5 scores a real surrogate with the same function.

Check yourself

  1. 1The target is switched from Cp to pressure in pascals (free stream about 10⁵ Pa). The relative L2 error drops from 4 % to 0.1 %. Has the model improved?
  2. 2The mesh is refined at the leading edge, which is also where the model’s errors are largest. Which RMSE comes out larger?
  3. 3A drag study must pick the best of 12 variants that differ by little. Beyond the field RMSE, what should be checked?
RMSE is 0.05 in Cp. Good or bad?

It depends on the spread of the data. Next to a Cp standard deviation of 0.36, for example, it is about 14 % of the variation; report both, and the max error.

The test cases have inlet speeds from 0.25 to 50 m/s. Why not average velocity errors in m/s over them?

The fastest cases would set the average. Compute each case’s error in its own reference units (velocity divided by its free-stream speed, pressure by its dynamic pressure), then average over cases and give the median as well.

A model’s mean squared error on a test case is 0.0036 and that of the free stream predicted everywhere is 0.0040. What is its skill score, and what does it say?

1 − 0.0036/0.0040 = 0.1. The model removes only a tenth of the squared error of a reference that needs no training: little skill on that case, however small 0.0036 looks.

Exercises

  1. Exercise 3-3. Score the mean-field baseline of the lesson’s listing on the 12 test runs, inside and outside the box. Why is its R² so high on every set?

    Answer

    Inside the box: relative L2 error 0.167, R² 0.958, lift error 0.218. Outside: 0.372, 0.807 and 0.491. R² pools every point of every run, and most of the variation of Cp is from point to point over the surface, which the mean field already has. Measured point by point across the validation runs (r2_score(true, pred, multioutput="variance_weighted")), the same baseline scores R² −0.12: no better than the mean, as it should be.

Go further