Live build, 12–13 Dec: turn an app agentic, no fee. Register →

Courses / Data Science & ML with AI

Session 5 of 8

Linear Regression in Python with scikit-learn: Predict

Notes

Linear Regression in Python with scikit-learn: Predict Numbers and Measure MAE, RMSE and R²

Course: Data Science & ML with AI

Before you start

You need Python 3 with pandas, numpy and scikit-learn installed (pip install pandas numpy scikit-learn). The examples use the diabetes dataset that ships inside scikit-learn, so nothing is downloaded and no account is needed. You should know what a feature and a target are, and why rows are split into a training set and a held-back test set. Both are explained again in the key concepts table, so a quick read of it is enough preparation.

Keep one question in mind while you read: a model says it explains 45% of something; what does that tell me about how wrong its predictions are? By the end you will be able to answer it with numbers you computed yourself, and to catch an AI assistant that answers it loosely.

Summary

Linear regression predicts a number by adding up the features, each multiplied by a weight called a coefficient, plus a starting value called the intercept. Training chooses the weights that make the squared gaps between predictions and true values on the training rows as small as possible. A model is judged on held-back rows with three numbers: the mean absolute error (the typical miss, in the target’s own units), the root mean squared error (the same idea, with large misses counted more heavily) and R², which compares the model with always guessing the average. A coefficient is a statement about a model, not a proven cause, and when two features move together the individual coefficients become unreliable. This chapter fits a model on the diabetes data, computes each metric by hand to prove you understand it, and trains you to check an AI assistant’s reading of a model.

Key concepts

Term Definition
Linear regression A model that predicts a number as an intercept plus each feature multiplied by its own coefficient.
Coefficient The number a feature is multiplied by. It states how much the prediction changes when that feature rises by one unit while the other features stay fixed.
Intercept The prediction when every feature is zero; the starting value the coefficients adjust.
Least squares The way linear regression is fitted: choose the coefficients that minimise the sum of the squared gaps between true and predicted values on the training rows.
Residual (error) The gap between a row’s predicted value and its true value; it can be positive or negative.
Mean absolute error (MAE) The average size of the residuals, ignoring their sign. It is in the units of the target, and lower is better.
Root mean squared error (RMSE) The square root of the average squared residual. It is in the target’s units like MAE, but squaring makes large misses count more.
R² (coefficient of determination) A score that compares the model with a baseline that always predicts the average target: 1.0 is perfect, 0.0 is no better than that baseline, and it can be negative when the model is worse.
Baseline A deliberately simple prediction, such as the training average for every row, that a real model must beat.
Multicollinearity Two or more features that move closely together, so the model cannot tell their effects apart and their individual coefficients swing unreliably.
Scaled features Columns rewritten to have a mean of zero and a fixed spread, so coefficients are per scaled unit rather than per original unit.

Explanations

The failure, before the explanation

A team trains a model to predict a disease-progression score and shares one line in a status update: “R² is 0.45, so the model is off by 45%.” A manager repeats it as “the model is 55% accurate” and plans a launch around that figure. Both sentences sound reasonable, and both are wrong. R² is not a percentage of error, and no accuracy figure follows from it. On the data you will work with below, the model’s typical miss is about 43 points on a score whose average is about 146, which is roughly 29%, a different number measuring a different thing. You will compute all three and see why they differ. Quoting a metric you cannot recompute is how a project ends up with a number nobody understands.

Predicting a number: what linear regression does

A taxi company charges a flat fee plus a rate per kilometre. If you knew the fee and the rate you could predict any fare from its distance. Suppose instead you only had a pile of past fares and distances, and had to work out the fee and the rate. That is linear regression: it finds the starting value and the rate from examples. With several inputs there is one rate for each. A second picture is a set of sliders: the model starts at a base value and each feature has a slider whose setting says how much the prediction moves for one unit of that feature.

The scikit-learn documentation describes LinearRegression as fitting a linear model with coefficients that minimise the residual sum of squares between the observed targets and the targets predicted by the linear approximation. The predicted value is the intercept plus each coefficient times its feature. After fitting, the coefficients are stored in coef_ and the intercept in intercept_. This is least squares.

Run the first example on the diabetes data. The documentation describes it as 442 patients with ten baseline measurements each and a measure of disease progression one year later as the target; by default the features are mean-centred and rescaled. The block below splits the rows 80/20, fits a model with a single feature, body mass index (bmi), and prints what it learned:

import numpy as np
import pandas as pd
from sklearn.datasets import load_diabetes
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

X, y = load_diabetes(return_X_y=True, as_frame=True)
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)
print(X_train.shape, X_test.shape)

one = LinearRegression().fit(X_train[["bmi"]], y_train)
print(round(one.intercept_, 1), round(one.coef_[0], 1))
print(round(one.predict(pd.DataFrame({"bmi": [0.0]}))[0], 1))
print(round(one.predict(pd.DataFrame({"bmi": [0.1]}))[0], 1))
(353, 10) (89, 10)
152.0 998.6
152.0
251.9

The split gives 353 training rows and 89 test rows. The model’s intercept is 152.0 and its coefficient for bmi is 998.6. The third line shows the intercept’s meaning: a patient whose scaled bmi is 0.0 (the average) gets the prediction 152.0. The fourth line shows the coefficient’s meaning: raising scaled bmi by 0.1 raises the prediction to 251.9, which is 99.9 higher, and 0.1 times 998.6 is 99.86. Because the features are scaled, 998.6 is the change per one scaled unit, not per kilogram per square metre.

Now use all ten features. Before reading its results, measure a baseline. The baseline is a DummyRegressor, which the documentation describes as a simple baseline to compare with real regressors; with its mean strategy it always predicts the mean of the training set.

MAE, RMSE and R²: three ways to score a number

Four patients’ true scores are 100, 150, 200 and 250, and a model predicts 110, 140, 230 and 240. The residuals (prediction minus truth) are +10, -10, +30 and -10. How wrong is the model? The three standard answers, worked by hand:

  • MAE: ignore signs and average: (10 + 10 + 30 + 10) / 4 = 15.0. On average the model misses by 15 points.
  • RMSE: square each residual (100, 100, 900, 100), average them to 300, take the square root: about 17.32. The single miss of 30 pulls it above the MAE of 15 because squaring weights large misses more.
  • R²: compare the model’s squared misses with those of a baseline that always predicts the average, 175. The baseline’s squared misses add up to 12,500 and the model’s to 1,200, so R² = 1 - 1,200 / 12,500 = 0.904.

Check the worked example in code:

from sklearn.metrics import r2_score

y_true = np.array([100, 150, 200, 250])
y_pred = np.array([110, 140, 230, 240])
err = y_pred - y_true
print(err.tolist())
print(np.abs(err).mean(), (err**2).mean(), round(float(np.sqrt((err**2).mean())), 2))
print(r2_score(y_true, y_pred))
[10, -10, 30, -10]
15.0 300.0 17.32
0.904

The first line is the residuals. The second is the MAE (15.0), the mean squared error (300.0) and the RMSE (17.32). The third is R², 0.904, matching the hand calculation.

The scikit-learn documentation describes the mean absolute error as a non-negative value whose best value is 0.0, and lists a root mean squared error loss beside it, which this chapter computes as the square root of the mean squared residual, in the same units as the target. For R² it says the best possible score is 1.0, that it can be negative because a model can be arbitrarily worse, and that a constant model always predicting the average target gets 0.0 when the target is not constant. So R² is a comparison with the baseline, not a percentage of anything.

Metric Units Best value Reads as Reacts strongly to
MAE the target’s 0 The typical miss Nothing in particular; all misses count in proportion
RMSE the target’s 0 A typical miss that leans toward big ones A few very large misses
R² none 1 How much better than always guessing the average A model worse than the average (it goes negative)

Fitting on all ten features and scoring on held-back rows

The next block computes the baseline and then the full model, always scoring on the 89 test rows:

from sklearn.dummy import DummyRegressor
from sklearn.metrics import mean_absolute_error, root_mean_squared_error

base = DummyRegressor(strategy="mean").fit(X_train, y_train)
bp = base.predict(X_test)
print("baseline MAE, RMSE, R2:", round(mean_absolute_error(y_test, bp), 1),
      round(root_mean_squared_error(y_test, bp), 1), round(r2_score(y_test, bp), 3))

model = LinearRegression().fit(X_train, y_train)
pred = model.predict(X_test)
print("intercept:", round(model.intercept_, 1))
print(pd.Series(model.coef_, index=X.columns).round(1).to_string())

mae = mean_absolute_error(y_test, pred)
rmse = root_mean_squared_error(y_test, pred)
r2 = r2_score(y_test, pred)
print("model MAE, RMSE, R2:", round(mae, 1), round(rmse, 1), round(r2, 3))
print("train MAE, R2:", round(mean_absolute_error(y_train, model.predict(X_train)), 1),
      round(r2_score(y_train, model.predict(X_train)), 3))
print("test target mean, std:", round(y_test.mean(), 1), round(y_test.std(), 1))
baseline MAE, RMSE, R2: 64.0 73.2 -0.012
intercept: 151.3
age     37.9
sex   -242.0
bmi    542.4
bp     347.7
s1    -931.5
s2     518.1
s3     163.4
s4     275.3
s5     736.2
s6      48.7
model MAE, RMSE, R2: 42.8 53.9 0.453
train MAE, R2: 43.5 0.528
test target mean, std: 145.8 73.2

Read the results in order. The baseline, always predicting the training average, has an MAE of 64.0 on the test rows and an R² of -0.012, slightly below zero because the test average differs from the training average. That is the bar. The model’s test MAE is 42.8, which is 21.2 points better, and its RMSE is 53.9, higher than its MAE of 42.8 because a few rows are missed by a lot. Its R² is 0.453: it removes about 45% of the squared error that the baseline makes, which is a statement about squared error and not a percentage of wrong predictions. On the training rows the R² is higher, 0.528, as is normal: a model fits the rows it learned from a little better than rows it did not.

The test target has an average of 145.8 and a standard deviation of 73.2, which puts the baseline’s RMSE (73.2) and the target’s spread on the same footing. The error to quote is “about 43 points on a score averaging about 146”, which is a fact about the model’s misses, not about R².

Recompute one metric by hand

Whenever someone quotes a metric, rebuild it from the residuals. It takes four lines and removes any doubt about what the number means. This is the check the chapter’s AI section uses:

resid = pred - y_test.to_numpy()
print(round(np.abs(resid).mean(), 1))
print(round(1 - (resid**2).sum() / ((y_test - y_test.mean()) ** 2).sum(), 3))
print(round(np.abs(resid).max(), 1), (np.abs(resid) > 100).sum(), len(resid))
print(round(mae / y_test.mean(), 3))
print(pd.DataFrame({"actual": y_test.to_numpy()[:5], "predicted": pred[:5].round(1),
                    "error": resid[:5].round(1)}).to_string())
42.8
0.453
154.5 5 89
0.294
   actual  predicted  error
0   219.0      139.5  -79.5
1    70.0      179.5  109.5
2   202.0      134.0  -68.0
3   230.0      291.4   61.4
4   111.0      123.8   12.8

The first two lines reproduce the library’s MAE (42.8) and R² (0.453) from the residuals alone, so you know what each number measures. The third line says the largest miss is 154.5 points and 5 of the 89 rows are missed by more than 100. That is the reason the RMSE is above the MAE. The fourth line is the MAE as a share of the average target, 0.294, the honest answer to “how far off is it in percentage terms”. The table shows the first five test rows. For the first one the model predicts 139.5 for a patient whose true score was 219, so the error, prediction minus truth, is -79.5: a miss low by 79.5 points.

Reading coefficients, and why correlated features break them

A recipe’s cost depends on flour and sugar. If someone always buys them together, you cannot tell from receipts how much each one adds to the bill, because they never vary alone. This is multicollinearity, and linear regression suffers from it. The scikit-learn user guide warns that least-squares coefficients assume the features are independent of one another; when some features are strongly correlated, small random errors in the target can swing the estimates widely.

The diabetes table has a pair like that: s1 (total serum cholesterol) and s2 (low-density lipoproteins) are measured on the same blood sample. Check how they move together, then refit without s2:

print(round(X["s1"].corr(X["s2"]), 3))
X_train_no_s2 = X_train.drop(columns="s2")
no_s2 = LinearRegression().fit(X_train_no_s2, y_train)
print(round(pd.Series(no_s2.coef_, index=X_train_no_s2.columns)["s1"], 1))
p2 = no_s2.predict(X_test.drop(columns="s2"))
print(round(mean_absolute_error(y_test, p2), 1), round(r2_score(y_test, p2), 3))
0.897
-316.7
42.9 0.453

The correlation between s1 and s2 is 0.897. Dropping s2 moves the coefficient of s1 from -931.5 to -316.7, while the test MAE barely moves (42.9 against 42.8) and the R² stays at 0.453. The predictions are about as good, but the story the coefficient tells is very different. The right reading is that a coefficient states how the prediction changes with that feature while the others stay fixed, so with a close partner present it is not a reliable measure of that feature’s own importance. A coefficient also describes the model and says nothing about cause.

With AI: check an assistant’s explanation of a model

Ask an assistant to “explain this model’s results to a non-technical manager” and you get a confident summary. This is a plausible one for the model above:

Assistant’s summary

  1. “The R² of 0.453 means the model’s predictions are off by about 45% on average.”
  2. “The coefficient for s1 is -931.5, the largest in size, so total cholesterol is the strongest protective factor: raising it lowers disease progression.”
  3. “The model is clearly useful: its error is much smaller than the baseline’s.”

Use the hand check from this chapter on each claim.

Claim 1. Recompute the error from the residuals, as you did above: the MAE is 42.8 points, which is 0.294 of the average target, about 29%, not 45%. The 0.453 is R², the share of the baseline’s squared error that the model removes. The assistant gave a wrong reading of a correct number.

Claim 2. The coefficient is big only in the presence of its close partner. The correlation of s1 with s2 is 0.897, and refitting without s2 moves the coefficient to -316.7 with almost the same test error. So the large figure is not a reliable measure of s1 on its own, and “protective factor” is a causal claim that a coefficient cannot support.

Claim 3. This one holds, and the check is a number: the model’s MAE of 42.8 is 21.2 points better than the baseline’s 64.0 on the same 89 test rows. It is “clearly useful” only in that narrow sense; with a typical miss near 43 on a score averaging 146, a clinic would still want to ask whether that is accurate enough for the decision.

Two of three claims failed the check, in the same confident voice as the one that passed. The skill is to rebuild each number from residuals and a baseline before repeating it.

Claim type Check to run What the check shows here
“The error is X%” Recompute MAE from residuals, divide by the average target 0.294 (MAE over the average target), not 0.45
“This feature matters most” Refit without a correlated partner and compare s1 moves from -931.5 to -316.7
“The model beats the baseline” Compare model and baseline on the same test rows 42.8 against 64.0

Three situations you will meet, and what they mean for your work

Before the table, three situations:

  1. A report says “R² = 0.9” with no mention of which rows it was measured on.
  2. A model’s RMSE is much higher than its MAE, and a stakeholder asks whether something is wrong.
  3. Two features are nearly copies of one another, and a stakeholder wants to know which one drives the prediction.
What you see What it means What to do
R² with no rows named (situation 1) It may have been measured on training rows, where it runs higher Ask for the test-set figure and a baseline, then recompute it
RMSE well above MAE (situation 2) A few rows are missed by a lot List the largest residuals and look at those rows
Near-duplicate features (situation 3) Their coefficients share the credit unpredictably Refit without one, compare coefficients and errors, and avoid causal wording

Flashcards

Say the answer aloud before revealing it. Speaking it is what exposes the gaps that reading past a written answer hides.

What does linear regression predict, and how?

It predicts a number on a scale. The prediction is an intercept plus each feature multiplied by its own coefficient, with the coefficients chosen to make the squared training errors as small as possible.

What do `coef_` and `intercept_` hold after fitting?

coef_ holds one coefficient per feature and intercept_ holds the starting value. The intercept is the prediction when every feature is zero, and each coefficient is the change per one unit of its feature with the others fixed.

How is MAE calculated, and what does it tell you?

Take each residual, drop its sign, and average. The result is in the target’s units and reads as the typical miss, so an MAE of 42.8 means predictions are off by about 43 points on average.

Why is RMSE larger than MAE on the same predictions?

RMSE squares each residual before averaging, so a few big misses weigh heavily. When the errors are uneven RMSE sits above MAE, and the gap grows with the size of the largest misses.

What does an R² of 0 mean, and what does a negative R² mean?

Zero means the model does no better than always predicting the average target. A negative value means it does worse than that, which can happen on test rows.

Is an R² of 0.45 an error of 45%?

No. R² is the share of the baseline’s squared error that the model removes. The error as a share of the target comes from the MAE divided by the average target, which here is about 29%.

Why score a regression model on held-back rows and against a baseline?

Training rows flatter the model, since it was fitted to them, and a number alone has no meaning without a bar to clear. The held-back rows and the baseline show whether it learned a transferable pattern.

Why are the diabetes coefficients not in kilograms or years?

The dataset’s features are mean-centred and rescaled by default, so each coefficient is the change in the prediction per one scaled unit, not per original unit.

What is multicollinearity and what does it do to coefficients?

It is two or more features moving closely together, such as s1 and s2 with a correlation of 0.897. The model cannot separate their effects, so each coefficient can swing widely, like s1 moving from -931.5 to -316.7.

How would you check an assistant's claim that the model "is off by X%"?

Rebuild the error from the residuals: take the MAE, divide it by the average target, and compare it with X. If the assistant has quoted R² as an error percentage, the numbers will not match.

Model answer

The question: “You have built a regression model. How do you tell an examiner it is any good?” A strong answer hits five beats, in this order:

  1. Hold-out — score on rows the model did not train on.
  2. Baseline — compare with always predicting the average.
  3. Error in units — report MAE, and RMSE for the effect of large misses.
  4. R² — read it as the share of the baseline’s error removed, not a percentage of error.
  5. Coefficients — read them with caution when features are correlated.

“I score on held-back rows, because training rows flatter a model. I compare with a baseline that always predicts the average, because a number means nothing without a bar to clear. I report the mean absolute error in the target’s own units as the typical miss, and the root mean squared error to show how much a few large misses matter. I read R² as how much of the baseline’s squared error the model removes, so 0.45 is a comparison, never an error of 45%. Finally I treat coefficients with care: with correlated features they share credit unpredictably, so I refit without a partner before I say which feature matters, and I do not read them as causes.”

Missing a beat is a failure state. Without the hold-out the score is flattered. Without the baseline no figure has a meaning. Without error in units nobody learns how far off a prediction can be. Without a correct reading of R² a manager hears 45% error. Without care over coefficients a feature gets credit or blame it has not earned.

Why this matters

  • Honest reporting. Stating a typical miss in the target’s own units, next to a baseline, is how a model result becomes something a decision-maker can use.
  • Catching loose statements. Metrics are often misquoted, by people and by assistants. Being able to rebuild a number from residuals is the defence.
  • Explaining models. Stakeholders ask which feature matters. Knowing how correlated features distort coefficients keeps the answer from being a confident mistake.
  • A first benchmark. Linear regression is quick to fit and easy to read, so it is a sensible baseline for any model you build in a later chapter.

After this unit

You can now fit a linear regression, score it with MAE, RMSE and R², and challenge an explanation of it. The next chapter changes the target from a number to a label: classification with logistic regression, where you will meet the confusion matrix, precision and recall.

Quiz

Answers are not marked on this page yet. Work through the questions and check the written ones against the criteria printed with each question. The answer key is kept back for now.

Quiz — Linear Regression in Python with scikit-learn: Predict Numbers and Measure MAE, RMSE and R²

Instructions: Eight multiple-choice questions. Pick one option per question. Work closed-book, then compare your letters with the answer key, which is held separately and holds the reasons.


1. [recall] A regression model scores an R² of 0.0 on held-back rows. What does that mean?

a) The model explains all of the variation in the target and its error is exactly zero b) The model’s average error on the held-back rows works out to zero points c) Every prediction the model makes is wrong by exactly the same amount d) The model does no better than a guess of the average target value for every row


2. [application] A model’s errors on four test rows are +5, -15, +10 and -10 points. What is its mean absolute error?

a) -2.5, because the signed errors are added up and divided by the four rows b) 10.0, because the sizes of the four errors are averaged without their signs c) 10.6, because the squared errors are averaged and then the square root is taken d) 112.5, because each error is squared and the squares are averaged


3. [scenario] An assistant tells your manager: “The model’s R² of 0.45 means its predictions are off by 45% on average.” You need to find out whether that is right. What would you do?

a) Retrain the model with unscaled features and see whether the R² figure changes b) Rerun the metric on the training rows to see whether 0.45 appears there as well c) Recompute the MAE from the residuals and divide it by the average target to see the real share d) Accept the claim, since R² between 0 and 1 can be read directly as a percentage error


4. [recall] Which statement correctly compares RMSE with MAE on the same predictions?

a) RMSE squares each error before averaging, so a few very large misses raise it more than MAE b) RMSE ignores the sign of each error while MAE keeps it, so RMSE is always the larger one c) RMSE is measured in squared units of the target while MAE is measured in the target’s units d) RMSE is calculated only on training rows while MAE is calculated only on the test rows


5. [application] In a fitted model with all ten diabetes features, the coefficient of bmi is 542.4. The features are scaled. If bmi rises by 0.1 and every other feature stays fixed, what happens to the prediction?

a) It rises by 542.4, because the coefficient is the change for any rise in bmi b) It rises by 5.4, because the change has to be divided by the ten features in the model c) It rises by about 54.2, because the change is 0.1 times the coefficient of 542.4 d) It falls by about 54.2, because a rise in a measurement lowers the progression score


6. [scenario] An assistant says the coefficient of s1, at -931.5, proves cholesterol is the strongest protective factor. You refit without s2, which has a correlation of 0.897 with s1. The s1 coefficient becomes -316.7 and the test error barely changes. What should you conclude?

a) The first model was fitted on too few rows, so its coefficients should be discarded entirely b) Correlated features share credit unpredictably, so one coefficient cannot be read as a separate cause c) The second model is the correct one, so -316.7 now measures the true effect of cholesterol d) The change proves that s2 has no effect on the target and can always be left out


7. [recall] What does LinearRegression try to minimise when it is fitted?

a) The largest single gap between a prediction and its true value on the training rows b) The number of features that receive a coefficient other than zero in the final model c) The R² score of the model, measured on the rows that were held back for testing d) The sum of the squared gaps between true and predicted values on the training rows


8. [application] A baseline that always predicts the training average has an MAE of 64.0 on the test rows. A fitted model has an MAE of 42.8 on the same rows. Which statement is correct?

a) The model beats the baseline, because its typical miss is 21.2 points smaller b) The baseline wins, because a model with an MAE above zero has not learned anything c) Neither can be judged, because an MAE has meaning only when it is a percentage d) Neither beats the other, because both errors are small next to the average target of 145.8

Want help building this with someone?

Tell us what you are working on and we will write back about a mentor-led cohort, live sessions or 1:1 training. It is only an enquiry: you choose whether to go further.

Ask about mentor-led training

TechEazy Consulting training material — not affiliated with or endorsed by pandas, scikit-learn or any other project or company named in this course.