Sub topic 7
Regression: predicting a number
Prerequisites
This chapter assumes you know what features and labels are, and that you have met supervised learning and classification. You should be comfortable with Python, NumPy arrays, and the idea of a function with a slope and an intercept.
What regression is
Regression is the supervised task of predicting a continuous number. The label is a quantity such as a price, a temperature, or a delivery time. Classification picks from a fixed set of categories. Regression returns a value that can fall anywhere on a number line.
A quick test: if averaging two possible answers still makes sense, the task is probably regression. The average of "$200,000" and "$300,000" is a valid price. The average of "cat" and "dog" is not a valid class.
The simplest model: a straight line
Linear regression assumes the label is a weighted sum of the features plus a constant. With one feature x, the model is:
prediction = slope * x + intercept
The slope and intercept are the model's parameters. Training searches for the values that fit the labeled examples best. With several features, there is one weight per feature, plus one intercept.
A worked example
The code below creates noisy data from a known rule, y = 3x + 2, then asks the model to recover that rule from the data alone.
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]]))X has shape (100, 1): 100 examples with one feature each. The noise term, with standard deviation 1, stands in for real-world scatter. The learned coef_ and intercept_ should land close to 3 and 2, though not exactly on them. The prediction for x = 5 should be near 17, because 3 × 5 + 2 = 17.
How the fit is chosen
Linear regression usually minimizes the mean squared error (MSE). For each example it takes the gap between the true label and the prediction, squares it, and averages the results.
Squaring has two effects. Positive and negative errors cannot cancel each other. Large errors are punished much more than small ones, so a single wild outlier can pull the line toward it.
Common errors
- Using accuracy as the metric. Accuracy counts exact matches, and a predicted number almost never equals the true one exactly. Use MSE, root mean squared error (RMSE), or mean absolute error (MAE). RMSE and MAE are in the same units as the label, which makes them easier to read.
- Scoring on training data. A low training error says little about new inputs. Hold out a test set, as covered in the generalization chapter.
- Forcing a line onto a curve. If the true relationship bends, a straight line underfits. Plot the residuals, which are the true values minus the predictions. A visible pattern in them means the model is missing structure.
- Extrapolating. The model will return a number for any input, including one far outside the training range. That number has no support from the data.
- Passing a 1-D array as
X. Scikit-learn expects a 2-D array of shape(n_examples, n_features). Usereshape(-1, 1)for a single feature.
Choosing a metric
| Metric | What it tells you | Sensitive to outliers |
|---|---|---|
| MSE | Average squared error | Very |
| RMSE | Typical error, in label units | Very |
| MAE | Average absolute error, in label units | Less |
Exercise
A model predicts house prices in dollars and has an RMSE of 20,000 on the test set. What does that number mean, and why is accuracy the wrong metric here?
Show answer
On average, the predictions are off by roughly $20,000, with larger misses weighted more heavily because errors are squared before averaging. Accuracy counts exact matches. A predicted price will almost never equal the true price exactly, so accuracy would be near zero even for a good model.
Exercise
You fit LinearRegression on one feature stored in a 1-D array of shape (100,), and scikit-learn raises an error. What is the fix?
Show answer
Reshape the features to 2-D with X.reshape(-1, 1), giving shape (100, 1). Scikit-learn expects one row per example and one column per feature.