Tutorials › Exam SRM - Statistics for Risk Modeling › Worked KNN Regression Cases with Scaling and Tuning

Exam SRM · Nearest-Neighbor Learning · Tutorial 814 of 926

Worked KNN Regression Cases with Scaling and Tuning

Learn to scale predictors consistently, calculate KNN regression predictions, and tune the number of neighbors using validation mean squared error.

Intermediate 10 min read

What You'll Learn

  • Scale predictors using training-set ranges or means and standard deviations.
  • Apply the same scaling constants to new observations.
  • Identify the nearest neighbors using Euclidean distance.
  • Calculate and compare unweighted and inverse-distance weighted predictions.
  • Choose the number of neighbors by minimizing validation mean squared error.
  • Avoid raw-unit distance and validation-selection errors.

Applying KNN Regression

In \(k\)-nearest-neighbor (KNN) regression, a prediction is formed from the observed responses of the training observations closest to a new predictor vector. The method is local: changing the predictors, the distance scale, or the number of neighbors can change which responses contribute to a prediction. In applied problems, the arithmetic is usually manageable; the important decisions are to scale sensibly, use the specified neighbor rule, and tune \(k\) using validation data rather than the training fit.

Definition: Suppose the training data consist of \(n\) labeled observations \((\mathbf{x}_i,y_i)\), where \(\mathbf{x}_i\) is a predictor vector and \(y_i\) is a numeric response. For a query vector \(\mathbf{x}_0\), the \(k\) nearest neighbors are the \(k\) training observations with the smallest distances to \(\mathbf{x}_0\), under a specified distance measure. The unweighted KNN regression prediction is the average of their responses.

KNN regression does not require a parametric distribution for the response or a linear relationship between predictors and response. It does require a defined predictor representation and distance rule. Its predictions can be useful when nearby observations tend to have similar expected responses. If the predictors are on very different scales, a distance calculation in the original units can give one predictor disproportionate influence for purely numerical reasons.

Scaling Before Measuring Distance

For predictors measured in different units, a common approach is to scale each predictor using constants calculated from the training data. Two familiar choices are min-max scaling and standardization. For min-max scaling, predictor \(j\) is transformed as follows, where \(a_j\) and \(b_j\) are its training-set minimum and maximum:

$$ x_{ij}^{*}=\frac{x_{ij}-a_j}{b_j-a_j} $$

For standardization, subtract the training mean and divide by the training standard deviation. After either transformation, Euclidean distance between a query and training observation is the square root of the sum of squared differences across the transformed predictors. The scaling rule is a modeling choice, not a guarantee that every predictor is equally relevant. The transformed features and the distance rule must be appropriate to the problem.

Important: Calculate scaling constants from the training data, then use those same constants to transform validation observations and future query points. Do not calculate a separate scale for each query or use validation outcomes to decide the scaling constants.

Worked Example: Min-Max Scaling Changes the Neighbors

A hypothetical estimator predicts a numeric claim-severity measure, in thousands of dollars, from annual income, in thousands of dollars, and policy tenure, in years. The training observations are A: \((76,0)\), response \(100\); B: \((80,1.8)\), response \(180\); C: \((60,1.7)\), response \(140\); and D: \((100,2)\), response \(220\). Predict the response for a query with income \(75\) and tenure \(1.8\), using \(k=2\) and min-max scaling.

Method. Use the training minimum and maximum for each predictor. Income ranges from \(60\) to \(100\), and tenure ranges from \(0\) to \(2\). Thus the scaled query is \(((75-60)/40,(1.8-0)/2)=(0.375,0.9)\).

The scaled training points are A: \((0.4,0)\), B: \((0.5,0.9)\), C: \((0,0.85)\), and D: \((1,1)\). Calculate squared Euclidean distances; taking square roots is unnecessary for ranking:

  • A: \((0.4-0.375)^2+(0-0.9)^2=0.000625+0.81=0.810625\).
  • B: \((0.5-0.375)^2+(0.9-0.9)^2=0.015625+0=0.015625\).
  • C: \((0-0.375)^2+(0.85-0.9)^2=0.140625+0.0025=0.143125\).
  • D: \((1-0.375)^2+(1-0.9)^2=0.390625+0.01=0.400625\).

The two smallest squared distances are B's \(0.015625\) and C's \(0.143125\). Their responses are \(180\) and \(140\), so the prediction is \((180+140)/2=160\) thousand dollars.

Check and trap avoided. Without scaling, the raw distances for A, B, C, and D are approximately \(2.06\), \(5.00\), \(15.00\), and \(25.00\). Raw-unit distance would select A and B, giving \((100+180)/2=140\), rather than the scaled result of \(160\). In this example, the tenure range is only two years while income ranges over forty thousand dollars; raw distance lets income's numerical scale dominate. The calculation uses the training ranges for both the training observations and query.

Unweighted and Distance-Weighted Predictions

The ordinary KNN prediction gives each selected neighbor equal influence. A weighted version gives closer neighbors more influence. One possible rule is inverse-distance weighting, with weight \(w_i=1/d_i\), where \(d_i\) is the distance to neighbor \(i\). The prediction is the weighted response average. Other weight rules are possible, so a problem's specified rule takes precedence.

$$ \widehat{y}(\mathbf{x}_0)= \frac{\sum_{i\in N_k(\mathbf{x}_0)}w_i y_i} {\sum_{i\in N_k(\mathbf{x}_0)}w_i} $$

Here \(N_k(\mathbf{x}_0)\) denotes the selected set of \(k\) neighbors. A distance-weighted prediction still averages responses, but it does not generally equal the unweighted average. If a selected neighbor has distance zero, inverse-distance weights are undefined; a standard practical rule is to predict from the zero-distance observations alone, or to use a specified alternative weighting rule. Do not apply the inverse-distance formula unchanged at zero distance.

Worked Example: Comparing Equal and Inverse-Distance Weights

A hypothetical portfolio review uses one already scaled predictor. For a new case, the three nearest training observations have scaled distances \(0.1\), \(0.2\), and \(0.4\), with responses \(80\), \(140\), and \(260\) thousand dollars, respectively. For \(k=3\), calculate the unweighted prediction and the inverse-distance weighted prediction.

Unweighted method. Add the three responses and divide by three:

$$ \widehat{y}_{\mathrm{unweighted}}=\frac{80+140+260}{3} =\frac{480}{3}=160 $$

The unweighted prediction is \(160\) thousand dollars.

Weighted method. The inverse-distance weights are \(1/0.1=10\), \(1/0.2=5\), and \(1/0.4=2.5\). The weighted response total is \(10(80)+5(140)+2.5(260)=800+700+650=2{,}150\). The weight total is \(10+5+2.5=17.5\). Therefore:

$$ \widehat{y}_{\mathrm{weighted}}=\frac{2{,}150}{17.5} =122.857\ldots $$

To two decimal places, the weighted prediction is \(122.86\) thousand dollars. It is lower than the unweighted prediction because the closest neighbor has the lowest response and receives the greatest weight.

Check and trap avoided. The weights must be used in both the numerator and denominator. Dividing \(2{,}150\) by \(3\) would not be a weighted average. The answer also remains in thousands of dollars, the unit used for the responses.

Why the Neighbor Average Is the Least-Squares Prediction

The unweighted neighbor average has a simple justification. Within the selected neighborhood, treat the prediction as one constant \(c\). Choose \(c\) to minimize the sum of squared deviations between the neighbor responses and that constant:

$$ Q(c)=\sum_{i\in N_k(\mathbf{x}_0)}(y_i-c)^2 $$

Differentiate with respect to \(c\), set the derivative equal to zero, and solve. Since the second derivative is \(2k>0\), the resulting critical point is the minimum:

$$ \frac{dQ}{dc}=-2\sum_{i\in N_k(\mathbf{x}_0)}(y_i-c)=0 \quad\Longrightarrow\quad kc=\sum_{i\in N_k(\mathbf{x}_0)}y_i \quad\Longrightarrow\quad c=\frac{1}{k}\sum_{i\in N_k(\mathbf{x}_0)}y_i $$

Thus the neighbor average is the constant that minimizes squared error among the selected responses. If squared deviations are instead weighted by positive weights, minimizing the weighted sum gives the weighted average in the preceding formula. This explains the calculation; it does not establish that the chosen neighbors will predict well for new data. That is why \(k\) must be assessed using data not used to fit the neighborhood predictions.

Tuning \(k\) with Validation Errors

A small \(k\) makes predictions depend on only a few observations and can be sensitive to individual responses. A larger \(k\) averages over a broader neighborhood and may smooth away local variation. The appropriate choice depends on predictive performance. Given validation responses \(y_j\) and predictions \(\widehat{y}_j(k)\), the validation mean squared error (MSE) is the average squared prediction error:

$$ \operatorname{MSE}_{\mathrm{val}}(k) =\frac{1}{m}\sum_{j=1}^{m}\bigl(y_j-\widehat{y}_j(k)\bigr)^2 $$

For a set of candidate values of \(k\), select the value with the smallest validation MSE, unless the problem specifies a different criterion or tie rule. The validation observations are prediction targets, not members of their own neighbor pools: each validation prediction is formed from the training observations. Training error alone is not a substitute for validation error because it measures fit on the observations used to construct the predictions.

Worked Example: Selecting \(k\) from Validation Predictions

A hypothetical analyst has four validation responses, in thousands of dollars: \(20,30,40,50\). The supplied predictions for four candidate values of \(k\) are shown below. Calculate each validation MSE and select \(k\).

\(k\)Validation predictionsSquared errorsValidation MSE
116, 32, 34, 50\(16, 4, 36, 0\)\(56/4=14\)
318, 31, 37, 50\(4, 1, 9, 0\)\(14/4=3.5\)
519, 28, 38, 49\(1, 4, 4, 1\)\(10/4=2.5\)
721, 27, 38, 48\(1, 9, 4, 4\)\(18/4=4.5\)

For example, at \(k=3\), the residuals, computed as observed minus predicted, are \(2,-1,3,0\). Their squares sum to \(4+1+9+0=14\), so the MSE is \(14/4=3.5\). The other rows use the same calculation. The smallest validation MSE is \(2.5\), attained at \(k=5\); therefore select \(k=5\) among these candidates.

Check and trap avoided. The prediction errors need not be positive, but their squares are nonnegative. The selected value is based on validation MSE, not on which \(k\) has the smallest numerical value or the smallest training error. If a separate test set is available, reserve it for a final assessment after tuning rather than using it to select \(k\).

A Reliable Calculation Sequence

A careful KNN regression solution keeps scaling, neighbor selection, averaging, and tuning as distinct steps. This makes it easier to identify where an incorrect result entered the calculation.

1
Fix the predictor scale.
Use the stated scaling method and constants calculated from training data; transform query and validation predictors with those same constants.
2
Calculate and rank distances.
Apply the specified distance metric to the scaled predictors. Squared Euclidean distances may be ranked without taking square roots.
3
Predict from the selected neighbors.
Use the unweighted mean or the specified normalized weighted mean, and preserve the response's units.
4
Tune using validation performance.
Calculate the requested validation error for each candidate \(k\), then choose according to the stated criterion.

These calculations are aligned with the SOA Exam SRM (Statistics for Risk Modeling) syllabus. Common errors include scaling the query differently from the training data, using distances from unscaled predictors after the problem specifies scaling, averaging only the weights rather than the weighted responses, and choosing \(k\) from training performance when validation errors are supplied. A final check should confirm the neighbor identities, the prediction units, and the direction of the validation comparison.

Check Your Understanding

Try each problem by identifying the calculation rule before substituting values.

  1. A predictor has training minimum \(10\) and maximum \(30\). A query value is \(22\). What is its min-max scaled value? (Answer: \(0.6\))
  2. After scaling, a query has distances \(0.2,0.5,0.7\) to three observations with responses \(40,70,100\). For \(k=2\), what is the unweighted prediction? (Answer: \(55\))
  3. Two selected neighbors have distances \(0.25\) and \(0.5\), and responses \(60\) and \(120\). Under inverse-distance weighting, what is the prediction? (Answer: \(80\))
  4. A validation set has four cases. For one candidate \(k\), its observed-minus-predicted errors are \(1,-2,1,0\). What is its validation MSE? (Answer: \(1.5\))
  5. Three candidates have validation MSEs \(k=2: 6.25\), \(k=4: 4.00\), and \(k=6: 4.50\). Which \(k\) is selected by minimum validation MSE? (Answer: \(k=4\))
Clinical Biostats