Concepts / Linear Models for Regression

Linear Models for Regression

A linear model for regression predicts a weighted sum of the input features plus an offset, written as ŷ = w[0]*x[0] + ... + w[p]*x[p] + b, and the weights can be negative.

  • Programming

Why Regression Needs a Number, Not a Label

Many introductory machine learning methods answer the question of which category a new data point belongs to. Regression asks a different question: what number should we predict? A house price, a temperature, or a score is a continuous target value, and a regression model must produce a number for every new input.

This article covers two families of regression models. The first is k-nearest neighbors regression, which keeps the familiar idea of looking at the closest training points but uses their numeric targets to produce a prediction. The second is the linear regression model, which predicts a weighted sum of the input features plus an offset. For both, we will trace exactly what the model computes, so that its predictions stop looking like magic.

Tracing One Prediction with Nearest Neighbors

The simplest case is a single neighbor. To predict the target for a new input, the algorithm finds the nearest training point and returns that point's target value. Nothing is averaged. The prediction is copied directly from the closest example.

When more than one neighbor is used, the prediction becomes the average, or mean, of the target values of the relevant neighbors. The number of neighbors is set by the parameter n_neighbors, which is often written as k. The steps are the same for every value of k: find the k nearest training points, read their target values, and average them. The diagram traces this path for one query point.

New query pointFind k nearesttraining pointsdistance decides neighborsRead their targetvaluesnumbers, not labelsAverage the targetvaluesthe mean of the neighborsPredicted numberk targets
What steps turn a new input into a prediction: find the k closest training points, read their target values, then average them?
Worked example

Tracing a k = 3 prediction by hand

A training set has five points with targets: at input 1.0 the target is 2.0, at 2.0 it is 3.0, at 4.0 it is 7.0, at 6.0 it is 10.0, and at 9.0 it is 12.0. Predict the target for a new query at input 2.5 using k = 3. Distance here is the gap along the single feature.

  1. 1
    Measure distances

    The gaps from 2.5 are 1.5 (to 1.0), 0.5 (to 2.0), 1.5 (to 4.0), 3.5 (to 6.0), and 6.5 (to 9.0).

  2. 2
    Select the k nearest

    The three smallest gaps belong to inputs 2.0, 1.0, and 4.0, so those are the three neighbors.

  3. 3
    Read their targets

    The targets of those neighbors are 3.0, 2.0, and 7.0.

  4. 4
    Average them

    The mean is (3.0 + 2.0 + 7.0) / 3 = 4.0, so the prediction is 4.0.

Result

The predicted target for input 2.5 is 4.0. Nothing about the query was used except which points were nearest; the output is a mean of training targets.

Fitting and Scoring a Model in scikit-learn

In scikit-learn, KNeighborsRegressor is used the same way as KNeighborsClassifier. You create it with n_neighbors, call fit on training data, call predict on new inputs, and call score to get the R2 score. The program below follows the four jobs a complete regression run needs: load data, split it, fit a regressor with three neighbors, then predict and score on the test set. The dataset here is a small synthetic sine-shaped set generated for this lesson.

python
Notes on the code
  • reg.fit receives only the training data, so the test set remains unseen
  • predict returns one numeric prediction per row of X_test
  • score returns the R2 score on the test data

Read the program as one complete unit. The line that fits the model uses only the training split. Only afterward do we call predict and score on the test split. If you accidentally fit on the full dataset before scoring, the score would reflect inputs the model had already seen, and it would no longer be a fair measure of how the model handles new data.

What do you think happens?

If you call predict on a training input with k = 1, what value comes back?

Reveal answer
Answer:

The target value of that same training point.

With one neighbor, the nearest training point to a training input is that point itself, and its target is copied directly.

How the Neighbor Count Shapes the Fit

The number of neighbors controls how closely the model follows the training data. The source compares predictions for 1, 3, and 9 neighbors on a one-dimensional dataset, evaluating the model along a dense line of inputs across the feature range. The comparison exposes the central trade-off in choosing k.

k = 1passes through everytraining pointUnsteady curveeach point controls its ownregionSmall kmore detail, somejaggednessBalanced fitfollows structure withoutchasing every pointLarge kaverages many targetsSmooth curvefits training data lessclosely
How does the fitted curve change between k=1, a small k, and a large k, and why does a larger k produce a smoother prediction?

With a single neighbor, the predicted values pass through all of the data points, which gives a very unsteady prediction. Considering more neighbors produces smoother predictions, but those smoother predictions fit the training data less well. A larger k smooths the curve because each prediction averages more targets, so one unusually high or low training target has less influence on any single output.

The source identifies two main parameters for k-nearest neighbors: the number of neighbors and the way distance between data points is measured. By default, KNeighborsRegressor uses Euclidean distance, which works well in many settings. The number of neighbors is the parameter you should adjust.

Reading the R2 Score

Definition

The R2 score, also known as the coefficient of determination, is the value returned by the score method of a regressor. It measures how good a prediction is for a regression model. A value of 1 corresponds to a perfect prediction. A value of 0 corresponds to a constant model that just predicts the mean of the training set responses.

To read a score, compare it against those two reference points. A score near 1 means the predictions closely match the targets. A score near 0 means the model is no better than always predicting the training mean. The source reports a test score of 0.83 for its model, which it describes as indicating a relatively good model fit.

EASY

A model scores 0.02 on the test set. Explain in one or two sentences what this tells you about the model compared with simply predicting the training mean.

Hints
  • Compare the score with the two reference points, 1 for a perfect match and 0 for the constant mean model.
  • A score close to 0 means the model is roughly as good as the constant baseline.

Mistakes and Limits of Nearest-Neighbor Regression

  • Common mistake

    Using k = 1 because it fits the training data most closely

    What it looks like

    A model with one neighbor reproduces every training target exactly, so its training fit looks perfect.

    Why it fails

    The source describes this as a very unsteady prediction that passes through all data points. Such a curve can chase noise rather than real structure.

    Do this instead

    Tune the neighbor count and compare candidate values on held-out data.

  • Common mistake

    Judging the model only on training data

    What it looks like

    Calling score on the same data used by fit.

    Why it fails

    The score then reflects inputs the model has already seen, so it overstates how well the model handles new data.

    Do this instead

    Split the data first, fit only on the training part, and score on the test part.

  • Common mistake

    Expecting predictions to exceed the range of training targets

    What it looks like

    Predicting a value far above every training target for a query well outside the training inputs.

    Why it fails

    Each prediction is an average of training target values, so it stays within the range of those targets.

    Do this instead

    Expect nearest-neighbor predictions to be bounded by the training targets, and use a different model if you need extrapolation.

  • Common mistake

    Ignoring preprocessing: the source advises preprocessing the data when using k-NN, because neighbors are chosen by distance

  • Common mistake

    Using k-NN for large problems: prediction can be slow when the training set is very large in number of features or number of samples

The Linear Prediction Formula

A linear model for regression predicts a weighted sum of the input features plus an offset. For a single data point with features x_0 through x_p, where p is the number of features, the general prediction formula is written below. The values w and b are parameters learned from data, and the symbol ŷ, read as y-hat, is the prediction the model makes.

Formula
Formula, step by step
  1. 1
    Each feature x_i is multiplied by its own weight w_i.
  2. 2
    The products w_0 x_0 through w_p x_p are added together, forming a weighted sum.
  3. 3
    The constant b is added at the end to shift the result.
  4. 4
    The result ŷ is the model's prediction for that data point.
ŷthe predictionw[0] x[0]first weight times firstfeature+ ... +one term per featurew[p] x[p]last weight times lastfeature+ bthe offsetequals
How does each piece of the formula contribute to the prediction, from the first weighted feature to the offset?

Read the formula from left to right as a recipe. Each feature is multiplied by its weight, the products are added, and the constant b is added at the end. The weights are the entries of w, and they can be negative. A negative weight means that a larger value of that feature pushes the prediction down rather than up. Adding a feature adds one more term to the sum and one more weight to learn.

Worked example

Computing one linear prediction

A model has two features, with weights w = [2.0, -1.0] and offset b = 0.5. Find the prediction for a data point with features x = [3.0, 4.0].

  1. 1
    Weight the first feature

    w_0 x_0 = 2.0 times 3.0 = 6.0.

  2. 2
    Weight the second feature

    w_1 x_1 = -1.0 times 4.0 = -4.0. The negative weight pulls the prediction down.

  3. 3
    Add the weighted terms

    6.0 + (-4.0) = 2.0.

  4. 4
    Add the offset

    2.0 + 0.5 = 2.5.

Result

The predicted value is 2.5.

What the Weights and Offset Mean

The two kinds of learned parameter have distinct geometric meanings. With a single feature, the parameters describe a line, and the learned values are interpreted directly from it. The parameter meanings below follow from that picture.

Line, Plane, or Hyperplane

The shape of a linear regression prediction depends on how many features the model uses. The source characterizes linear models by the geometric object their prediction forms. The table summarizes the cases.

Number of featuresShape of the predictionMeaning
1LineA slope w[0] and an offset b describe the prediction
2PlaneOne slope per feature axis, sitting over a two-dimensional input
More than 2HyperplaneThe higher-dimensional version of a line or plane

Dimension of the feature space determines the prediction surface

A hyperplane is the higher-dimensional version of a line or plane, and the source uses it to describe the general case. You cannot draw a hyperplane for many features, but the same formula and the same role for each weight and the offset apply in every dimension.

Testing the Straight-Line Belief

A common first reaction to linear models is that they must be too simple. A straight line fitted to a wiggly pattern seems to ignore almost everything interesting in the data, and many learners conclude that a model which outputs only a line or a flat surface cannot capture real structure. The source agrees that, on one-dimensional data, a straight line looks very restrictive, and that in a sense the fine details of the data are lost. It also calls the assumption that the target is a linear combination of the features a strong and somewhat unrealistic assumption.

What do you think happens?

Suppose a dataset has more features than it has training data points. Could a linear model fit the training targets exactly?

  • Yes, a linear model can fit the training targets exactly

  • No, a linear model is always too simple for that case

Reveal answer
Answer:

Yes, a linear model can fit the training targets exactly.

The source notes that if there are more features than training data points, any target can be perfectly modeled as a linear function on the training set. Judging linear models from one-dimensional data gives a skewed picture.

The source also notes that there are many different linear models for regression. They all share the same prediction formula. What differs between them is how the parameters w and b are learned from training data and how model complexity can be controlled. The source says it will go on to cover the most popular of these models.

Practice Tracing a Neighbor Prediction

MEDIUM

Using the five training points from the worked example (inputs 1.0, 2.0, 4.0, 6.0, 9.0 with targets 2.0, 3.0, 7.0, 10.0, 12.0), predict the target for a query at input 5.0 using k = 2. List the two neighbors, read their targets, and compute the average.

Hints
  • Compute the gap from 5.0 to each training input and pick the two smallest.
  • The nearest inputs to 5.0 are 4.0 and 6.0.
  • Average the two targets that belong to those inputs.

Key Takeaways

  • k-nearest neighbors regression predicts a number by averaging the target values of the k nearest training points; with one neighbor it copies the nearest target.
  • The neighbor count k controls the trade-off between an unsteady curve that follows the training data closely and a smooth curve that fits it less well, so k should be tuned.
  • The R2 score is 1 for a perfect prediction and 0 for a model that always predicts the training mean; scikit-learn exposes it through score.
  • The linear prediction is a weighted sum of features plus an offset, ŷ = w_0 x_0 + ... + w_p x_p + b. The weights are slopes along each feature axis, b is the y-axis offset, and the prediction is a line, plane, or hyperplane depending on the number of features.
  • A linear model's straight-line picture is misleading in one dimension: with more features than training points, a linear model can fit the training targets exactly.

Related concepts

More concepts starting with L