Sub topic 1
What regression predicts and why we use it
Regression predicts a number. You give a model some measured inputs, such as the floor area of a flat, and it returns a continuous quantity, such as a price. This chapter sets up the vocabulary and the data layout used in the rest of the tutorial. It also covers when regression is the right tool and where it stops being one.
Prerequisites
This chapter assumes you have the following:
- Basic Python, including functions and imports.
- Introductory NumPy: creating arrays and reading
.shape. - Basic pandas: selecting columns from a DataFrame.
- High-school algebra: the equation of a line, the mean and the variance.
You do not need any machine learning background. Scikit-learn is the Python library used throughout. Install it with pip install scikit-learn.
The prediction target
A regression problem has a target, the quantity you want to predict, and that target is numeric and ordered. Differences between values are meaningful. A prediction of 310 is closer to a true value of 300 than a prediction of 450 is.
Typical regression targets:
- The sale price of a house.
- Tomorrow's electricity demand in megawatts.
- The time a delivery will take, in minutes.
- A patient's blood glucose level six months after a baseline visit.
The inputs are called features. Each feature is a measured property of one example, such as area, number of rooms or distance to the city centre. Each example is one row of data, called a sample.
Regression differs from classification, which predicts a category such as "spam" or "not spam". The two can use similar models, but they are scored differently. A classifier is right or wrong. A regressor is off by some amount, so we measure how far off it is.
| Task | Target | Example output | Typical question |
|---|---|---|---|
| Regression | Continuous number | 312.4 | How much? |
| Classification | Category label | "spam" | Which one? |
Supervised learning in one picture
Regression is a kind of supervised learning. You train on examples where the correct answer is already known, and the model learns a rule that maps features to the target. Later you apply that rule to new samples whose target you do not know.
There are two phases:
- Fit. The model sees
Xandytogether and chooses its internal parameters so its predictions on the training data are close toy. - Predict. The model sees only new
Xand returns estimates ofy.
The second phase is the reason to fit a model at all. A model that only reproduces known answers is a lookup table. The goal is to estimate targets for samples you have not seen, so performance on unseen data is what matters.
Why use regression
Regression is used for several different purposes.
- Prediction. Estimate a value you cannot measure yet, such as next month's sales. You care about accuracy on new data.
- Explanation. Describe how the target changes as a feature changes, for example "each extra square metre adds about 2.5 thousand to the price". You care about the fitted parameters. A later chapter covers how to read them.
- Baselines and benchmarks. A simple regression is a cheap reference. If a complex model barely beats it, the complexity is not paying off.
Linear models are popular for these jobs. They train in milliseconds, they behave predictably, and their parameters can be read directly. Many real relationships are close enough to linear in a limited range of the inputs, and a linear model captures that part with little risk of overfitting.
How scikit-learn expects the data
Scikit-learn uses a fixed layout:
Xis a 2-D array of shape(n_samples, n_features). Rows are samples and columns are features.yis a 1-D array of shape(n_samples,), holding one target value per sample.
The most common first error is passing a 1-D feature array as X. Scikit-learn raises an error because it cannot tell whether the values are many samples with one feature or one sample with many features. Use reshape(-1, 1) for a single feature.
The example below builds synthetic flat prices, checks the shapes, and fits a baseline that ignores the features entirely. DummyRegressor with strategy="mean" always predicts the mean of the training targets.
import numpy as np
from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_absolute_error
rng = np.random.default_rng(0)
area = rng.uniform(40, 160, size=100) # square metres
X = area.reshape(-1, 1) # shape (100, 1)
y = 2.5 * area + 30 + rng.normal(0, 15, size=100) # price in thousands
print("X shape:", X.shape, "y shape:", y.shape)
baseline = DummyRegressor(strategy="mean").fit(X, y)
print("baseline prediction for 100 m2:", baseline.predict([[100.0]]))
print("baseline MAE:", mean_absolute_error(y, baseline.predict(X)))Every prediction equals the training mean, whatever the area. The mean absolute error (MAE) is the average size of the miss, in the units of the target. Any model that uses the area should beat this number. If it does not, the features carry no useful signal, or the model is badly set up.
Here the baseline is scored on its own training data to keep the example short. Later chapters score models on held-out data, which is the honest way to measure them.
When regression is the right tool
Check these points before choosing a regression model:
- The target is numeric and meaningfully ordered. A zip code is a number but not a quantity, so predicting one is classification. Averaging two zip codes means nothing.
- You have labelled examples. Without known targets there is nothing to supervise the fit.
- Future samples resemble the training samples. The model learns patterns in the data it saw. If the world changes, the patterns may stop holding.
- Predicting a number is actually the goal. Sometimes the decision depends only on a threshold, such as "will the price exceed 300?". A classifier may fit that need better.
Edge cases and limits
Extrapolation. A model fitted on flats between 40 and 160 square metres says nothing reliable about a 400 square metre mansion. A linear model will still produce a number, and it may look plausible. Be suspicious of predictions outside the range of the training features.
Bounded or skewed targets. Prices and durations cannot be negative, but a linear model can predict a negative value. Targets with a long right tail, such as incomes, often make the largest errors dominate the fit. A common remedy is to model the logarithm of the target. This chapter only flags the problem.
Counts and proportions. A count of events or a share between 0 and 1 is numeric, so regression applies. Specialised models often respect such limits better, and scikit-learn has some, but they are outside this tutorial.
Noise. Even with the right model and plenty of data, predictions will not be exact. Part of the target is random variation that no feature explains. A perfect fit on training data is therefore a warning sign, not a goal. Later chapters on overfitting and regularization explain why.
How the rest of the tutorial builds on this
The next chapters define the linear model, show how ordinary least squares chooses its parameters, and introduce the estimator API of fit, predict and score. After that you will measure error properly on held-out data, check residuals, and move on to pipelines, cross-validation and regularized models. All of it rests on the picture in this chapter: features in, a number out, and a fit that is judged on samples it has not seen.
Exercises
Exercise
You have a dataset of customer records and want to predict how many minutes each customer will spend on a website. Is this regression or classification, and what are X and y?
Show answer
It is regression, because the target is a continuous number of minutes. X is a 2-D array of shape (ncustomers, nfeatures) with the customer attributes. y is a 1-D array of shape (n_customers,) with the minutes spent.
Exercise
A teammate has one feature stored in a 1-D NumPy array a of length 50 and calls model.fit(a, y). Scikit-learn raises an error. What is wrong, and what is the fix?
Show answer
Scikit-learn requires X to be 2-D with shape (nsamples, nfeatures), and a has shape (50,). Reshape it with a.reshape(-1, 1) to get shape (50, 1), one feature across 50 samples, and pass that as X.
Exercise
Why is a model that predicts the training mean for every sample useful, and what does it tell you if your real model has a similar error?
Show answer
It is a baseline that uses no feature information, so it sets the error you get from knowing only the average target. A real model with a similar error is adding almost nothing. The features may carry little signal, or the model or its setup may have a problem.