Sub topic 7
Regression: predicting a number
Prerequisites and scope
This chapter assumes you know what features and labels are, and that you have seen the supervised workflow: fit on training data, then evaluate on held-out data. You should be comfortable with Python, NumPy arrays, and the idea of a function with a slope and an intercept. It covers regression only. Loss minimization, overfitting, and evaluation each get their own chapters, so they appear here only where regression needs them.
What regression is
Regression is a supervised learning task where the label is a number on a continuous scale. The model learns a function from features to that number. Examples:
- Predicting the price of a house from its area and number of rooms.
- Predicting tomorrow's electricity demand from temperature and day of the week.
- Predicting how many minutes a delivery will take from distance and traffic.
The deciding question is what the label looks like. If the answer is a category such as "spam" or "not spam", the task is classification. If the answer is a quantity where "close" is meaningful, it is regression. Predicting 41 when the truth is 42 is a small error. Predicting "cat" when the truth is "dog" is simply wrong. That difference is why regression needs error measures that capture distance.
A label that looks numeric is not always a regression target. Star ratings from 1 to 5, or ZIP codes, are really categories or ordered categories. Ask whether averaging two labels gives something meaningful.
The model: a line through the data
The simplest regression model is linear regression. With one feature, it predicts
prediction = slope * x + interceptThe slope and the intercept are the model's parameters, the numbers that training adjusts. With several features, there is one coefficient per feature plus a single intercept:
prediction = w1*x1 + w2*x2 + ... + wn*xn + bEach coefficient says how much the prediction changes when that feature rises by one unit and the others stay fixed. The intercept is the prediction when all features are zero. That is sometimes meaningless in practice, for example a house with zero area, so do not over-interpret it.
A worked example
The following code generates noisy data from a known rule, y = 3x + 2 plus noise. Then it checks whether the model recovers that rule.
import numpy as np
from sklearn.linear_model import LinearRegression
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(100, 1))
y = 3 * X[:, 0] + 2 + rng.normal(0, 1, size=100)
model = LinearRegression().fit(X, y)
print(model.coef_, model.intercept_)
print(model.predict([[5.0]]))A few details matter here:
Xis two-dimensional with shape(100, 1): 100 examples, one feature. Scikit-learn always expects this shape for features, even when there is only one.yis one-dimensional with shape(100,).coef_is an array with one entry per feature. It should come out close to 3.intercept_is a single number that should come out close to 2.predicttakes a two-dimensional input, so a single new example is written[[5.0]]. The result should be near3 * 5 + 2 = 17.
The estimates are close to the true values but not equal to them. The noise in the data shifts the fitted line a little. With fewer examples or more noise, the estimates drift further.
How the line is chosen
Many lines could pass near the points, so training needs a way to rank them. Linear regression uses squared error. For each training example, take the difference between the true value and the prediction, square it, and average over all examples. This average is the mean squared error (MSE), and it is the loss that ordinary least squares minimizes.
Squaring has two effects. Positive and negative errors cannot cancel each other out. Large errors also count much more than small ones: an error of 10 costs 100, while ten errors of 1 cost only 10 in total. The fitted line will therefore bend toward outliers, points far from the general trend.
For ordinary linear regression, the best parameters can be computed directly from the data with linear algebra, so no iterative search is needed. Other regression models, such as neural networks, use gradient-based optimization instead. The chapter on training covers that.
Evaluating a regressor
A classifier is judged by how often it is right. A regressor is almost never exactly right, so you measure how far off it is. Always compute these numbers on held-out test data, not on the training set.
| Metric | What it measures | Units | Notes |
|---|---|---|---|
| Mean absolute error (MAE) | Average size of the error | Same as the label | Easy to explain. Treats all errors equally. |
| Mean squared error (MSE) | Average of squared errors | Label squared | The training loss for least squares. Penalizes large errors heavily. |
| Root mean squared error (RMSE) | Square root of MSE | Same as the label | Like MAE but weighted toward large errors. |
| R² (coefficient of determination) | Share of variance explained | None | 1 is perfect. 0 matches always predicting the mean. Can be negative on test data. |
Which one to report depends on the cost of mistakes. If a miss of 20 is twice as bad as a miss of 10, MAE reflects your cost. If a miss of 20 is far worse than two misses of 10, RMSE reflects it better. R² is useful for comparing models on the same data. It does not tell you the error in real units, and it is hard to compare across datasets.
The next example computes all four on a held-out split.
import numpy as np
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.metrics import (
mean_absolute_error,
mean_squared_error,
r2_score,
)
rng = np.random.default_rng(0)
X = rng.uniform(0, 10, size=(200, 1))
y = 3 * X[:, 0] + 2 + rng.normal(0, 1, size=200)
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.25, random_state=0
)
model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)
mse = mean_squared_error(y_test, pred)
print("MAE :", mean_absolute_error(y_test, pred))
print("MSE :", mse)
print("RMSE:", np.sqrt(mse))
print("R^2 :", r2_score(y_test, pred))Because the noise has a standard deviation of 1, the RMSE should land near 1. That is the best any model can do here, since the noise cannot be predicted. This is a useful habit: when you know or can estimate the noise level, you know the floor under the error.
Note that train_test_split here has no stratify argument. Stratifying keeps class proportions equal across splits, which only makes sense for categories.
Beyond a straight line
A linear model fits only linear relationships. If the true pattern curves, the model underfits: it has too little flexibility, and the error is high on both training and test data. Common remedies:
- Add features that capture the curve, such as the square of a feature (polynomial features).
- Use a more flexible model, such as a decision tree regressor or a gradient-boosted ensemble.
- Transform the label when it spans orders of magnitude, for example by predicting the logarithm of a price.
Flexibility has a cost. A high-degree polynomial can pass through every training point and still predict badly on new data. That is overfitting, and the held-out error is how you catch it. Regularized variants such as Ridge and Lasso add a penalty on large coefficients to reduce this risk.
The diagram shows how the pieces of a regression workflow connect.
Common errors
- Passing a one-dimensional feature array.
fit(X, y)withXof shape(100,)raises an error asking you to reshape. UseX.reshape(-1, 1)for a single feature. - Reporting training error as if it were the model's quality. Training error is optimistic. Report test error.
- Extrapolating. A line keeps going forever, but the real relationship may not. Predicting far outside the range of the training features is unreliable, such as a model trained on areas of 50 to 200 square meters asked about 2,000.
- Comparing features measured on different scales by coefficient size. A coefficient of 0.001 on a feature measured in millions may matter more than a coefficient of 5 on a feature between 0 and 1. Standardize features before comparing coefficients.
- Reading R² as accuracy. A high R² does not mean the predictions are accurate in practical terms. Check the error in the label's own units.
- Ignoring outliers. Because of the squaring, one bad data point can pull the whole fit. Inspect residuals, which are the differences between true and predicted values. If they show a pattern instead of random scatter, the model is missing something.
Summary
Regression predicts a continuous number. Linear regression learns one coefficient per feature plus an intercept by minimizing mean squared error. You judge it on held-out data with MAE, RMSE, and R², chosen according to how costly large mistakes are. When a straight line is too rigid, add features or use a more flexible model, and watch the test error for signs of overfitting.
Exercise
A model predicts house prices in thousands of dollars. On the test set its MAE is 20 and its RMSE is 45. What does the gap between the two numbers suggest, and which metric would you favor if a few very large mistakes would be especially costly to the business?
Show answer
RMSE is much larger than MAE because squaring gives large errors extra weight. The gap suggests that most predictions are off by a modest amount, but a few predictions are off by a lot. If large mistakes are especially costly, favor RMSE, since it reflects that cost. You should also look at the residuals to find which houses produce the large errors.
Exercise
You fit LinearRegression on training data where the feature area ranges from 50 to 200 square meters. A colleague asks it to predict the price of a 2,000 square meter property. Give two reasons to distrust the answer.
Show answer
First, the request is far outside the range seen in training, so the model is extrapolating and nothing shows the linear trend holds there. Second, the model's error was measured only on data similar to the training range, so the test metrics say nothing about how reliable it is at 2,000 square meters. Large properties may follow a different pricing pattern than a straight line.