Linear regression is the simplest and most widely used machine learning algorithm. It predicts a number by drawing the straight line that best fits your data. In this module you'll understand exactly how it works, then build one in Python.
- Level: Beginner
- Time: about 35 minutes
- Needs: Modules 1 and 2
By the end of this module you will be able to
- Explain what linear regression does and when to use it
- Read the equation of a line: slope and intercept
- Explain what residuals are and how the "best" line is found
- Measure a model's performance with MAE, RMSE and R²
- Use multiple features and explain what each coefficient means
- Know when linear regression is the wrong tool
- Train, test and use a linear regression model in scikit-learn
3.1What is linear regression?
In Module 1 you trained a model that predicted exam scores from study hours. That model was linear regression. Now we'll look at it properly.
Linear regression is a supervised learning algorithm that predicts a number. It looks at the relationship between features and a target, and draws the straight line that fits the data best. Then it uses that line to make predictions.
Linear regression in one sentence
Linear regression finds the straight line that best fits your data points, so you can use it to predict a number for new data.
In this module, we'll help an estate agent in Newcastle predict house prices. Here are ten houses they sold recently:
| Size (m²) | 50 | 60 | 65 | 75 | 80 | 90 | 100 | 110 | 120 | 135 |
|---|---|---|---|---|---|---|---|---|---|---|
| Price (£k) | 130 | 150 | 148 | 175 | 185 | 200 | 228 | 240 | 265 | 290 |
You can already see the pattern: bigger houses cost more. Linear regression turns that pattern into an exact rule we can use to price a house that hasn't been sold yet.
When should you use linear regression?
Use it when the answer is a number (a price, a temperature, a number of sales) and when the target goes up or down steadily as the features change. It's also the best place to start: data scientists often try linear regression first as a baseline before trying anything more complicated.
3.2The equation of a straight line
You may remember this from school maths. Every straight line can be written as:
| Letter | Name | What it means | In our example |
|---|---|---|---|
| y | Target | The thing we want to predict | House price |
| x | Feature | The information we know | House size |
| m | Slope (or coefficient) | How much y goes up when x goes up by 1 | Extra £ for each extra m² |
| c | Intercept | The value of y when x is 0, where the line starts | The "starting price" |
For our houses, linear regression finds this line:
In plain English: start at £30,300 and add about £1,930 for every square metre. So for a 95 m² house:
That's the whole idea. "Training" a linear regression model simply means finding the best values for m and c.
3.3Residuals: how wrong is the line?
No straight line goes through every point perfectly. The gap between a real value and the line's prediction is called a residual (or error).
For example, the 65 m² house sold for £148k. The line predicted about £155.8k, so its residual is −£7.8k. The model over-estimated that house.
A good line has small residuals overall. But how do we decide which line is "best"? That's the next lesson.
3.4Finding the best line
Linear regression uses a method called least squares. It works like this:
- Work out the residual for every point.
- Square each residual (multiply it by itself).
- Take the average. This is the Mean Squared Error (MSE).
- Pick the line with the smallest MSE.
Why square the errors? Two reasons. First, it stops positive and negative errors cancelling each other out (+5 and −5 would add up to 0, which would wrongly look perfect). Second, it punishes big mistakes much more than small ones: an error of 10 becomes 100, but an error of 2 only becomes 4.
Try it: find the best line yourself
Moving sliders by hand is slow. The computer finds the best line in a split second, using either a direct maths formula or a method called gradient descent. Gradient descent is like walking down a hill in fog: you feel which way is downhill, take a small step, and repeat until you reach the bottom (the smallest error). It's also how neural networks learn, which you can explore in the CX Learn Neural Networks track.
3.5How good is the model? MAE, RMSE and R²
Once a model is trained, we test it on data it hasn't seen and measure how well it did. For regression, there are four common measures.
A small worked example
Our model predicts the prices of three test houses:
| House | Actual (£k) | Predicted (£k) | Error | Error² |
|---|---|---|---|---|
| A | 200 | 210 | −10 | 100 |
| B | 250 | 240 | +10 | 100 |
| C | 300 | 330 | −30 | 900 |
| Measure | How to work it out | Our example | What it tells you |
|---|---|---|---|
| MAE Mean Absolute Error | Average of the errors, ignoring minus signs | (10 + 10 + 30) ÷ 3 = 16.7 | "On average, we're about £16.7k out." The easiest to explain. |
| MSE Mean Squared Error | Average of the squared errors | (100 + 100 + 900) ÷ 3 = 366.7 | Used to train the model. Hard to read because the units are squared. |
| RMSE Root Mean Squared Error | Square root of MSE | √366.7 = 19.1 | Back in £k. Higher than MAE because it punishes the big £30k miss. |
| R² R-squared | Compares the model to just guessing the average every time | (from the full test set) | How much of the variation the model explains. 1 is perfect, 0 is no better than guessing. |
Which one should I report?
Use MAE or RMSE when talking to a manager, because they're in real units ("we're usually within £13k"). Use R² to compare models on the same data. Look at more than one, because each tells you something different.
3.6Multiple linear regression
House size isn't the only thing that affects price. The number of bedrooms and how far the house is from the city centre matter too. Multiple linear regression uses several features at once. The idea is exactly the same, the equation just gets longer:
Each feature gets its own slope, called a coefficient. We trained this model on 200 houses (you'll see the code in lesson 3.8). Here is what it learned:
| Feature | Coefficient | What it means in plain English |
|---|---|---|
| Size (m²) | +1.61 | Each extra square metre adds about £1,610 |
| Bedrooms | +11.36 | Each extra bedroom adds about £11,360, for a house of the same size and location |
| Distance to centre (km) | −3.89 | Each extra kilometre from the centre takes off about £3,890 |
| Intercept | 38.5 | The starting value. On its own it has no real meaning (no house has 0 m² and 0 bedrooms) |
A positive coefficient means the feature pushes the price up. A negative one pushes it down. This makes linear regression very easy to explain, which is one reason businesses love it.
Careful comparing coefficients
You can't say "bedrooms matter 7 times more than size" just because 11.36 is bigger than 1.61. The features are measured in different units (one bedroom is a much bigger change than one square metre). To compare importance fairly, scale the features first, as you learned in Module 2.
3.7When linear regression goes wrong
Linear regression is powerful, but it makes some assumptions. When they aren't true, the predictions get worse.
1. The relationship isn't a straight line
Car stopping distances (from the UK Highway Code) don't rise in a straight line: doubling your speed more than doubles the distance.
| Problem | What happens | What to do |
|---|---|---|
| Curved relationship | The line misses the pattern, as above | Add curved features (polynomial regression) or use a tree-based model |
| Outliers | Because errors are squared, one extreme point can drag the whole line towards it | Check outliers first, as you learned in Module 2 |
| Features that move together | If size and number of rooms rise together, the model can't tell which one matters, and coefficients become unreliable (called multicollinearity) | Remove one of the pair, or combine them |
| Predicting far outside the data | The model has only seen houses up to 160 m². Asking about a 1,000 m² mansion is guesswork (called extrapolation) | Only trust predictions inside the range you trained on |
3.8Linear regression in Python
Now let's build the full house price model with scikit-learn. We create 200 houses where we secretly know the "true" rule, so we can check whether the model discovers it: £1,600 per m², £12,000 per bedroom and −£4,000 per km, plus some random noise, just like real life.
import numpy as np
import pandas as pd
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LinearRegression
from sklearn.metrics import mean_absolute_error, mean_squared_error, r2_score
# 1. Create a dataset of 200 houses (price in £1000s)
rng = np.random.default_rng(42)
n = 200
df = pd.DataFrame({
"size_m2": rng.integers(45, 160, n),
"bedrooms": rng.integers(1, 6, n),
"distance_km": rng.uniform(0.5, 15, n).round(1),
})
df["price"] = (40 + 1.6 * df["size_m2"] + 12 * df["bedrooms"]
- 4 * df["distance_km"] + rng.normal(0, 15, n)).round(0)
# 2. Features (X) and target (y)
X = df[["size_m2", "bedrooms", "distance_km"]]
y = df["price"]
# 3. Split into training and test sets
X_train, X_test, y_train, y_test = train_test_split(
X, y, test_size=0.2, random_state=42)
# 4. Train the model
model = LinearRegression()
model.fit(X_train, y_train)
# 5. What did the model learn?
print("Intercept:", round(model.intercept_, 1))
for name, coef in zip(X.columns, model.coef_):
print(f"{name}: {coef:.2f}")
# 6. Test it on houses it has never seen
pred = model.predict(X_test)
print("MAE: ", round(mean_absolute_error(y_test, pred), 1))
print("RMSE:", round(np.sqrt(mean_squared_error(y_test, pred)), 1))
print("R²: ", round(r2_score(y_test, pred), 3))
# 7. Predict a new house: 95 m², 3 bedrooms, 4 km from the centre
new_house = pd.DataFrame({"size_m2": [95], "bedrooms": [3], "distance_km": [4]})
print(f"Predicted price: £{model.predict(new_house)[0]:.1f}k")
Intercept: 38.5 size_m2: 1.61 bedrooms: 11.36 distance_km: -3.89 MAE: 13.1 RMSE: 16.3 R²: 0.921 Predicted price: £209.8k
What the output tells us
- The model found the hidden rule. It learned 1.61, 11.36 and −3.89, very close to the true values of 1.6, 12 and −4. It only saw the data, never the rule.
- MAE of 13.1 means predictions are, on average, about £13k away from the real price.
- RMSE of 16.3 is a bit higher than MAE, which means there are a few bigger misses.
- R² of 0.921 means the model explains about 92% of the differences in house prices. That's strong.
Do I need to scale features for linear regression?
For plain LinearRegression, no. The predictions are the same either way. But scaling does help if you want to compare coefficients fairly, and it's required for the regularised versions (Ridge and Lasso) you'll meet in Module 5.
3.9Linear regression in the real world
| Industry | What it predicts | Example features |
|---|---|---|
| Property | House prices and rents | Size, bedrooms, location, garden |
| Retail | Next month's sales | Advertising spend, season, price, promotions |
| Energy | Electricity demand | Temperature, time of day, day of the week |
| HR | Fair salary for a role | Years of experience, skills, location |
| Logistics | Delivery time | Distance, traffic, number of stops |
| Marketing | Return on ad spend | Spend on each channel (TV, social, search) |
In data analyst and BI roles, you'll often use linear regression not only to predict, but to explain: "for every extra £1,000 spent on social ads, sales rise by about £4,200". Being able to say this clearly is a valuable skill.
SummaryKey takeaways
- Linear regression is a supervised algorithm that predicts a number using a straight line.
- The line is y = m × x + c: m is the slope, c is the intercept.
- A residual is the gap between the real value and the prediction.
- Least squares picks the line with the smallest average squared error (MSE).
- MAE and RMSE are errors in real units; R² shows how much variation the model explains.
- Multiple linear regression uses many features; each coefficient shows how much that feature moves the prediction.
- It struggles with curved patterns, outliers, features that move together and predictions outside the training range.
- In scikit-learn:
LinearRegression()→.fit()→.predict().
Check your understanding
Your machine learning roadmap
- 01Introduction to Machine LearningWhat ML is and how it works
- 02Preparing Data for Machine LearningFeatures, encoding, scaling, train/test split
- 03Linear RegressionYou are here
- 04Logistic RegressionPredicting yes or no
- 05Evaluating ModelsAccuracy, precision, recall, overfitting, cross-validation
- 06K-Nearest NeighboursLearning from similar examples
- 07Decision TreesFlowcharts that learn
- 08Random Forest and Gradient BoostingMany models working together
- 09Support Vector MachinesFinding the best boundary
- 10Naive BayesProbability-based classification
- 11Clustering with K-MeansFinding groups without labels
- 12Dimensionality Reduction with PCASimplifying big datasets
- 13Capstone ProjectBuild and present a full ML project
Next module
Logistic Regression