In a normal linear model with an intercept, observations and independent mean coefficients, adjusted is
It compares the residual variance estimate with the unmodelled sample variance, adjusting the raw coefficient of determination for fitted dimension. It can be negative and is not guaranteed to increase when another regressor is added. In penalized regression a related convention uses the fit's effective degrees of freedom instead of ; the precise smoothing-software variance convention should be specified.
With fixed covariates and independent new responses having the same marginal distributions as the training responses, expanding squared losses cancels their second moments. Independence makes , yielding the displayed identity. For a fixed linear smoother with covariance , it reduces to , linking prediction optimism to effective degrees of freedom.
// Target: analysis.bigb
Fitted values Created 2026-09-24 Updated 2026-10-14
Fitted values are the predictions at the predictor values used to fit a regression model. In linear regression with an explicit regression intercept,
Here is the slope design matrix, and is the regression residual vector. The fitted values estimate the regression function at the observed predictors; they need not equal the observed responses, which may also contain random errors. Prediction at a new predictor vector uses with the same centering and scaling used in fitting. A prediction interval addresses uncertainty in a new response rather than just displaying this point prediction.
For the five constructed observations in linear regression, ordinary least squares gives fitted values . The ridge regression fit at instead gives . Both fitted vectors have sample mean because the regression intercept is unpenalized; their regression residuals differ and their residual sums of squares are and , respectively.
For ordinary least squares, the fitted values are the orthogonal projection of onto the column space of the complete design matrix, including its regression intercept column. They remain unique even in rank-deficient ordinary least squares, although the regression coefficients can be nonunique. The regression residuals are then orthogonal to every column.[ref] With centered slopes, ridge regression instead satisfies , so the regression residuals need not be orthogonal to the slope columns. Their sum is still zero because the regression intercept remains free.
For fixed predictors and scales and a fixed positive penalty, ridge regression gives a linear smoother,
For with at least one nonzero slope direction, this matrix is not an orthogonal projection matrix: applying it twice shrinks that direction again. Its effective degrees of freedom are , where are the positive singular values of ; the extra counts the free regression intercept. If the penalty is selected using , the resulting fitting rule need not be a linear smoother, since its chosen also depends on .
Let be the influence matrix, so . Its trace is the effective degrees of freedom, accounting for shrinkage of the fitted smooth rather than just counting basis coefficients. The generalised cross-validation score is
For a fixed smoothing parameter, the exact leave-one-out residual of this penalized linear fit is , obtained by removing its observation's contribution to the normal equations. Thus Leave-one-out cross-validation uses the average of their squared values. GCV replaces the individual leverages by their average . This avoids separate refits and gives a criterion balancing the small training residuals of a flexible fit against its larger complexity.
Evaluate the score across positive , or optimize it numerically, and choose minimizing GCV. Then refit or retain the spline at this value. In the full natural smoothing-spline family the trace decreases from towards as smoothing increases. The selected parameter is intended to give good prediction, rather than necessarily to pass through every point.
library(mgcv) loads the fitting package; gam fits a Gaussian generalised additive model with the printed identity link. The smooth specification s(x, bs="cr") uses a penalized cubic regression spline. This is a finite-dimensional smooth basis, rather than a full interpolating spline with a free value at all observations. The fitted model is
Here in the centred cubic regression-spline basis, with its curvature penalized through . The intercept is estimated separately. In the displayed fit the smooth test space has rank , consistent with nine smooth coefficients after the centring constraint, while penalization lowers its effective dimension.
The intercept estimate is , with standard error , and . Because the smooth is centred over the observations, the intercept is the overall fitted average, not necessarily the fitted response at . Its test compares this average with zero. The significance-code legend maps progressively smaller -values to stars; stars are an annotation, not an effect-size measure.
The smooth has effective degrees of freedom, displaying substantial nonlinearity: a centred purely linear term would use one. Est.rank=9 reports the rank used for its approximate significance calculation. The -value below is very strong evidence that the mean depends on , against a zero smooth term. It does not mean the fitted curve is the exact generating function, or that lack of fit has been tested. The total effective dimension including the intercept is .
The adjusted coefficient of determination of and deviance explained of indicate that nearly all variation about the response mean is explained. For this Gaussian model, deviance explained is . The scale estimate estimates residual variance, corresponding to a residual standard deviation about . The GCV score is the prediction-oriented criterion used for smoothing selection, not a probability. It is consistent with the reported scale and effective dimension: .
In the PDF's plot, the solid curve is the estimated centred smooth , and the dashed curves show pointwise uncertainty around that smooth, rather than prediction intervals for new noisy responses. The label s(x,8.24) gives its rounded effective degrees of freedom. The rug marks the observed covariate locations. Reading the endpoints gives
The smooth is increasing with an almost flat middle and one inflection, resembling a cubic. A simpler model to investigate is ordinary Gaussian polynomial regression
It uses four mean coefficients rather than about nine effective ones. The apparent near-odd shape also makes a plausible further reduction, but the linear and quadratic terms should be checked rather than discarded solely from the picture. The figure suggests this alternative; it does not supply coefficients or establish the true simulation model.
Condition on the training covariates, and let . The fresh response has the same marginal distribution as and is independent of the complete training response vector, hence independent of . Assume the relevant second moments are finite. Expanding the squared errors gives
The first expectation averages over both training and new responses; the second averages over training responses only. Subtracting cancels both second-moment terms, leaving
Averaging over the design points proves the covariance formula for prediction optimism:
No linear fitting rule or Gaussian noise assumption is needed. The difference arises because a training response and its fitted value are dependent, whereas a fresh response and the fitted value are independent. Ordinary fitting often makes those covariances positive and the training error too favorable, explaining the name prediction optimism.
For example, if is a fixed linear smoother and , then . Thus
This links the optimism correction to effective degrees of freedom. For a data-selected fitting operator, its realized trace alone does not generally give the covariance penalty, since selecting the model uses the responses too.
An orthonormal multiresolution analysis is a sequence of closed subspaces satisfying , , , and iff . A scaling function has integer translates forming an orthonormal basis of , and its scaled translates span . Thus contains information at resolution about .
The detail space is generated by the corresponding wavelet functions . The orthogonal splitting iterates to
Accordingly a square-integrable signal has a coarse-and-detail wavelet series,
and its wavelet projection onto keeps the coarse coefficients and details below level . Increasing adds finer-scale oscillations and localized features. On the real line there are infinitely many translates at each level; for a bounded observation interval, with an appropriate interval or periodic construction, the relevant approximation dimension satisfies . For the Haar wavelet on a unit interval this is exactly , corresponding to a separate mean on each dyadic subinterval.
This hierarchy gives a concrete meaning to wavelet approximation complexity. Coarse resolution uses few coefficients and can miss sharp features; fine resolution uses more coefficients and can fit noise. By orthogonality, projection bias is the energy of the omitted details,
For an orthonormal sequence model with independent coefficient noise of variance , estimating the retained coefficients without shrinkage gives
The first term decreases with resolution while the second increases, making the bias-variance tradeoff explicit. Equivalently, a fixed orthogonal regression projection of rank has effective degrees of freedom and prediction optimism under independent equal-variance errors.
Wavelets also permit local rather than only global complexity control. Thresholding small estimated detail coefficients, for example by soft thresholding, retains strong local structure while suppressing fine-scale noise elsewhere. A sparse retained coefficient set can represent localized features much more economically than keeping every coefficient through a high level. Its locations and scales matter as well as its count. If that set is selected using the same noisy responses, however, selection adds adaptivity: its raw coefficient count is not automatically its covariance-based degrees of freedom. Resolution or threshold tuning should therefore account for prediction error, using an appropriate risk estimate or cross-validation, rather than only decreasing training error.
Wavelet complexity is controlled by retained resolutions and coefficients; more detail reduces approximation bias while increasing estimation variance and sensitivity to noise.
The trace of the smoother's influence matrix is its total effective degrees of freedom. Include the unpenalized intercept as well as both centered smooth terms:
The Ref.df entries are for approximate significance calibration and must not be summed to obtain this trace. A consistency check using the generalized cross-validation form and scale estimate gives ; the small difference is explained by rounding in the displayed quantities. The required trace is about .
The original PDF's age smooth is nearly flat, its uncertainty band includes zero across the age range, and its approximate p-value is . The exposure smooth is increasing and convex: it is fairly flat at low exposure and rises more steeply at high exposure. Its effective degrees of freedom suggest a modest departure from a straight line, rather than a highly oscillatory relationship.
A suitable simpler model is therefore the grouped quasibinomial regression
with age omitted and dispersion estimated. A positive quadratic coefficient captures the convex exposure relationship; retaining the linear term respects the usual polynomial hierarchy. This model should be refitted, rather than assigning coefficients from the smooth plot. Compare its residual pattern and dispersion-adjusted fit with the additive model to check that the quadratic approximation is adequate. An exposure-only quadratic logit model is a justified parsimonious candidate, while the graph does not justify a sharp threshold or a zero-dispersion model.
The proposed generalized additive model retains the binary response and logit link, but replaces the linear age effect by a smooth function:
A penalized cubic regression spline represents ; frailty remains a parametric coefficient. The plotted age smooth is centered, so its vertical values represent an age contribution to log odds, not probabilities or the entire fitted predictor.
The plot gives no evidence that the nonlinear model improves the mean structure. The fitted curve is essentially a straight descending line, and the label s(age,1) reports effective degrees of freedom close to one, consistent with a linear effect. The widening bands near the ends reflect sparse data and increasing uncertainty, not detected curvature. A linear-age logistic regression is therefore adequate on this evidence and simpler to interpret. A formal comparative claim would need a suitable test or predictive/model-selection criterion, but the figure supplies no reason to retain extra nonlinear flexibility.
Assume initially that the design points are distinct and ordered on . The cubic smoothing spline minimizes
over functions with an absolutely continuous first derivative and square-integrable second derivative. Dividing the residual term by simply changes the scaling assigned to . The minimum roughness property of the natural cubic spline interpolant reduces the problem to natural cubic splines with knots at the design points: among functions with any prescribed fitted values, that interpolant has the smallest integrated squared curvature. The minimizer is therefore a natural cubic smoothing spline, with natural second-derivative boundary conditions and linear tails when extended.
Choose a full basis for this natural-spline space. Put and . Writing changes the objective to
Differentiation gives . Although the curvature penalty has an affine nullspace, the full basis at distinct design points makes the combined matrix positive definite. Hence
Equivalently, use the cardinal basis that interpolates the observations, making and . These are smoothing matrices, symmetric but generally not idempotent. Their effective degrees of freedom are . As the fit interpolates; as it approaches ordinary least squares on the affine functions. With replicated predictors, use a design matrix for distinct knots and observation weights; the basis form remains valid when identifiable.
Useful choices include Leave-one-out cross-validation, generalized cross-validation, and estimation of smoothness by restricted maximum likelihood through a mixed-model representation. For fixed , the leave-one-out residual identity for a linear smoother gives
Minimize these over a suitable range. Choose smoothing by predictive performance or a variance-component likelihood, not by arbitrarily forcing a visually appealing curve.
The null model's 99 residual degrees of freedom imply . Each predictor has a one-degree-of-freedom linear contribution in the parametric table, plus the reported nonlinear contribution. Consequently the termwise effective degrees of freedom are
Include the intercept once, giving about total effective degrees of freedom. The more precise residual degrees of freedom in the output give
There is no conflict: and are rounded, so they cannot recover the precise total. Individual unrounded termwise values are not provided.
The package's residual mean-square estimate of error variance is
matching the rounded in the table. The nonlinear experience contribution is highly significant, while the smaller nonlinear education contribution has approximate .
This calculation uses the effective residual degrees of freedom reported by this fit. For a general non-idempotent linear smoother , the noise contribution to expected RSS is , and the expectation can additionally contain squared smoothing bias. Thus dividing by is not a universal exact-unbiasedness theorem. The output's separation of linear and nonlinear term degrees of freedom is documented at cran.r-project.org/web/packages/gam/gam.pdf.
The generalized additive mixed model fits
where denotes the furnace random intercept and is a centered penalized cubic regression spline. Its wiggly components have a mixed-model representation; there is no explicit furnace-specific random slope in this formula.
The plotted smooth gives no evidence that a nonparametric fixed effect is needed. It is essentially a straight rising line, and s(stir,1) indicates effective degrees of freedom close to one. The wider bands at extreme stirring rates reflect uncertainty, not detected nonlinearity. A linear fixed stirring effect is adequate on this evidence.
If the three supplied Akaike information criterion values are on a common valid likelihood basis, choose strength_model3, the fixed linear slope plus random-intercept model: its AIC is smallest, versus for the additional random slope and for the smooth. The differences are and , respectively, so especially the random-slope comparison represents modest support rather than decisive evidence. Retaining the population slope is consistent with part (c); this choice removes only its random variation.
There is a likelihood-basis caveat in the literal printed commands. lmer fits by REML by default, whereas the Gaussian gamm call defaults to ML; direct AIC on these objects need not compare the same type of likelihood. Moreover the earlier ML ANOVA prints for strength_model, whereas this table prints , so these numbers should not silently be treated as one identical ML fit. To obtain a defensible common comparison, fit all candidates to the same observations by ML:
fit_slope <- update(strength_model, REML = FALSE)
fit_intercept <- update(strength_model3, REML = FALSE)
fit_smooth <- mgcv::gamm(strength ~ s(stir, bs = "cr"),
random = list(furnace = ~ 1), method = "ML")
AIC(fit_slope, fit_intercept, fit_smooth$lme)
The supplied ranking favours the simpler random-intercept model; the displayed original calls alone do not certify that ranking as a consistent ML comparison. This distinction is particularly relevant when the smooth changes the fixed-effect space. The Gaussian gamm ML default and mixed-model representation are documented at stat.ethz.ch/R-manual/R-devel/library/mgcv/html/gamm.html.
For , minimize the smoothing spline objective over the Sobolev space of functions with square-integrable second derivative on the observed interval:
The roughness penalty measures curvature; its null space consists of affine functions. To see why the minimizer is a natural cubic spline, let be the natural spline interpolating the values of any competitor at its distinct observation locations, and put . Integration by parts twice on each knot interval gives : on each interval, vanishes at the knots, is continuous, and vanishes at the outer endpoints. Hence
while both functions have the same residual sum of squares. This proves the reduction to a finite-dimensional spline space.
For distinct and , use its -dimensional basis, write , and define the positive semidefinite matrix
The penalized least squares problem is , so
Use linear continuation outside the observation interval. The fitted-value matrix is ; its trace gives the effective degrees of freedom. As decreases to zero, the natural spline approaches interpolation, with trace ; as it grows without bound, the fit approaches ordinary least squares on , with trace two. For the criterion alone does not determine values between observations; the natural interpolant is the limiting convention. Repeated observation locations are combined by using distinct knots and their multiplicities as weights, rather than pretending the spline design has independent interpolation values.
Because no family is specified, the command fits a Gaussian identity-link generalized additive model:
The are centered penalized regression splines with cubic regression bases; centering separates them from the intercept. The age curve in the original figure falls to a minimum near age 25, then rises markedly, particularly from about 40 onwards. Its effective degrees of freedom are , reflecting curvature. The white-cell curve has effective degrees of freedom one and is nearly flat with a slight positive slope; the pointwise uncertainty bands are consistent with no substantial effect. These plots display centered partial mean contributions, not numbers of prescriptions by themselves.
A simpler mean model keeps the age regression spline and replaces the white-cell smooth by a linear term. A separate issue is that the response is a nonnegative count: a Poisson regression with logarithmic link function respects that support and positivity of the mean. A reasonable candidate is
model1p <- gam(npres ~ s(age, bs="cr") + wbc, family=poisson(link="log"))
gam.check(model1p)
If diagnostics show overdispersion, one can fit
model1nb <- gam(npres ~ s(age, bs="cr") + wbc, family=nb(link="log"))
using a negative binomial regression. Alternatively, if a Gaussian approximation is adequate, the minimal simplification is gam(npres ~ s(age, bs="cr") + wbc). These are candidates to compare by diagnostics and validation, rather than guaranteed improvements from the partial plots alone. Retain the curved age effect; consider a linear or removable white-cell effect, and assess an appropriate count family. Refit before interpreting the old curves on a new link scale.
The command fits a Gaussian generalized additive mixed model
The population growth curve is a centered penalized regression spline with a cubic regression basis. The incubator term remains a random slope without a random intercept, because ~0+hours removes the intercept. A population linear component is allowed within the smooth's unpenalized part; curvature is penalized rather than being required.
A gamm fit returns a list with gam and lme components. Plot the population smooth and pointwise uncertainty bands with
plot(fly.model2$gam, se=TRUE, residuals=TRUE)
Inspect whether the fitted curve departs materially from an affine function, particularly in regions supported by observations. The effective degrees of freedom near one suggest that the penalization has selected an approximately linear centered smooth. Bands and partial residuals help distinguish convincing curvature from noisy deviations, although pointwise bands are not a simultaneous test of linearity. A formal comparison would need to account for both smoothing selection and the incubator dependence. The smooth plot tests the visual plausibility of a common straight growth curve while retaining incubator-specific slope variation.
Put , so and with independent noise vectors having covariance matrix . For any deterministic linear smoother ,
whereas independence gives
Expanding the first trace shows that the second expression exceeds the first by , proving the identity.
For ridge regression,
Its effective degrees of freedom are . Thus training error is optimistically biased for independent-copy prediction error by . The graph exhibits exactly this effect: the dashed training curve keeps falling as decreases, while the solid test curve eventually rises through overfitting.
Penalized least squares Created 2026-10-05 Updated 2026-10-14
For , a full-column-rank design matrix , and a positive semidefinite matrix , minimize . Differentiation gives . The fitted-value matrix is , whose trace measures the effective degrees of freedom.