Follow the regression pipeline from raw observations to a fitted model, validation, and a prediction in the original units. Work through each calculation before using code to check it.
1. Identify the inputs, unknowns, and outputs
An observation is one recorded case. Let be the number of observations and the number of original features. The th feature of observation is ; its observed response is . Subscripts are labels, not multiplication. Our final task is to return a prediction for a new input, not merely an error score.
An ordinary affine model is . The intercept is the prediction when all features are zero. Holding the other features fixed, increasing feature by one unit changes the prediction by . If several inputs change together, one coefficient alone does not describe the total change.
The design matrix has one observation per row and one model term per column. Its columns match the order of the coefficients in . For , a row is and . For , a row is . Thus is , is , and is . Only an ordinary affine model with an intercept and all original features has . A quadratic in one original feature already has three design columns.
The residual is : observation minus prediction. . Squaring prevents positive and negative residuals from cancelling and penalizes large residuals more heavily. An argmin returns minimizing parameters; it does not return the minimum loss value.
2. Fit once, without hiding the elimination
Use . For , has rows and .
.
Differentiating with respect to and setting the result to zero gives , or . Differentiating with respect to gives , or .
Subtract the first equation from the second: , so . Substitution gives , hence . The fitted model is .
Its training predictions are . Residuals are , so . Check their sum: . Check their inner product with : . These are residual orthogonality to the intercept column and feature column, respectively.
is just a compact form of the same equations. Write only when has full column rank. For a counterexample, two identical columns allow different coefficient pairs with the same sum, hence the same prediction. The parameters need not be unique. QR or SVD can solve least squares without explicitly forming an inverse.
3. LOOCV: remove the observation before fitting again
Compare a constant model with an affine model . Fitting on all observations and then scoring each one in turn computes training error, not leave-one-out cross-validation.
LOOCV takes development data, candidate specifications, and a scoring loss. Here each fold holds out one observation and fits on the other two. Average the three held-out squared errors; smaller is better. A held-out response is available for scoring, not for fitting that fold.
Why is the constant prediction the training mean? With training responses, minimize their squared deviations from one real constant . Differentiate the sum, set the derivative to zero, and divide by the positive count . The second derivative is positive, so this is the unique minimum, not merely a stationary point. The mean is computed anew from each fold’s training responses, never from its held-out response.
Fold 1: hold out (0,1)
The training points are . The constant least-squares prediction is their response mean, . At its squared error is .
The line has slope . From , the intercept is zero. The fold's line is ; it predicts 0 at , giving squared error 1.
Fold 2: hold out (1,2)
The training points are . The constant prediction is , giving . The line has slope and intercept 1. At it also predicts , with squared error .
Fold 3: hold out (2,4)
The training points are . Their constant prediction is , with squared error . Their line is . It predicts 3 at , with squared error 1.
| Held-out | Constant prediction | Constant squared error | Line prediction | Line squared error |
|---|---|---|---|---|
| 0 | 3 | 4 | 0 | 1 |
| 1 | 5/2 | 1/4 | 5/2 | 1/4 |
| 2 | 3/2 | 25/4 | 3 | 1 |
Constant . Line . Select the affine model specification, not a winning fold's coefficients.
Now refit on all three development observations, obtaining as above. Do not arbitrarily deploy , , or . For new input , the refitted prediction is . This is not a known true response. Without its observed , no prediction error can be computed at that point.
If a final test set exists, keep it outside model selection, feature selection, and tuning. A test score repeatedly consulted to revise a model is not an independent final evaluation. In this three-point example there is no separate test set; LOOCV must not be relabelled as an independent final-test result.
Concept lensAlgebraic
Leave-one-out errors from a single fit
For ordinary least squares with a fixed design, the three refits above can be read off one full-data fit. Let be the hat matrix, so the training predictions are , and suppose its diagonal entries satisfy . A rank-one update of (the Sherman–Morrison formula) shows that the held-out residual of observation equals , where is its full-fit residual. For the affine model, gives ; the residuals become , whose squares are the line column of the table. For the constant model every , and the residuals from the mean become , with squares . The shortcut is a property of least squares on a fixed design; it does not apply when a fold learns its own preprocessing or penalty in a way that changes the fitted map.
4. Scores, fold sizes, and leakage
The training response mean is . . The refitted training is . This high training score is not the same quantity as the LOOCV score 0.75: one is a dimensionless comparison to the training-mean baseline, the other an average held-out squared prediction error.
For evaluated observations, , , and . RMSE has the units of . Here training and . A single held-out observation has , so ordinary is undefined for that fold; do not average such foldwise values. Test may be negative: true values with predictions give , , .
For unequal fold sizes, a per-observation MSE pools squared errors before dividing by the total number of evaluated observations. A one-point fold with MSE 9 and a three-point fold with MSE 1 give , not . Equal-fold and equal-observation weighting answer different questions.
Every learned preprocessing step belongs inside training. In each fold, estimate means, standard deviations, missing-value rules, and feature selection from the training partition alone, then apply those fixed rules to validation. Only the final refit re-estimates them from all development data. Computing a mean on the full dataset before splitting lets held-out observations influence the fitted coordinate system: leakage can occur without directly using their responses.
Why a k-fold training partition has n(k−1)/k observations
Here counts development observations and counts folds, not features or parameters. Divide the observations into disjoint, approximately equal validation groups. In one round exactly one group is held out; its complement is the training partition. If is divisible by , the held-out group has observations, so subtract this count from . For and , hold out 20 and train on 80 in each round; run all five rounds so each observation is validated once. For and , a balanced partition has group sizes 21,21,21,20,20, hence the training sizes are 82,82,82,83,83. The expression is then an average or approximation, not a possible fractional sample count. LOOCV is the special case and trains on observations per round.
Monte Carlo validation: repeated random splits, not input sensitivity
Choose the candidate models or values, a loss, a training/validation ratio, and a number of repetitions before examining outcomes. For each repetition draw a fresh random split of the development observations, for example 80 training and 20 validation observations from . Different repetitions may reuse observations, so these are not disjoint k-fold groups. Use the same split for all candidates in a repetition to make their comparison fair. This simple random-split procedure assumes exchangeable observations; time-ordered or grouped observations require an appropriate time/group-respecting split.
Within each repetition: (1) estimate means, scales and any other learned preprocessing only on its 80 training observations; (2) freeze and apply those rules to both partitions; (3) fit each candidate using those 80 training observations; (4) predict the 20 validation responses and calculate the stated validation loss. Store a loss for every candidate on every split. Average each candidate’s validation losses over repetitions, then select the candidate with the smaller average. Do not select the single luckiest split or take its fitted coefficients as the final model.
For a small bookkeeping example, suppose the validation MSEs for are 4,9,5 over three repetitions and those for are 6,5,4. The averages are 6 and 5, so select , even though achieved 4 on the first split. These are illustrative recorded losses, not newly claimed empirical results. After selection, re-estimate preprocessing and refit the model on all 100 development observations. Evaluate a separate final test set only after the choices are fixed; its observations and responses must not participate in split selection, choice or preprocessing estimates.
Monte Carlo validation resamples training/validation partitions and studies out-of-sample loss for model selection. Monte Carlo input sensitivity instead perturbs an input or uncertain quantity and propagates that perturbation through a model. Section 8 illustrates input sensitivity with fixed perturbations. They ask different questions. A lower LOOCV or repeated-split score means better performance in this specified comparison on these observed data; it does not guarantee the genuinely best population model, the best untested candidate, or the smallest future error. Reusing the same validation evidence to make many choices can itself overfit that evidence.
5. Undo standardization: restore the response first
Let , where and nonzero are training-feature statistics. If and the fitted model is , first restore the response: .
Substitution gives . Separate variable terms from constants: and . If was not transformed, use ; do not introduce a response standard deviation that was never used.
Example: . Then and . The restored model is . At it gives 20. Alternatively , then . Agreement checks the entire restoration.
The incorrect intercept 10 would predict 40 at : it fails to subtract the 20 contributed by input centering. A zero-variance feature has and cannot be divided by its standard deviation; remove the redundant constant feature or specify a constant-column rule. Standardization is not unit-norm scaling: under the population-variance convention, standardized values have squared sum , not 1.
6. Ridge: write the full objective before differentiating
Specify , , with diagonal penalty matrix . Penalizing every coefficient means . Leaving the first coefficient, an intercept, unpenalized means . is not implicitly 1, and missing original matrices do not justify invented numerical answers.
The gradient is . Setting it to zero gives . An inverse formula requires invertibility. For and positive-semidefinite , the quadratic form is . Uniqueness holds exactly when and intersect only at zero. Full penalization ensures this; unpenalized directions must still be identified by the data.
A fully specified fresh example uses , model , and objective , with no intercept penalty. The design columns are orthogonal: . Thus and , yielding . Predictions are , , penalty , total objective 1. OLS gives and RSS 0, but its value under the same ridge objective is 2. Ridge sacrifices fit to reduce its penalty; this is not a calculation error.
If the intercept is also penalized, the first equation becomes and : a different problem. For , multiply the whole objective by to get . Matching parameter names or numerical values does not establish matching penalty strength. With orthogonal columns of squared norms , the coordinate shrinkage factor is . It is a common factor only when those norms agree; correlated columns cannot use the formula coordinate by coordinate.
Counterexample mode
An unpenalized redundant column breaks ridge uniqueness
Keep , and , but add a constant feature alongside the intercept, so the model is with , and penalize only the slope: . Then lies in both and . The objective depends on and only through , and every vector , , attains the minimum value found above; the matrix is singular. Penalizing the redundant column as well, , gives objective along this family, so the unique minimizer is . A positive guarantees uniqueness only in the directions it actually penalizes.
General Tikhonov: the operator is not the quadratic weight
Ridge is a special case of Tikhonov regularization. The coefficient vector is called below; it has the same role as above. The operator first transforms the coefficients, and the squared length is taken afterwards. may be rectangular. Read the objective before deciding what to add to the normal matrix:
The transpose appears because a squared Euclidean length is a vector multiplied by its transpose. There are two copies of , not one. The quadratic-weight notation used above is also correct, but its already contains this product. If a problem calls its quadratic weight instead, follow its definition rather than the letter. These three conventions describe the same objective only with the indicated identifications:
For an unpenalized first-coordinate intercept, choose a zero first column in ; a diagonal choice is . That particular diagonal matrix satisfies because and . This shortcut fails for general diagonal entries:
Here happens to equal , but not . If the objective were instead with the very same numerical matrix , the weight would be rather than . It would be a different optimization problem. To produce a quadratic weight through a squared norm, use an operator .
Calculate a non-indicator penalty all the way to prediction
Reuse the three observations above, but replace the indicator operator by , keeping . The penalty is now , not and not . Compute the design products, add the penalty matrix, and solve:
Check the result in the original objective, including the factor inside the norm. The predicted response at a new input is . The much smaller slope is explained by the stronger penalty; it is not inconsistent with the earlier slope , which solved .
For , the solution is unique precisely when . If that condition fails, the normal equations still characterize minimizers, but an ordinary inverse is unavailable. When , this becomes ordinary least squares and uniqueness instead requires full column rank of . When is given, use it; when it is to be selected, compare candidates by validation and refit as in Sections 3–4. If neither a value nor a selection rule is supplied, report a formula in rather than choosing 1.
7. Lasso: do not omit zero
Consider . For , the derivative is and its candidate is , positive only for . For , the derivative is , giving , which contradicts . Thus no negative interior candidate is valid.
For , the ordinary derivative at zero does not exist. When the penalty vanishes and the minimizer is . The left derivative is ; the right derivative is exactly when . The complete solution is . Values give 3,2,0,0; include the boundary 6 in the zero branch. Convexity makes these conditions globally sufficient.
By contrast, ridge has solution , nonzero for every finite in this example. Lasso reaches exact zero. This does not mean every ridge coefficient in every dataset is necessarily nonzero.
If the objective becomes , the positive candidate is and the zero threshold is 3. Only the squared-loss factor changed, not the entire objective, so the minimizer changes. More generally, for a nonzero column and target residual , minimizing gives , where and . With nonorthogonal design columns, this is a coordinate subproblem, not permission to independently threshold all original correlations and call the result a global solution.
8. Sensitivity: state what changes and what stays fixed
Fix and change only a new input. The exact change is . Moving from 3 to 3.1 changes the prediction from to , an increase 0.15. No refitting occurs.
Now instead change the third training response from 4 to and refit with the same design. The input mean remains 1. The slope numerator increases by while its denominator is 2, giving . The response mean increases by ; therefore . The new prediction at is . A training-response change can produce a larger prediction change, especially in extrapolation. The old slope 1.5 does not describe this experiment.
Near-collinear features can make coefficients sensitive to small perturbations even when training predictions are relatively stable. Ridge often stabilizes penalized directions but does not guarantee lower test error. A sensitivity report must specify the perturbed quantity, its magnitude, whether fitting is repeated, and whether coefficients or predictions are measured.
Putting the regression decisions back together
The output of regression is a rule for predicting a response from new inputs. The coefficients, together with the feature and preprocessing definitions, specify that rule; training RSS is how one fitting objective is measured; a validation score helps choose the rule. These are three different outputs of three different stages.
| Stage | Decision or calculation | What passes to the next stage |
|---|---|---|
| Define | Specify response, features, candidate models and loss convention | A reproducible training procedure |
| Fit inside each fold | Learn preprocessing and coefficients on the training part only | Predictions on that fold's held-out observations |
| Compare | Pool held-out errors for each model and penalty value | One chosen model specification and penalty |
| Refit | Relearn preprocessing and coefficients using all development observations | One final fitted rule, including preprocessing |
| Use and evaluate | Apply the saved rule to new inputs; evaluate on an untouched test set if available | Predictions in original units and an honest performance estimate |
OLS, Ridge and Lasso share this pipeline. OLS minimizes the squared residual loss; Ridge adds a quadratic penalty; Lasso adds an absolute-value penalty. Fix the loss normalization and whether the intercept is penalized before comparing numerical values of the penalty parameter. Choose both the model family and its penalty by the same held-out procedure, rather than picking the smallest training RSS. Once a test set is used to tune those choices, it no longer supplies an untouched final check.
Finish the running example, rather than stopping at cross-validation
For the three observations in sections 2–3, constant and affine models have LOOCV MSEs and . The affine model wins this comparison. Its full-data refit is , so a new observation with receives prediction . This is not the average of the three fold models and not the fitted line from the last fold. The three training observations are a small calculation example, not a guarantee of accuracy on a new population.
The slope says that this fitted prediction increases by response units per input unit. It does not, by itself, establish that changing the input causes that response change. The value is a model-selection score; it is not a prediction, coefficient, or independent test-set result. For a Ridge or Lasso candidate, the same sequence applies, with its penalty chosen during validation and retained during the final refit.
If dimension reduction comes before prediction
A longer pipeline can be preprocessing → PCA → regression → prediction. Fit preprocessing and PCA separately inside each training fold, then transform held-out inputs using those fitted quantities; select the number of components along with the regression settings. For the final refit, relearn the selected pipeline on all development data. PCA is unsupervised, but fitting it using held-out inputs still leaks information about their distribution. A high-variance component can also be irrelevant to the response, so reconstruction quality alone cannot decide which predictive pipeline wins.
Return to the course problem map to distinguish prediction, representation and grouping, or compare PCA and MDS before choosing a representation.
9. Check your understanding
Quick check
(Predict at using both the standardized and restored models in Section 5.)
Solution · Solution 1
At in Section 5, . The restored formula also gives .
Quick check
(Minimize and compare its value with the zero candidate.)
Solution · Solution 2
For , the threshold is 2 and . Its objective is , below the zero candidate's 9.
Quick check
(What happens to the Section 6 ridge fit when ? What does this establish about future prediction?)
Solution · Solution 3
Setting in Section 6 gives , predictions , RSS 0. Perfect training fit alone does not establish error-free prediction on unknown data.
Quick check
(Compare changing a new input from 3 to 2.8 with lowering the third training response by 0.2 and refitting.)
Solution · Solution 4
With the final fixed model, changing a new input from 3 to 2.8 gives . Changing the third training response by and refitting instead changes the prediction at by . These are different questions.
fx-50FH II: check arithmetic without skipping the mathematics
Use ordinary scalar arithmetic on the fx-50FH II here: write the full expression before executing it. For constant LOOCV, enter (4+1/4+25/4)/3 and expect 3.5. For line LOOCV, enter (1+1/4+1)/3 and expect 0.75. For the final prediction, enter 5/6+(3/2)*3 and expect (approximately 5.333333333). For training , enter 1-(1/6)/(14/3) and expect (approximately 0.9642857143). Here * means multiplication; keep complete denominator brackets.
Obtaining 0.75 does not establish that each fold used only its two training observations. A calculator cannot detect leakage. Derive the coefficients and residuals on paper, then use scalar arithmetic for checking. Ordinary single-feature REG output is not automatically a ridge, lasso, or multivariable-regression solution. These checks require neither CAS nor full matrix functionality.