Polynomial regression: fitting curves and choosing degree
多项式回归
Use scaled polynomial features and QR least squares, verify a small fit exactly, and compare interpolation with validation and extrapolation.
polynomial-regressionA curved prediction can still be a linear model
A sensor’s response may bend as its input increases. A straight line misses that bend; a quadratic can describe it with three coefficients. The new feature is the squared input, not a new kind of optimizer.
For one input x, a polynomial of degree at most d predicts:
The curve is nonlinear in x when higher powers contribute, but linear in the unknown coefficients. Degree 0 gives a constant, degree 1 a line, and degree 2 permits a parabola. The highest coefficient may be zero, so choosing d means “at most d,” not a guarantee of that exact degree. The official scikit-learn 1.7 documentation explains this basis-function interpretation. §1.1.18.
The important choice is how much curvature the data justify. In the example below, a fourth-degree curve hits five noisy training points exactly. A quadratic predicts new points better. That result will come from executed numbers rather than a claim that higher degrees always fail.
Fit coefficients in the expanded feature space
For n observations, put the powers of each input in one row of a Vandermonde design matrix V. Ordinary least squares chooses coefficients by:
The last equality follows by differentiating the squared loss. It says the residual is orthogonal to every fitted feature column. The objective is convex. The coefficient vector is unique when V has full column rank. For this univariate basis, d+1 distinct input values suffice: a nonzero polynomial of degree at most d cannot have more than d distinct roots. Repeated inputs may still be useful repeated measurements, but do not add distinct design locations.
With n distinct inputs and d = n−1, an interpolating polynomial fits arbitrary responses exactly in exact arithmetic. Noise is included in those responses. A zero training residual therefore does not establish that the underlying response law is known.
No Gaussian assumption is needed to define or solve this finite least-squares problem. Interpreting it as an estimate of a conditional mean additionally calls for a suitable sampling/error model; uncertainty intervals require further assumptions and calculations. Polynomial coefficients by themselves do not establish causation.
Scaling changes coordinates, not the unpenalized function family
The program uses u = (x−c)/s, with c the training-input midpoint and s its largest absolute deviation, or 1 for a constant input. It fits powers of u and stores c and s with the coefficients. Training inputs then lie in [−1,1]. Coefficients must be evaluated in u, not substituted directly into powers of the original x.
For nonzero s, the complete degree-d bases in x and u span the same polynomials. Exact unpenalized fitted predictions are invariant to this affine change; coefficient values are not. A ridge penalty on the coefficient numbers generally changes under a basis change unless its penalty is transformed too. See ridge regression and conditioning.
Powers can still become nearly dependent after scaling. The implementation applies Householder reflections to V and y together, obtaining the QR least-squares reduction:
Here Q denotes the thin orthonormal factor; the code does not form it or an inverse. It transforms the right-hand side and back-substitutes in R. This avoids forming VᵀV, whose 2-norm condition number is squared for a full-rank V. Linear regression gives that connection; SVD provides a broader rank-sensitive route. NumPy 2.3’s polynomial least-squares routine uses SVD and reports rank diagnostics; our short solver is not its replacement. NumPy polyfit notes.
Fit on training inputs and preserve the transformation
The complete Python 3.10+ example fits one real input and one response, without weights or regularization. Its deliberate teaching limit is degree 0 through 6. That limit does not guarantee good conditioning. A small remaining QR column is rejected using the displayed code’s threshold; this is a conservative numerical screen, not an SVD condition-number estimate. The solver also rejects insufficient distinct floating-point inputs instead of silently choosing a nonunique solution.
Inputs must be lists or tuples of finite Python integers/floats; Booleans are rejected. Integer values are converted to floating point, so extremely large or indistinguishably close values can be rejected. Prediction accepts an unmodified returned model, checks new inputs and reports nonfinite scaling/results as errors. An empty prediction list is allowed. The scaled coefficients are ordered from constant term upward. For arithmetic range, the solver also temporarily divides the response by its maximum absolute value (or 1 for an all-zero response), then restores that factor in the coefficients.
from math import copysign, fsum, hypot, isfinite, sqrt
def numbers(values):
if type(values) not in (list, tuple):
raise ValueError('expected a list or tuple')
out = []
for x in values:
if type(x) not in (int, float):
raise ValueError('expected a real int or float, not Boolean')
try:
value = float(x)
except OverflowError as error:
raise ValueError('number cannot be represented as float') from error
if not isfinite(value):
raise ValueError('all values must be finite')
out.append(value)
return out
def fit(xs, ys, degree):
x, y = numbers(xs), numbers(ys)
if not x or len(x) != len(y):
raise ValueError('nonempty equally sized training arrays required')
if type(degree) is not int or not 0 <= degree <= 6:
raise ValueError('this teaching solver supports integer degrees 0 through 6')
p, n = degree + 1, len(x)
if len(set(x)) < p:
raise ValueError('need at least degree + 1 distinct floating-point inputs')
low, high = min(x), max(x)
if low == high:
center, scale = low, 1.0
else:
center = low / 2 + high / 2
scale = max(abs(t - center) for t in x)
if not isfinite(scale):
raise ValueError('input spread cannot be represented')
A = []
for t in x:
u = (t - center) / scale
row = [1.0]
for _ in range(degree):
row.append(row[-1] * u)
A.append(row)
yscale = max(abs(t) for t in y) or 1.0
b = [t / yscale for t in y]
threshold = 1e-12 * sqrt(n)
# Householder reflections: apply the same orthogonal transforms to A and y.
for j in range(p):
v = [A[i][j] for i in range(j, n)]
length = hypot(*v)
if length <= threshold:
raise ValueError('numerically unresolved column; reduce degree or revise data')
v[0] += copysign(length, v[0])
norm = hypot(*v)
v = [t / norm for t in v]
for k in range(j, p):
dot = fsum(v[r] * A[j + r][k] for r in range(len(v)))
for r, value in enumerate(v):
A[j + r][k] -= 2 * value * dot
dot = fsum(v[r] * b[j + r] for r in range(len(v)))
for r, value in enumerate(v):
b[j + r] -= 2 * value * dot
coef = [0.0] * p
for j in range(p - 1, -1, -1):
coef[j] = (b[j] - fsum(A[j][k] * coef[k] for k in range(j + 1, p))) / A[j][j]
coef = tuple(t * yscale for t in coef)
if not all(isfinite(t) for t in coef):
raise ValueError('coefficients overflowed')
return {'center': center, 'scale': scale, 'coef': coef}
def predict(model, xs):
# model must be an unmodified result of fit; coefficients use scaled u, not x.
result = []
for x in numbers(xs):
u = (x - model['center']) / model['scale']
if not isfinite(u):
raise ValueError('scaled prediction input overflowed')
value = 0.0
for coefficient in reversed(model['coef']):
value = value * u + coefficient
if not isfinite(value):
raise ValueError('prediction overflowed')
result.append(value)
return tuple(result)
def truth(x):
return 1 + 0.5 * x + 0.75 * x * x
if __name__ == '__main__':
train_x = (-2, -1, 0, 1, 2)
noise = (0.2, -0.2, 0.1, -0.15, 0.25)
train_y = tuple(truth(x) + e for x, e in zip(train_x, noise))
valid_x = (-1.5, -0.5, 0.5, 1.5)
valid_y = tuple(truth(x) for x in valid_x)
for degree in (1, 2, 4):
model = fit(train_x, train_y, degree)
train_mse = fsum((a - b) ** 2 for a, b in zip(predict(model, train_x), train_y)) / len(train_x)
valid_mse = fsum((a - b) ** 2 for a, b in zip(predict(model, valid_x), valid_y)) / len(valid_x)
print(degree, 'train/validation MSE:', round(train_mse, 6), round(valid_mse, 6),
'at x=4:', round(predict(model, (4,))[0], 6))
exact = fit(train_x, tuple(truth(x) for x in train_x), 2)
print('scaled coefficients:', tuple(round(x, 6) for x in exact['coef']))
print('held-out truth at x=4:', truth(4))
Actual output:
1 train/validation MSE: 1.92295 0.925788 at x=4: 4.6
2 train/validation MSE: 0.0172 0.00617 at x=4: 16.15
4 train/validation MSE: 0.0 0.027442 at x=4: 35.05
scaled coefficients: (1.0, 1.0, 3.0)
held-out truth at x=4: 15.0
This is a synthetic response law with a fixed, stated perturbation at five training points. The four interior validation responses come from the unperturbed law. They are useful for demonstrating the effect of fitting those perturbations; this tiny construction is not an estimate of performance on a real sensor population.
The training mean squared error drops from 1.92295 to 0.0172 and then essentially zero. The fourth-degree validation error is larger than the quadratic’s. At x = 4, outside the training interval [−2,2], the quartic predicts 35.05 while the synthetic truth is 15. The quadratic predicts 16.15. These are outcomes of this fixture, not universal guarantees about either degree.
The separate exact fit stores coefficients (1,1,3) because u = x/2: 1 + u + 3u² equals 1 + 0.5x + 0.75x². Reading those coefficients as powers of x would evaluate a different curve.
For a real model-selection workflow, choose candidate degrees in advance, fit transformations on each training fold, and use validation to select degree. Refit the chosen procedure on the permitted training data, then evaluate once on untouched test data. Our prediction function never changes c or s using validation inputs. For this unpenalized complete polynomial basis, affine scaling alone preserves the exact function space; the training-only convention also keeps regularized or feature-selected extensions from using evaluation information.
With k = d+1 and n ≥ k, building the design and computing QR use:
Here m is the number of queried inputs. These arithmetic bounds count the stored n-by-k matrix and transformed response. Prediction uses Horner evaluation, validating and retaining the queried inputs/results; the model itself stores k coefficients. An empty query still takes constant work, covered by the 1 in the time bound and k ≥ 1 in the space bound. Float conversion of very large integers has additional bit costs. No explicit inverse or normal-equation matrix is formed by the fitted implementation.
Choosing degree and checking extrapolation
With fixed data, nested unregularized polynomial spaces can only decrease the optimal training loss in exact arithmetic: the lower-degree fit remains available by setting new coefficients to zero. Validation loss need not follow that trend. Numerical rejection or roundoff can also prevent this ideal nesting property from appearing exactly in computed results.
High powers are global features. A change in one fitted coefficient affects the whole curve, and extrapolation can grow rapidly. Scaling helps the arithmetic but does not justify predictions outside the observed region. Orthogonal polynomial bases can improve conditioning; splines offer locally supported alternatives. NumPy’s documentation discusses these options and warns about poorly determined coefficients. It does not provide a universal safe degree for arbitrary data. NumPy 2.3 notes.
With r input variables, including every monomial of total degree at most d gives the following number of columns, counting the constant:
For two inputs and degree two, the columns are 1, x₁, x₂, x₁², x₁x₂ and x₂². The interaction is different from either square. Column counts can grow quickly, and an intercept should not be duplicated when the constant feature is already supplied. The multivariate transformation is described in the official documentation but is not implemented by this univariate program. scikit-learn 1.7, polynomial features.
Polynomial regression also differs from a Taylor expansion: its coefficients are fitted to observations, rather than fixed by derivatives of a known function at one point. It is a regression model, not multinomial logistic classification.
Check the basis and the evidence
-
Why is a quadratic regression called linear in its parameters? What would happen if the coefficient of x² were zero?
Answer: The prediction is a weighted sum of fixed features 1, x and x²; no unknown coefficient is squared or multiplied by another unknown coefficient. A zero quadratic coefficient leaves a line, or a constant if the linear coefficient is also zero.
-
The returned exact coefficients are (1,1,3), with center 0 and scale 2. Predict at x = 2, and explain why direct substitution into 1+x+3x² is wrong.
Answer: u = 1, so the prediction is 5. The coefficients multiply powers of u. Direct substitution into powers of x gives 15 and describes a different polynomial. In original coordinates the fitted function is 1+0.5x+0.75x².
-
Two distinct x values each have repeated noisy observations. Can they identify a unique quadratic? Does a fourth-degree fit through five distinct observations establish that degree four is the true mechanism?
Answer: Two distinct design locations cannot identify all three quadratic coefficients, regardless of repetition. Five distinct points do determine a degree-at-most-four interpolant, but that interpolant also fits their noise. Validation and domain knowledge are still needed; the executed example shows worse validation error for the interpolant.
-
There are three predictors, and every monomial through total degree two is included. How many columns are there? If the degree was chosen using the test set, would its error still be an untouched evaluation?
Answer: There are 10 columns: one constant, three linear terms, three squares and three pairwise interactions. Once test responses influence degree selection, that set has become part of model selection; a fresh independent evaluation is needed for an untouched test claim.
Separate basis design, numerical solving and model selection
The scikit-learn source used here is its versioned 1.7 documentation, rendered as 1.7.2, specifically §1.1.18. It explains polynomial feature maps and an explicit constant column. The NumPy source is the versioned 2.3 manual for numpy.polynomial.polynomial.polyfit; its coefficients are ascending powers, and its SVD-based diagnostics are different from our QR screen. No library code or example data were copied, and no dependency installation is required to run this program.
Our independent checks solve small rational normal equations with exact fractions, then compare predictions to the floating QR implementation. Exact arithmetic makes that a suitable test reference without recommending floating normal equations for numerical work. Other checks cover residual orthogonality, duplicate design locations, affine-coordinate invariance, overflow rejection and the displayed training/validation example. Together with the derivation, these checks establish the stated teaching behavior; they do not certify arbitrary high-degree data or supply uncertainty intervals.
Make a prediction, then check
Five distinct noisy training points are interpolated by a degree-four polynomial. What does zero training loss establish?
Learning objectives
- Derive polynomial least squares as a linear model in expanded features and identify when its coefficients are unique.
- Fit and evaluate a scaled univariate model with QR, preserving the training transformation and checking numerical limits.
- Compare interpolation, validation and extrapolation without equating zero training loss with a known response mechanism.
Prerequisites & connections
Explore related knowledge →References
- scikit-learn 1.7 — Polynomial regression: extending linear models with basis functions
scikit-learn developers - NumPy 2.3 — numpy.polynomial.polynomial.polyfit
NumPy developers
Version1 · Editorial status: Recorded technical checks completed
View technical check record (AI)
Codex · 2026-09-05 · Codex technical check: primary-source locations, original runnable models, independent mathematical and computational references, bilingual review and second-agent cross-checks; not independent human peer review.
- Original synthetic sensor curve with six anchors, five identical formulas, identical full Python, five actual output lines and four answers per locale. Distinguishes nonlinear inputs from linear coefficients, at-most degree, repeated design locations, interpolation/noise, and conditional-mean versus uncertainty assumptions.
- All eight tests passed. Independent exact-Fraction normal equations compare 28 predictions across degrees 0–6; residual orthogonality and nonincreasing nested training SSE are separately checked without reusing floating QR. Verified exact scaled quadratic coefficients (1,1,3), repeated observations, constants, affine coordinates, unchanged training transformations and Horner evaluation.
- Executed degrees 1/2/4 give training MSE 1.922950/0.017200/near zero and validation MSE 0.925788/0.006170/0.027442; extrapolation at four is 4.6/16.15/35.05 versus synthetic truth 15. Explicitly a fixed-perturbation illustration, not population risk or a universal higher-degree failure. Thirteen invalid-fit cases and three prediction rejections cover Booleans, nonfinite values, oversized integers, collapsed floating inputs, nearly dependent columns and overflow.
- Reread QR reflections/back-substitution, training-input and temporary response scaling, the non-SVD numerical screen and possible ill-conditioning even at degrees 0–6. Rank/orthogonality have separate derivations; costs include the stored design and empty-query constant. No production-solver or interval claim. Reread under pinned Humanizer guidance; strict MDX/KaTeX/actual React HTML show five displays, six headings and four answers each with complete cost annotations. Only /tmp and AI author checks; review written pending independent cross-review.
- An independent AI reviewer found midpoint underflow for the smallest subnormal constant input. Constant inputs now retain that center with scale 1, and a 5e-324 constant prediction regression passes. Both locales now specify the 2-norm for the squared-condition-number identity; code, prose and final hashes were refrozen.
- Read full bilingual prose, example, eight tests and final metadata. Checked Vandermonde rank/root argument, interpolation versus noisy validation, affine basis invariance only for the unpenalized full basis, thin-QR semantics, response scaling, Householder sign choice, back-substitution, degree 0–6 and prediction contracts.
- Independent 75-digit Decimal discrete orthogonal-polynomial projection, not author exact normal equations or implemented Householder reflections: 112 fits and 560 predictions across degrees 0–6, shifted/reversed input coordinates and response scales 1, 1e-300 and 1e300. All satisfy the stated 2e-9 scale-relative comparison tolerance. Direct Lagrange products independently reproduce five quartic interpolation/extrapolation probes, including 35.05 at x=4.
- After the constant-input fix, all eight author tests passed; independently rechecked the numerical reference and three constant/subnormal cases. Reviewed synthetic MSE values, training-only transformation, rank rejection and overflow limitations, parameter/feature distinction and fit/predict storage bounds. No outstanding defects found.
- Strict final MDX/KaTeX and actual React HTML passed in both languages with five displays, six anchors and four answers. Complete math annotations match, and all five final hashes match the frozen manifest. This is an AI technical review, not human review or certification of arbitrary ill-conditioned inputs.
- Promoted the full prose, equations, code and exercises. Tests read formal MDX only; removed temporary fallbacks/draft skips and updated review assertion to checked. Algorithm and independent references are unchanged; final record binds both locale hashes.
Source locations checked:
- scikit-learn 1.7 — Polynomial regression: extending linear models with basis functions · Actually opened official versioned HTML through web. Page header identifies scikit-learn 1.7.2 under the /1.7/ path. Read section 1.1.18, lines 901–945: basis expansion, two-input quadratic terms, linearity in weights, PolynomialFeatures including a constant and LinearRegression(fit_intercept=False) in the pipeline. Read 946–955 to distinguish the source example and interaction-only setting; neither code nor data reused. Also read ordinary least squares lines 78–106 for the objective/rank sensitivity and solver context. No download, source-code review or execution of scikit-learn is claimed.
- NumPy 2.3 — numpy.polynomial.polynomial.polyfit · Actually opened official NumPy v2.3 polyfit manual through web. Read lines 90–149 for coefficient order, shape, rcond, scaled-Vandermonde rank/SVD diagnostics and RankWarning; lines 186–197 for weighted least-squares objective, SVD solving, poor determination, roundoff, and Chebyshev/Legendre/spline alternatives. The document’s heuristic degree-20 statement is deliberately not treated as a universal boundary. No NumPy source copied, downloaded or executed; the original standard-library program uses bounded-degree Householder QR instead.
- scikit-learn 1.7 — Polynomial regression: extending linear models with basis functions · Actually opened official /1.7/ documentation, header identifies 1.7.2. Read section 1.1.18 lines 901–955: nonlinear feature maps remain linear in coefficients, two-input squares and interaction, explicit constant column and fit_intercept=False pipeline. Also read OLS objective and rank sensitivity. No library source or execution audited.
- NumPy 2.3 — numpy.polynomial.polynomial.polyfit · Actually opened official 2.3 polyfit manual. Read coefficient order, shapes and diagnostics at lines 90–149; Notes 186–197 give weighted Vandermonde least squares solved using SVD, poorly determined coefficients, roundoff and alternative bases/splines. Verified the chapter neither calls its QR threshold SVD diagnostics nor adopts the heuristic degree statement as a universal guarantee.
Related topics