CadetX
CX Learn | Complete Machine Learning Guide
Scikit-Learn · Python
CadetX logo CadetX CX Learn
ML-101 · Module 3 Beginner about 35 minutes 10 Lessons Prereq: Modules 1 and 2

Linear Regression

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²)506065758090100110120135
Price (£k)130150148175185200228240265290

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:

y = m × x + c
LetterNameWhat it meansIn our example
yTargetThe thing we want to predictHouse price
xFeatureThe information we knowHouse size
mSlope (or coefficient)How much y goes up when x goes up by 1Extra £ for each extra m²
cInterceptThe value of y when x is 0, where the line startsThe "starting price"
A straight line. The intercept c is where the line crosses the vertical axis. The slope m is the rise divided by the run. x (feature) y (target) run rise slope m = rise ÷ run intercept c: where the line starts
Figure 1. The intercept tells you where the line starts. The slope tells you how steep it is: how far it goes up for every step to the right.

For our houses, linear regression finds this line:

Price = 1.93 × Size + 30.3

In plain English: start at £30,300 and add about £1,930 for every square metre. So for a 95 m² house:

Price = 1.93 × 95 + 30.3 = £213.6k

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).

Residual = Actual value − Predicted value
House size against price with the line of best fit. Red dashed lines show the residuals: the gap between each real price and the line.100150200250300406080100120140House size (m²)Price (£k)Residual: £7.8k below the line
Figure 2. Each red dashed line is a residual. A point above the line has a positive residual (the house sold for more than predicted); a point below has a negative one.

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:

  1. Work out the residual for every point.
  2. Square each residual (multiply it by itself).
  3. Take the average. This is the Mean Squared Error (MSE).
  4. 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

Error (MSE)

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:

HouseActual (£k)Predicted (£k)ErrorError²
A200210−10100
B250240+10100
C300330−30900
MeasureHow to work it outOur exampleWhat 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.7Used to train the model. Hard to read because the units are squared.
RMSE
Root Mean Squared Error
Square root of MSE√366.7 = 19.1Back 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.
R squared scale from 0 to 1. Near 0 is poor, around 0.5 is okay, above 0.8 is strong. 00.51 Poor: barely better than guessing Okay Strong: explains most of it 0.92
Figure 3. R² runs from 0 to 1 (it can even go below 0 if a model is truly terrible). The marker shows our Python model's score of 0.92 from lesson 3.8. What counts as "good" depends on the problem: predicting human behaviour rarely gets as high as predicting physics.

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:

Price = c + m₁ × Size + m₂ × Bedrooms + m₃ × Distance

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:

FeatureCoefficientWhat it means in plain English
Size (m²)+1.61Each extra square metre adds about £1,610
Bedrooms+11.36Each extra bedroom adds about £11,360, for a house of the same size and location
Distance to centre (km)−3.89Each extra kilometre from the centre takes off about £3,890
Intercept38.5The 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.

Car stopping distance against speed. The points curve upwards, so a straight line fits badly while a curve fits well.0204060801001020304050607080Speed (mph)Stopping distance (m)Straight line: misses the patternCurve: fits well
Figure 4. A straight line (red) can't follow a curved pattern. It predicts too short at the lowest and highest speeds, and too long in the middle. A curved model (green) fits much better. Always plot your data first.
ProblemWhat happensWhat to do
Curved relationshipThe line misses the pattern, as aboveAdd curved features (polynomial regression) or use a tree-based model
OutliersBecause errors are squared, one extreme point can drag the whole line towards itCheck outliers first, as you learned in Module 2
Features that move togetherIf 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 dataThe 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.

house_prices.py
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")
Output
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

IndustryWhat it predictsExample features
PropertyHouse prices and rentsSize, bedrooms, location, garden
RetailNext month's salesAdvertising spend, season, price, promotions
EnergyElectricity demandTemperature, time of day, day of the week
HRFair salary for a roleYears of experience, skills, location
LogisticsDelivery timeDistance, traffic, number of stops
MarketingReturn on ad spendSpend 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

  1. 01
    Introduction to Machine LearningWhat ML is and how it works
  2. 02
    Preparing Data for Machine LearningFeatures, encoding, scaling, train/test split
  3. 03
    Linear RegressionYou are here
  4. 04
    Logistic RegressionPredicting yes or no
  5. 05
    Evaluating ModelsAccuracy, precision, recall, overfitting, cross-validation
  6. 06
    K-Nearest NeighboursLearning from similar examples
  7. 07
    Decision TreesFlowcharts that learn
  8. 08
    Random Forest and Gradient BoostingMany models working together
  9. 09
    Support Vector MachinesFinding the best boundary
  10. 10
    Naive BayesProbability-based classification
  11. 11
    Clustering with K-MeansFinding groups without labels
  12. 12
    Dimensionality Reduction with PCASimplifying big datasets
  13. 13
    Capstone ProjectBuild and present a full ML project