A4.3.1 Predicting numbers with linear regression
HL onlyCommand term: Explain1. Fit the line yourself
An ice-cream shop recorded the temperature (independent / predictor variable, x) and ice creams sold (dependent / response variable, y) on 12 days. Move the sliders to fit a line. The red lines are the errors (residuals): make them as small as possible.
| Sum of squared errors (smaller = better) | |
| r² (closer to 1 = better fit) |
2. How the computer finds the best line (least squares)
Five students: hours revising (x) and test score out of 10 (y). Click Next to calculate the line of best fit step by step.
3. How well does the model fit? Exploring r²
Choose a data set and add noise. The line of best fit and r² update automatically.
4. Interpret a real model
An estate agent's model:
Score: 0 /
In this lab you practise the least squares method, the meaning of slope and intercept, r², residuals and the danger of extrapolation. Work through the sections in order: run it, read it, change it, then extend it.
1. Set up in PyCharm
- Open PyCharm and choose New Project (a pure Python project; any recent Python 3 works). Name it
shelfwise_ai. - Right-click the project folder → New → Python File, and give it the file name shown below.
- Press Copy code below and paste it into the empty file (or press Download .py and drag the file into the project).
- Right-click inside the editor and choose Run (Windows Shift+F10, Mac Ctrl+R). The output appears in the Run window at the bottom.
- No extra libraries are needed: the lab uses only Python's built-in modules, so you can see exactly how the algorithm works.
2. Copy and run the program
# ShelfWise AI - Lab A4.3.1: predicting weekly loans with linear regression
# x = copies of a book on display, y = loans of that book in a week
data = [(2, 6), (3, 7), (4, 11), (5, 10), (6, 15), (8, 16), (9, 22), (10, 19), (12, 27), (14, 28)]
PREDICT_FOR = [7, 11, 20] # display sizes to predict
n = len(data)
xs = [x for x, _ in data]
ys = [y for _, y in data]
mean_x, mean_y = sum(xs) / n, sum(ys) / n
# least squares: the line that makes the total squared error as small as possible
slope = sum((x - mean_x) * (y - mean_y) for x, y in data) / sum((x - mean_x) ** 2 for x in xs)
intercept = mean_y - slope * mean_x
print(f"Regression line: loans = {intercept:.2f} + {slope:.2f} x copies")
print(f" slope: each extra copy on display adds about {slope:.2f} loans a week")
print(f" intercept: with 0 copies the line predicts {intercept:.2f} loans")
def predict(x):
return intercept + slope * x
# how good is the fit? r^2 = 1 - (unexplained variation / total variation)
ss_res = sum((y - predict(x)) ** 2 for x, y in data)
ss_tot = sum((y - mean_y) ** 2 for y in ys)
r2 = 1 - ss_res / ss_tot
print(f" r^2 = {r2:.3f} ({r2:.1%} of the variation in loans is explained by copies)")
print("\nResiduals (actual - predicted):")
for x, y in data:
bar = "+" * min(30, round(max(0, y - predict(x)) * 4)) or "-" * min(30, round(max(0, predict(x) - y) * 4))
print(f" x={x:2} actual {y:2} predicted {predict(x):5.1f} residual {y - predict(x):+5.2f} {bar}")
print("\nPredictions:")
for x in PREDICT_FOR:
note = " (outside the data: extrapolation, be careful)" if not min(xs) <= x <= max(xs) else ""
print(f" {x} copies -> {predict(x):.1f} loans a week{note}")
3. Expected output
The program uses a fixed random seed, so with the same settings you should see exactly this output.
Regression line: loans = 2.04 + 1.93 x copies slope: each extra copy on display adds about 1.93 loans a week intercept: with 0 copies the line predicts 2.04 loans r^2 = 0.953 (95.3% of the variation in loans is explained by copies) Residuals (actual - predicted): x= 2 actual 6 predicted 5.9 residual +0.11 x= 3 actual 7 predicted 7.8 residual -0.82 --- x= 4 actual 11 predicted 9.7 residual +1.26 +++++ x= 5 actual 10 predicted 11.7 residual -1.67 ------- x= 6 actual 15 predicted 13.6 residual +1.40 ++++++ x= 8 actual 16 predicted 17.4 residual -1.45 ------ x= 9 actual 22 predicted 19.4 residual +2.63 +++++++++++ x=10 actual 19 predicted 21.3 residual -2.30 --------- x=12 actual 27 predicted 25.2 residual +1.85 +++++++ x=14 actual 28 predicted 29.0 residual -1.00 ---- Predictions: 7 copies -> 15.5 loans a week 11 copies -> 23.2 loans a week 20 copies -> 40.6 loans a week (outside the data: extrapolation, be careful)
4. Read the output
Answer each question from your own output before you open the answer.
What does the slope 1.93 mean in this context?
What does r² = 0.953 tell you?
Why is the prediction for 20 copies marked with a warning?
5. Change it and predict
For each change: write down your prediction first, then edit the setting at the top of the program, run it, and compare. Change the setting back before the next task.
Task 1. Change (12, 27), (14, 28)] → (12, 27), (14, 28), (6, 40)]
Add an unusual week, (6, 40), to the end of the data (a book that went viral). What happens to r² and the line?
Check your prediction
r² falls from 0.953 to 0.391 and the intercept jumps from 2.04 to 6.00. One outlier pulls the whole least squares line towards it, because errors are squared. Check outliers before fitting.
Output with this change:
Regression line: loans = 6.00 + 1.71 x copies slope: each extra copy on display adds about 1.71 loans a week intercept: with 0 copies the line predicts 6.00 loans r^2 = 0.391 (39.1% of the variation in loans is explained by copies) Residuals (actual - predicted): x= 2 actual 6 predicted 9.4 residual -3.42 -------------- x= 3 actual 7 predicted 11.1 residual -4.13 ----------------- x= 4 actual 11 predicted 12.8 residual -1.84 ------- x= 5 actual 10 predicted 14.5 residual -4.54 ------------------ x= 6 actual 15 predicted 16.3 residual -1.25 ----- x= 8 actual 16 predicted 19.7 residual -3.67 --------------- x= 9 actual 22 predicted 21.4 residual +0.62 ++ x=10 actual 19 predicted 23.1 residual -4.09 ---------------- x=12 actual 27 predicted 26.5 residual +0.49 ++ x=14 actual 28 predicted 29.9 residual -1.92 -------- x= 6 actual 40 predicted 16.3 residual +23.75 ++++++++++++++++++++++++++++++ Predictions: 7 copies -> 18.0 loans a week 11 copies -> 24.8 loans a week 20 copies -> 40.2 loans a week (outside the data: extrapolation, be careful)
Task 2. Change PREDICT_FOR = [7, 11, 20] → PREDICT_FOR = [0, 100]
Set PREDICT_FOR = [0, 100]. Are these predictions sensible?
Check your prediction
Both are extrapolations. 0 copies gives 2.0 loans, which is impossible if there are no copies; 100 copies gives about 195 loans a week, which assumes demand never runs out. The model is only trustworthy inside the range of its data.
Output with this change:
Regression line: loans = 2.04 + 1.93 x copies slope: each extra copy on display adds about 1.93 loans a week intercept: with 0 copies the line predicts 2.04 loans r^2 = 0.953 (95.3% of the variation in loans is explained by copies) Residuals (actual - predicted): x= 2 actual 6 predicted 5.9 residual +0.11 x= 3 actual 7 predicted 7.8 residual -0.82 --- x= 4 actual 11 predicted 9.7 residual +1.26 +++++ x= 5 actual 10 predicted 11.7 residual -1.67 ------- x= 6 actual 15 predicted 13.6 residual +1.40 ++++++ x= 8 actual 16 predicted 17.4 residual -1.45 ------ x= 9 actual 22 predicted 19.4 residual +2.63 +++++++++++ x=10 actual 19 predicted 21.3 residual -2.30 --------- x=12 actual 27 predicted 25.2 residual +1.85 +++++++ x=14 actual 28 predicted 29.0 residual -1.00 ---- Predictions: 0 copies -> 2.0 loans a week (outside the data: extrapolation, be careful) 100 copies -> 194.7 loans a week (outside the data: extrapolation, be careful)
6. Extended activity: Multiple linear regression for ShelfWise
A longer project for homework or a double lesson. Save it as a new file so you keep the original.
- Add a second feature to each week: whether the book was promoted on the website (0 or 1). Invent 15 data points where promotion adds loans.
- Fit loans = a + b x copies + c x promoted. Hint: for two features you can solve the normal equations, or use the scikit-learn version below.
- Compare r² with and without the promotion feature.
- Write a recommendation for the librarian, with numbers: is it better to buy one more copy or to promote the book?
Success criteria
- The model includes both features and reports r².
- Slope values are interpreted in context.
- Your recommendation mentions the limits of the data (extrapolation, outliers).
7. Level up (optional): the same with scikit-learn
This optional part uses scikit-learn, the library professionals use. Install it once in PyCharm: Settings → Project → Python Interpreter → + → search scikit-learn → Install Package. Or type in PyCharm's Terminal: pip install scikit-learn. If the download is slow in China, use a mirror: pip install scikit-learn -i https://pypi.tuna.tsinghua.edu.cn/simple. Numbers may differ slightly between library versions.
# Optional: the same regression with scikit-learn (pip install scikit-learn)
from sklearn.linear_model import LinearRegression
from sklearn.metrics import r2_score
data = [(2, 6), (3, 7), (4, 11), (5, 10), (6, 15), (8, 16), (9, 22), (10, 19), (12, 27), (14, 28)]
X = [[x] for x, _ in data] # scikit-learn wants a list of feature rows
y = [y for _, y in data]
model = LinearRegression().fit(X, y)
print(f"loans = {model.intercept_:.2f} + {model.coef_[0]:.2f} x copies")
print(f"r^2 = {r2_score(y, model.predict(X)):.3f}")
print("prediction for 7 copies:", round(model.predict([[7]])[0], 1))
Output on our computer (scikit-learn 1.9):
loans = 2.04 + 1.93 x copies r^2 = 0.953 prediction for 7 copies: 15.5
Compare this with your from-scratch version: which results match, and why might the library choose slightly different values?
Learning objectives
By the end of this page you should be able to:
- Explain how linear regression predicts a continuous outcome.
- Distinguish between the independent (predictor) and dependent (response) variables.
- Explain the significance of the slope and intercept in the regression equation.
- Use a regression equation to make predictions.
- Explain how r² measures how well the model fits the data, and the limitations of linear regression.
What is linear regression?
Linear regression is a supervised learning algorithm that predicts a continuous numerical outcome (price, temperature, score, sales) by fitting a straight line through labelled training data.
- Independent (predictor) variable, x: the input used to make the prediction, e.g. temperature.
- Dependent (response) variable, y: the output being predicted; it depends on x, e.g. ice creams sold.
The regression equation
ŷ = a + b x
- Slope (gradient) b: how much the predicted y changes for each one-unit increase in x. Positive b → y increases with x; negative b → y decreases; b near 0 → little relationship.
- Intercept a: the predicted value of y when x = 0 (where the line crosses the y-axis). It may have no real-world meaning if x = 0 is outside the data (a house of 0 m²).
- Some texts write it as y = mx + c or y = β₀ + β₁x; the meaning is the same.
Least squares
The algorithm chooses a and b to minimise the sum of squared residuals, where a residual = actual y − predicted y:
b = Σ(x − x̄)(y − ȳ) ÷ Σ(x − x̄)² a = ȳ − b x̄
Measuring fit: r² (coefficient of determination)
r² = 1 − (sum of squared residuals ÷ total sum of squares)
- r² is between 0 and 1 (for the line of best fit). It is the proportion of the variation in y explained by x.
- r² = 0.81 → 81% of the variation in price is explained by floor area; the other 19% is due to other factors or noise.
- r² near 1 → points lie close to the line; near 0 → the line explains little.
Limitations
- Assumes a linear relationship: a curved pattern gives a poor fit, so plot the data first.
- Extrapolation (predicting far outside the range of the training data) is unreliable.
- Outliers can pull the line strongly.
- Correlation is not causation: a good fit doesn't prove x causes y.
Use the 中文 button at the top to show or hide the Chinese terms.
| Term | 中文 | Meaning |
|---|
Choose an answer. You get instant feedback.
Score: 0 /
Write your answer first, then reveal the markscheme. These are exam-style practice questions written for this site.
1. A model predicts a car's fuel consumption from its engine size. Identify the independent and dependent variables. [2]
2. A regression model is: exam score = 35 + 6 × hours revised. Explain the significance of the slope and the intercept. [4]
3. Using the model in question 2, predict the score of a student who revises for 7 hours. Show your working. [2]
4. The model in question 2 has r² = 0.36. Explain what this indicates. [2]
5. Explain two limitations of using linear regression to make predictions. [4]